blob: 3cf7baab95017256eec790fe51237c2a6c05e52f [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"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCall36f893c2011-01-28 11:13:47 +000020#include "CGCleanup.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/SourceManager.h"
27#include "clang/Basic/FileManager.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000028
29#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000030#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000031#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000032#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000033#include "llvm/ADT/StringMap.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"
Micah Villmow25a6a842012-10-08 16:25:52 +000036#include "llvm/DataLayout.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000037
Chris Lattner5f9e2722011-07-23 10:55:15 +000038#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000039
40
Chris Lattnerdce14062008-06-26 04:19:03 +000041using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000042using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000043
Chris Lattner0f984262008-03-01 08:50:34 +000044
Chris Lattner0f984262008-03-01 08:50:34 +000045namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000046/// Class that lazily initialises the runtime function. Avoids inserting the
47/// types and the function declaration into a module if they're not used, and
48/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000049class LazyRuntimeFunction {
50 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000051 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000052 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000053 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000054 public:
David Chisnall81a65f52011-03-26 11:48:37 +000055 /// Constructor leaves this class uninitialized, because it is intended to
56 /// be used as a field in another class and not all of the types that are
57 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000058 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
59
David Chisnall81a65f52011-03-26 11:48:37 +000060 /// Initialises the lazy function with the name, return type, and the types
61 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000062 END_WITH_NULL
63 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000064 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000065 CGM =Mod;
66 FunctionName = name;
67 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000068 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000069 va_list Args;
70 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000071 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000072 ArgTys.push_back(ArgTy);
73 va_end(Args);
74 // Push the return type on at the end so we can pop it off easily
75 ArgTys.push_back(RetTy);
76 }
David Chisnall81a65f52011-03-26 11:48:37 +000077 /// Overloaded cast operator, allows the class to be implicitly cast to an
78 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000079 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000080 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000081 if (0 == FunctionName) return 0;
82 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000083 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000084 ArgTys.pop_back();
85 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
86 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000087 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000088 // We won't need to use the types again, so we may as well clean up the
89 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000090 ArgTys.resize(0);
91 }
92 return Function;
93 }
David Chisnall789ecde2011-05-23 22:33:28 +000094 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000095 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000096 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000097
David Chisnall9f6614e2011-03-23 16:36:54 +000098};
99
100
David Chisnall81a65f52011-03-26 11:48:37 +0000101/// GNU Objective-C runtime code generation. This class implements the parts of
John McCallf7226fb2012-07-12 02:07:58 +0000102/// Objective-C support that are specific to the GNU family of runtimes (GCC,
103/// GNUstep and ObjFW).
David Chisnall9f6614e2011-03-23 16:36:54 +0000104class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000105protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000106 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000107 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000108 /// strut objc_super. Used for sending messages to super. This structure
109 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000110 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000111 /// struct objc_super*. The type of the argument to the superclass message
112 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000113 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000114 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
115 /// SEL is included in a header somewhere, in which case it will be whatever
116 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000117 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000118 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
119 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000120 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000121 /// Pointer to i8 - LLVM type of char*, for all of the places where the
122 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000123 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000124 /// Instance Method Pointer type. This is a pointer to a function that takes,
125 /// at a minimum, an object and a selector, and is the generic type for
126 /// Objective-C methods. Due to differences between variadic / non-variadic
127 /// calling conventions, it must always be cast to the correct type before
128 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000129 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000130 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
131 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
132 /// but if the runtime header declaring it is included then it may be a
133 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000134 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000135 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
136 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000137 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000138 /// The clang type of id. Used when using the clang CGCall infrastructure to
139 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000140 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000142 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000143 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
144 /// used in the code to document the difference between i8* meaning a pointer
145 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000146 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000147 /// LLVM type for C long type. The runtime uses this in a lot of places where
148 /// it should be using intptr_t, but we can't fix this without breaking
149 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000150 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000151 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000152 llvm::IntegerType *SizeTy;
David Chisnall49de5282011-10-08 08:54:36 +0000153 /// LLVM type for C intptr_t.
154 llvm::IntegerType *IntPtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000155 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000156 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000157 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
158 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000159 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000160 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000161 llvm::Type *BoolTy;
David Chisnall917b28b2011-10-04 15:35:30 +0000162 /// 32-bit integer type, to save us needing to look it up every time it's used.
163 llvm::IntegerType *Int32Ty;
164 /// 64-bit integer type, to save us needing to look it up every time it's used.
165 llvm::IntegerType *Int64Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000166 /// Metadata kind used to tie method lookups to message sends. The GNUstep
167 /// runtime provides some LLVM passes that can use this to do things like
168 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000169 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000170 /// Helper function that generates a constant string and returns a pointer to
171 /// the start of the string. The result of this function can be used anywhere
172 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000173 llvm::Constant *MakeConstantString(const std::string &Str,
174 const std::string &Name="") {
175 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000176 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000177 }
David Chisnall81a65f52011-03-26 11:48:37 +0000178 /// Emits a linkonce_odr string, whose name is the prefix followed by the
179 /// string value. This allows the linker to combine the strings between
180 /// different modules. Used for EH typeinfo names, selector strings, and a
181 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000182 llvm::Constant *ExportUniqueString(const std::string &Str,
183 const std::string prefix) {
184 std::string name = prefix + Str;
185 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
186 if (!ConstStr) {
Chris Lattner94010692012-02-05 02:30:40 +0000187 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall9735ca62011-03-25 11:57:33 +0000188 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
189 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
190 }
Jay Foada5c04342011-07-21 14:31:17 +0000191 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000192 }
David Chisnall81a65f52011-03-26 11:48:37 +0000193 /// Generates a global structure, initialized by the elements in the vector.
194 /// The element types must match the types of the structure elements in the
195 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000196 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000197 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000198 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000199 llvm::GlobalValue::LinkageTypes linkage
200 =llvm::GlobalValue::InternalLinkage) {
201 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
202 return new llvm::GlobalVariable(TheModule, Ty, false,
203 linkage, C, Name);
204 }
David Chisnall81a65f52011-03-26 11:48:37 +0000205 /// Generates a global array. The vector must contain the same number of
206 /// elements that the array type declares, of the type specified as the array
207 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000208 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000209 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000210 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000211 llvm::GlobalValue::LinkageTypes linkage
212 =llvm::GlobalValue::InternalLinkage) {
213 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
214 return new llvm::GlobalVariable(TheModule, Ty, false,
215 linkage, C, Name);
216 }
David Chisnall81a65f52011-03-26 11:48:37 +0000217 /// Generates a global array, inferring the array type from the specified
218 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000219 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000220 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000222 llvm::GlobalValue::LinkageTypes linkage
223 =llvm::GlobalValue::InternalLinkage) {
224 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
225 return MakeGlobal(ArrayTy, V, Name, linkage);
226 }
David Chisnall891dac72012-10-16 15:11:55 +0000227 /// Returns a property name and encoding string.
228 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
229 const Decl *Container) {
230 ObjCRuntime R = CGM.getLangOpts().ObjCRuntime;
231 if ((R.getKind() == ObjCRuntime::GNUstep) &&
232 (R.getVersion() >= VersionTuple(1, 6))) {
233 std::string NameAndAttributes;
234 std::string TypeStr;
235 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
236 NameAndAttributes += '\0';
237 NameAndAttributes += TypeStr.length() + 3;
238 NameAndAttributes += TypeStr;
239 NameAndAttributes += '\0';
240 NameAndAttributes += PD->getNameAsString();
241 return llvm::ConstantExpr::getGetElementPtr(
242 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
243 }
244 return MakeConstantString(PD->getNameAsString());
245 }
David Chisnall81a65f52011-03-26 11:48:37 +0000246 /// Ensures that the value has the required type, by inserting a bitcast if
247 /// required. This function lets us avoid inserting bitcasts that are
248 /// redundant.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000249 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnallc7ef4622011-03-23 22:52:06 +0000250 if (V->getType() == Ty) return V;
251 return B.CreateBitCast(V, Ty);
252 }
253 // Some zeros used for GEPs in lots of places.
254 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000255 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000256 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000257 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000258 llvm::LLVMContext &VMContext;
259private:
David Chisnall81a65f52011-03-26 11:48:37 +0000260 /// Placeholder for the class. Lots of things refer to the class before we've
261 /// actually emitted it. We use this alias as a placeholder, and then replace
262 /// it with a pointer to the class structure before finally emitting the
263 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000264 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000265 /// Placeholder for the metaclass. Lots of things refer to the class before
266 /// we've / actually emitted it. We use this alias as a placeholder, and then
267 /// replace / it with a pointer to the metaclass structure before finally
268 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000269 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000270 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000271 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000272 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000273 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000274 /// All of the Objective-C constant strings that have been generated for this
275 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000276 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000277 /// Map from string values to Objective-C constant strings in the output.
278 /// Used to prevent emitting Objective-C strings more than once. This should
279 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000280 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000281 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000282 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000283 /// For each variant of a selector, we store the type encoding and a
284 /// placeholder value. For an untyped selector, the type will be the empty
285 /// string. Selector references are all done via the module's selector table,
286 /// so we create an alias as a placeholder and then replace it with the real
287 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000288 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000289 /// Type of the selector map. This is roughly equivalent to the structure
290 /// used in the GNUstep runtime, which maintains a list of all of the valid
291 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000292 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000293 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000294 /// A map from selectors to selector types. This allows us to emit all
295 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000296 SelectorMap SelectorTable;
297
David Chisnall81a65f52011-03-26 11:48:37 +0000298 /// Selectors related to memory management. When compiling in GC mode, we
299 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000300 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000301 /// Runtime functions used for memory management in GC mode. Note that clang
302 /// supports code generation for calling these functions, but neither GNU
303 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000304 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
305 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000306
David Chisnall29254f42012-01-31 18:59:20 +0000307 typedef std::pair<std::string, std::string> ClassAliasPair;
308 /// All classes that have aliases set for them.
309 std::vector<ClassAliasPair> ClassAliases;
310
David Chisnall9735ca62011-03-25 11:57:33 +0000311protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000312 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000313 LazyRuntimeFunction ExceptionThrowFn;
James Dennett809d1be2012-06-13 22:07:09 +0000314 /// Function used for rethrowing exceptions, used at the end of \@finally or
315 /// \@synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000316 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000317 /// Function called when entering a catch function. This is required for
318 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000319 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000320 /// Function called when exiting from a catch block. Used to do exception
321 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000322 LazyRuntimeFunction ExitCatchFn;
James Dennett809d1be2012-06-13 22:07:09 +0000323 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000324 LazyRuntimeFunction SyncEnterFn;
James Dennett809d1be2012-06-13 22:07:09 +0000325 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000326 LazyRuntimeFunction SyncExitFn;
327
David Chisnall9735ca62011-03-25 11:57:33 +0000328private:
329
David Chisnall81a65f52011-03-26 11:48:37 +0000330 /// Function called if fast enumeration detects that the collection is
331 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000332 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000333 /// Function for implementing synthesized property getters that return an
334 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000335 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000336 /// Function for implementing synthesized property setters that return an
337 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000338 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000339 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000340 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000341 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000342 LazyRuntimeFunction SetStructPropertyFn;
343
David Chisnall81a65f52011-03-26 11:48:37 +0000344 /// The version of the runtime that this class targets. Must match the
345 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000346 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000347 /// The version of the protocol class. Used to differentiate between ObjC1
348 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
349 /// components and can not contain declared properties. We always emit
350 /// Objective-C 2 property structures, but we have to pretend that they're
351 /// Objective-C 1 property structures when targeting the GCC runtime or it
352 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000353 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000354private:
David Chisnall81a65f52011-03-26 11:48:37 +0000355 /// Generates an instance variable list structure. This is a structure
356 /// containing a size and an array of structures containing instance variable
357 /// metadata. This is used purely for introspection in the fragile ABI. In
358 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendling795b1002012-02-22 09:30:11 +0000359 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
360 ArrayRef<llvm::Constant *> IvarTypes,
361 ArrayRef<llvm::Constant *> IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000362 /// Generates a method list structure. This is a structure containing a size
363 /// and an array of structures containing method metadata.
364 ///
365 /// This structure is used by both classes and categories, and contains a next
366 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000367 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
368 const StringRef &CategoryName,
Bill Wendling795b1002012-02-22 09:30:11 +0000369 ArrayRef<Selector> MethodSels,
370 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000371 bool isClassMethodList);
James Dennett809d1be2012-06-13 22:07:09 +0000372 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall81a65f52011-03-26 11:48:37 +0000373 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
374 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000375 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000376 /// Generates a list of property metadata structures. This follows the same
377 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000378 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 SmallVectorImpl<Selector> &InstanceMethodSels,
380 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000381 /// Generates a list of referenced protocols. Classes, categories, and
382 /// protocols all use this structure.
Bill Wendling795b1002012-02-22 09:30:11 +0000383 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000384 /// To ensure that all protocols are seen by the runtime, we add a category on
385 /// a class defined in the runtime, declaring no methods, but adopting the
386 /// protocols. This is a horribly ugly hack, but it allows us to collect all
387 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000388 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000389 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000390 llvm::Constant *GenerateClassStructure(
391 llvm::Constant *MetaClass,
392 llvm::Constant *SuperClass,
393 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000394 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000395 llvm::Constant *Version,
396 llvm::Constant *InstanceSize,
397 llvm::Constant *IVars,
398 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000399 llvm::Constant *Protocols,
400 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000401 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +0000402 llvm::Constant *StrongIvarBitmap,
403 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +0000404 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000405 /// Generates a method list. This is used by protocols to define the required
406 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000407 llvm::Constant *GenerateProtocolMethodList(
Bill Wendling795b1002012-02-22 09:30:11 +0000408 ArrayRef<llvm::Constant *> MethodNames,
409 ArrayRef<llvm::Constant *> MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000410 /// Returns a selector with the specified type encoding. An empty string is
411 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000412 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
413 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000414 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000415 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
416 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000417 /// Emits a reference to a class. This allows the linker to object if there
418 /// is no class of the matching name.
John McCallf7226fb2012-07-12 02:07:58 +0000419protected:
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000420 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000421 /// Emits a pointer to the named class
John McCallf7226fb2012-07-12 02:07:58 +0000422 virtual llvm::Value *GetClassNamed(CGBuilderTy &Builder,
423 const std::string &Name, bool isWeak);
David Chisnall81a65f52011-03-26 11:48:37 +0000424 /// Looks up the method for sending a message to the specified object. This
425 /// mechanism differs between the GCC and GNU runtimes, so this method must be
426 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000427 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
428 llvm::Value *&Receiver,
429 llvm::Value *cmd,
430 llvm::MDNode *node) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000431 /// Looks up the method for sending a message to a superclass. This
432 /// mechanism differs between the GCC and GNU runtimes, so this method must
433 /// be overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000434 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
435 llvm::Value *ObjCSuper,
436 llvm::Value *cmd) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000437 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
438 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
439 /// bits set to their values, LSB first, while larger ones are stored in a
440 /// structure of this / form:
441 ///
442 /// struct { int32_t length; int32_t values[length]; };
443 ///
444 /// The values in the array are stored in host-endian format, with the least
445 /// significant bit being assumed to come first in the bitfield. Therefore,
446 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
447 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +0000448 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Chris Lattner0f984262008-03-01 08:50:34 +0000449public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000450 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
451 unsigned protocolClassVersion);
452
David Chisnall0d13f6f2010-01-23 02:40:42 +0000453 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000454
455 virtual RValue
456 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000457 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000458 QualType ResultType,
459 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000460 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000461 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000462 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000463 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000464 virtual RValue
465 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000466 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000467 QualType ResultType,
468 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000469 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000470 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000471 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000472 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000473 const CallArgList &CallArgs,
474 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000475 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000476 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000477 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
478 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000479 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
480 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000481 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000482
483 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000484 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000485 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
486 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
David Chisnall29254f42012-01-31 18:59:20 +0000487 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000488 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000489 const ObjCProtocolDecl *PD);
490 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000491 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000492 virtual llvm::Constant *GetPropertyGetFunction();
493 virtual llvm::Constant *GetPropertySetFunction();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000494 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
495 bool copy);
David Chisnall789ecde2011-05-23 22:33:28 +0000496 virtual llvm::Constant *GetSetStructFunction();
Fariborz Jahaniane3173022012-01-06 18:07:23 +0000497 virtual llvm::Constant *GetCppAtomicObjectFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000498 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000499 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000500
David Chisnall9f6614e2011-03-23 16:36:54 +0000501 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000502 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000503 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000504 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000505 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000506 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000507 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000508 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000509 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000510 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000511 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000512 llvm::Value *src, llvm::Value *dest,
513 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000514 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000515 llvm::Value *src, llvm::Value *dest,
516 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000517 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000518 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000519 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000521 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000522 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000523 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000524 QualType ObjectTy,
525 llvm::Value *BaseValue,
526 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000527 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000528 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000529 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000530 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000531 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000532 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000533 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000534 return NULLPtr;
535 }
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000536 virtual llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
537 const CGBlockInfo &blockInfo) {
538 return NULLPtr;
539 }
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000540 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
541 return 0;
542 }
Chris Lattner0f984262008-03-01 08:50:34 +0000543};
David Chisnall81a65f52011-03-26 11:48:37 +0000544/// Class representing the legacy GCC Objective-C ABI. This is the default when
545/// -fobjc-nonfragile-abi is not specified.
546///
547/// The GCC ABI target actually generates code that is approximately compatible
548/// with the new GNUstep runtime ABI, but refrains from using any features that
549/// would not work with the GCC runtime. For example, clang always generates
550/// the extended form of the class structure, and the extra fields are simply
551/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000552class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000553 /// The GCC ABI message lookup function. Returns an IMP pointing to the
554 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000555 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000556 /// The GCC ABI superclass message lookup function. Takes a pointer to a
557 /// structure describing the receiver and the class, and a selector as
558 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000559 LazyRuntimeFunction MsgLookupSuperFn;
560protected:
561 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
562 llvm::Value *&Receiver,
563 llvm::Value *cmd,
564 llvm::MDNode *node) {
565 CGBuilderTy &Builder = CGF.Builder;
David Chisnall6f3887e2011-10-28 17:55:06 +0000566 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000567 EnforceType(Builder, Receiver, IdTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000568 EnforceType(Builder, cmd, SelectorTy) };
569 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
570 imp->setMetadata(msgSendMDKind, node);
571 return imp.getInstruction();
David Chisnallc7ef4622011-03-23 22:52:06 +0000572 }
573 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
574 llvm::Value *ObjCSuper,
575 llvm::Value *cmd) {
576 CGBuilderTy &Builder = CGF.Builder;
577 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
578 PtrToObjCSuperTy), cmd};
Jay Foad4c7d9f12011-07-15 08:37:34 +0000579 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000580 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000581 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000582 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
583 // IMP objc_msg_lookup(id, SEL);
584 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
585 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
586 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
587 PtrToObjCSuperTy, SelectorTy, NULL);
588 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000589};
David Chisnall81a65f52011-03-26 11:48:37 +0000590/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000591class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000592 /// The slot lookup function. Returns a pointer to a cacheable structure
593 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000594 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000595 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
596 /// a structure describing the receiver and the class, and a selector as
597 /// arguments. Returns the slot for the corresponding method. Superclass
598 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000599 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000600 /// Type of an slot structure pointer. This is returned by the various
601 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000602 llvm::Type *SlotTy;
603 protected:
604 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
605 llvm::Value *&Receiver,
606 llvm::Value *cmd,
607 llvm::MDNode *node) {
608 CGBuilderTy &Builder = CGF.Builder;
609 llvm::Function *LookupFn = SlotLookupFn;
610
611 // Store the receiver on the stack so that we can reload it later
612 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
613 Builder.CreateStore(Receiver, ReceiverPtr);
614
615 llvm::Value *self;
616
617 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
618 self = CGF.LoadObjCSelf();
619 } else {
620 self = llvm::ConstantPointerNull::get(IdTy);
621 }
622
623 // The lookup function is guaranteed not to capture the receiver pointer.
624 LookupFn->setDoesNotCapture(1);
625
David Chisnall6f3887e2011-10-28 17:55:06 +0000626 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000627 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
628 EnforceType(Builder, cmd, SelectorTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000629 EnforceType(Builder, self, IdTy) };
630 llvm::CallSite slot = CGF.EmitCallOrInvoke(LookupFn, args);
631 slot.setOnlyReadsMemory();
David Chisnallc7ef4622011-03-23 22:52:06 +0000632 slot->setMetadata(msgSendMDKind, node);
633
634 // Load the imp from the slot
David Chisnall6f3887e2011-10-28 17:55:06 +0000635 llvm::Value *imp =
636 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnallc7ef4622011-03-23 22:52:06 +0000637
638 // The lookup function may have changed the receiver, so make sure we use
639 // the new one.
640 Receiver = Builder.CreateLoad(ReceiverPtr, true);
641 return imp;
642 }
643 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
644 llvm::Value *ObjCSuper,
645 llvm::Value *cmd) {
646 CGBuilderTy &Builder = CGF.Builder;
647 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
648
Jay Foad4c7d9f12011-07-15 08:37:34 +0000649 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000650 slot->setOnlyReadsMemory();
651
652 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
653 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000654 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000655 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner7650d952011-06-18 22:49:11 +0000656 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000657 PtrTy, PtrTy, IntTy, IMPTy, NULL);
658 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
659 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
660 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
661 SelectorTy, IdTy, NULL);
662 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
663 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
664 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000665 // If we're in ObjC++ mode, then we want to make
David Blaikie4e4d0842012-03-11 07:00:24 +0000666 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000667 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000668 // void *__cxa_begin_catch(void *e)
669 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
670 // void __cxa_end_catch(void)
David Chisnall4bd5d092011-08-08 17:26:06 +0000671 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000672 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000673 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000674 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000675 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000676};
677
John McCall0a7dd782012-08-21 02:47:43 +0000678/// Support for the ObjFW runtime. Support here is due to
679/// Jonathan Schleifer <js@webkeks.org>, the ObjFW maintainer.
680class CGObjCObjFW: public CGObjCGNU {
681protected:
682 /// The GCC ABI message lookup function. Returns an IMP pointing to the
683 /// method implementation for this message.
684 LazyRuntimeFunction MsgLookupFn;
685 /// The GCC ABI superclass message lookup function. Takes a pointer to a
686 /// structure describing the receiver and the class, and a selector as
687 /// arguments. Returns the IMP for the corresponding method.
688 LazyRuntimeFunction MsgLookupSuperFn;
689
690 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
691 llvm::Value *&Receiver,
692 llvm::Value *cmd,
693 llvm::MDNode *node) {
694 CGBuilderTy &Builder = CGF.Builder;
695 llvm::Value *args[] = {
696 EnforceType(Builder, Receiver, IdTy),
697 EnforceType(Builder, cmd, SelectorTy) };
698 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
699 imp->setMetadata(msgSendMDKind, node);
700 return imp.getInstruction();
701 }
702
703 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
704 llvm::Value *ObjCSuper,
705 llvm::Value *cmd) {
706 CGBuilderTy &Builder = CGF.Builder;
707 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
708 PtrToObjCSuperTy), cmd};
709 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
710 }
711
John McCallf7226fb2012-07-12 02:07:58 +0000712 virtual llvm::Value *GetClassNamed(CGBuilderTy &Builder,
713 const std::string &Name, bool isWeak) {
714 if (isWeak)
715 return CGObjCGNU::GetClassNamed(Builder, Name, isWeak);
716
717 EmitClassRef(Name);
718
719 std::string SymbolName = "_OBJC_CLASS_" + Name;
720
721 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
722
723 if (!ClassSymbol)
724 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
725 llvm::GlobalValue::ExternalLinkage,
726 0, SymbolName);
727
728 return ClassSymbol;
729 }
730
731public:
John McCall0a7dd782012-08-21 02:47:43 +0000732 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
733 // IMP objc_msg_lookup(id, SEL);
734 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
735 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
736 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
737 PtrToObjCSuperTy, SelectorTy, NULL);
738 }
John McCallf7226fb2012-07-12 02:07:58 +0000739};
Chris Lattner0f984262008-03-01 08:50:34 +0000740} // end anonymous namespace
741
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000742
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000743/// Emits a reference to a dummy variable which is emitted with each class.
744/// This ensures that a linker error will be generated when trying to link
745/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000746void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000747 std::string symbolRef = "__objc_class_ref_" + className;
748 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000749 if (TheModule.getGlobalVariable(symbolRef))
750 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000751 std::string symbolName = "__objc_class_name_" + className;
752 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
753 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000754 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
755 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000756 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000757 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000758 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000759}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000760
Chris Lattner5f9e2722011-07-23 10:55:15 +0000761static std::string SymbolNameForMethod(const StringRef &ClassName,
762 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000763 bool isClassMethod) {
764 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000765 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
766 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000767 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000768 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000769}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000770
David Chisnall9f6614e2011-03-23 16:36:54 +0000771CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
772 unsigned protocolClassVersion)
John McCallde5d3c72012-02-17 03:33:10 +0000773 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
774 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
775 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000776
777 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
778
David Chisnall9f6614e2011-03-23 16:36:54 +0000779 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000780 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000781 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000782 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000783 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000784 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000785 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000786 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000787 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000788 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000790 Int8Ty = llvm::Type::getInt8Ty(VMContext);
791 // C string type. Used in lots of places.
792 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
793
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000794 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000795 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000796 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000797 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000798 QualType selTy = CGM.getContext().getObjCSelType();
799 if (QualType() == selTy) {
800 SelectorTy = PtrToInt8Ty;
801 } else {
802 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
803 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000804
Owen Anderson96e0fc72009-07-29 22:16:19 +0000805 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000806 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
David Chisnall917b28b2011-10-04 15:35:30 +0000808 Int32Ty = llvm::Type::getInt32Ty(VMContext);
809 Int64Ty = llvm::Type::getInt64Ty(VMContext);
810
David Chisnall49de5282011-10-08 08:54:36 +0000811 IntPtrTy =
812 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
813
Chris Lattner391d77a2008-03-30 23:03:07 +0000814 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000815 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
816 ASTIdTy = CanQualType();
817 if (UnqualIdTy != QualType()) {
818 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000819 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000820 } else {
821 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000822 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000823 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Chris Lattner7650d952011-06-18 22:49:11 +0000825 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000826 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
827
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000828 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000829
830 // void objc_exception_throw(id);
831 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000832 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000833 // int objc_sync_enter(id);
834 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
835 // int objc_sync_exit(id);
836 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
837
838 // void objc_enumerationMutation (id)
839 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
840 IdTy, NULL);
841
842 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
843 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
844 PtrDiffTy, BoolTy, NULL);
845 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
846 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
847 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
848 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
849 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
850 PtrDiffTy, BoolTy, BoolTy, NULL);
851 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
852 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
853 PtrDiffTy, BoolTy, BoolTy, NULL);
854
Chris Lattner391d77a2008-03-30 23:03:07 +0000855 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000856 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000857 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
858 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000859
David Blaikie4e4d0842012-03-11 07:00:24 +0000860 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregore289d812011-09-13 17:21:33 +0000861 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +0000862 RuntimeVersion = 10;
863
David Chisnall9735ca62011-03-25 11:57:33 +0000864 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +0000865 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000866 // This is a bit of an hack. We should sort this out by having a proper
867 // CGObjCGNUstep subclass for GC, but we may want to really support the old
868 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000869 // Get selectors needed in GC mode
870 RetainSel = GetNullarySelector("retain", CGM.getContext());
871 ReleaseSel = GetNullarySelector("release", CGM.getContext());
872 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
873
874 // Get functions needed in GC mode
875
876 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000877 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
878 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000879 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000880 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
881 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000882 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000883 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
884 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000885 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000886 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000887 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000888 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000889 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000890 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
891 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000892 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000893}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000894
David Chisnallc7aed3b2011-06-29 13:16:41 +0000895llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +0000896 const std::string &Name,
897 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +0000898 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +0000899 // With the incompatible ABI, this will need to be replaced with a direct
900 // reference to the class symbol. For the compatible nonfragile ABI we are
901 // still performing this lookup at run time but emitting the symbol for the
902 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +0000903 //
904 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
905 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +0000906 if (!isWeak)
907 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000908 ClassName = Builder.CreateStructGEP(ClassName, 0);
909
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000910 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +0000911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000912 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000913 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000914}
915
David Chisnallc7aed3b2011-06-29 13:16:41 +0000916// This has to perform the lookup every time, since posing and related
917// techniques can modify the name -> class mapping.
918llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
919 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000920 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +0000921}
922llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000923 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000924}
925
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000926llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000927 const std::string &TypeEncoding, bool lval) {
928
Chris Lattner5f9e2722011-07-23 10:55:15 +0000929 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +0000930 llvm::GlobalAlias *SelValue = 0;
931
932
Chris Lattner5f9e2722011-07-23 10:55:15 +0000933 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +0000934 e = Types.end() ; i!=e ; i++) {
935 if (i->first == TypeEncoding) {
936 SelValue = i->second;
937 break;
938 }
939 }
940 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000941 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000942 llvm::GlobalValue::PrivateLinkage,
943 ".objc_selector_"+Sel.getAsString(), NULL,
944 &TheModule);
945 Types.push_back(TypedSelector(TypeEncoding, SelValue));
946 }
947
David Chisnallc7ef4622011-03-23 22:52:06 +0000948 if (lval) {
949 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
950 Builder.CreateStore(SelValue, tmp);
951 return tmp;
952 }
953 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000954}
955
956llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
957 bool lval) {
958 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000959}
960
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000961llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000962 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000963 std::string SelTypes;
964 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000965 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000966}
967
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000968llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000969 if (!CGM.getLangOpts().CPlusPlus) {
David Chisnall9735ca62011-03-25 11:57:33 +0000970 if (T->isObjCIdType()
971 || T->isObjCQualifiedIdType()) {
972 // With the old ABI, there was only one kind of catchall, which broke
973 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
974 // a pointer indicating object catchalls, and NULL to indicate real
975 // catchalls
John McCall260611a2012-06-20 06:18:46 +0000976 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
David Chisnall9735ca62011-03-25 11:57:33 +0000977 return MakeConstantString("@id");
978 } else {
979 return 0;
980 }
981 }
982
983 // All other types should be Objective-C interface pointer types.
984 const ObjCObjectPointerType *OPT =
985 T->getAs<ObjCObjectPointerType>();
986 assert(OPT && "Invalid @catch type.");
987 const ObjCInterfaceDecl *IDecl =
988 OPT->getObjectType()->getInterface();
989 assert(IDecl && "Invalid @catch type.");
990 return MakeConstantString(IDecl->getIdentifier()->getName());
991 }
David Chisnall80558d22011-03-20 21:35:39 +0000992 // For Objective-C++, we want to provide the ability to catch both C++ and
993 // Objective-C objects in the same function.
994
995 // There's a particular fixed type info for 'id'.
996 if (T->isObjCIdType() ||
997 T->isObjCQualifiedIdType()) {
998 llvm::Constant *IDEHType =
999 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1000 if (!IDEHType)
1001 IDEHType =
1002 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1003 false,
1004 llvm::GlobalValue::ExternalLinkage,
1005 0, "__objc_id_type_info");
1006 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1007 }
1008
1009 const ObjCObjectPointerType *PT =
1010 T->getAs<ObjCObjectPointerType>();
1011 assert(PT && "Invalid @catch type.");
1012 const ObjCInterfaceType *IT = PT->getInterfaceType();
1013 assert(IT && "Invalid @catch type.");
1014 std::string className = IT->getDecl()->getIdentifier()->getName();
1015
1016 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1017
1018 // Return the existing typeinfo if it exists
1019 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnallacd76fe2012-03-20 16:25:52 +00001020 if (typeinfo)
1021 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnall80558d22011-03-20 21:35:39 +00001022
1023 // Otherwise create it.
1024
1025 // vtable for gnustep::libobjc::__objc_class_type_info
1026 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1027 // platform's name mangling.
1028 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1029 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1030 if (!Vtable) {
1031 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1032 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1033 }
1034 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +00001035 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +00001036 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1037
1038 llvm::Constant *typeName =
1039 ExportUniqueString(className, "__objc_eh_typename_");
1040
1041 std::vector<llvm::Constant*> fields;
1042 fields.push_back(Vtable);
1043 fields.push_back(typeName);
1044 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +00001045 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +00001046 NULL), fields, "__objc_eh_typeinfo_" + className,
1047 llvm::GlobalValue::LinkOnceODRLinkage);
1048 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +00001049}
1050
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001051/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +00001052llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +00001053
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001054 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +00001055
David Chisnall48272a02010-01-27 12:49:23 +00001056 // Look for an existing one
1057 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1058 if (old != ObjCStrings.end())
1059 return old->getValue();
1060
David Blaikie4e4d0842012-03-11 07:00:24 +00001061 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall13df6f62012-01-04 12:02:13 +00001062
1063 if (StringClass.empty()) StringClass = "NXConstantString";
1064
1065 std::string Sym = "_OBJC_CLASS_";
1066 Sym += StringClass;
1067
1068 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1069
1070 if (!isa)
1071 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1072 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1073 else if (isa->getType() != PtrToIdTy)
1074 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1075
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001076 std::vector<llvm::Constant*> Ivars;
David Chisnall13df6f62012-01-04 12:02:13 +00001077 Ivars.push_back(isa);
Chris Lattner13fd7e52008-06-21 21:44:18 +00001078 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001079 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001080 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall13df6f62012-01-04 12:02:13 +00001081 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001082 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +00001083 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1084 ObjCStrings[Str] = ObjCStr;
1085 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001086 return ObjCStr;
1087}
1088
1089///Generates a message send where the super is the receiver. This is a message
1090///send to self with special delivery semantics indicating which class's method
1091///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +00001092RValue
1093CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001094 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001095 QualType ResultType,
1096 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001097 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001098 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001099 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001100 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001101 const CallArgList &CallArgs,
1102 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001103 CGBuilderTy &Builder = CGF.Builder;
David Blaikie4e4d0842012-03-11 07:00:24 +00001104 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001105 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001106 return RValue::get(EnforceType(Builder, Receiver,
1107 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001108 }
1109 if (Sel == ReleaseSel) {
1110 return RValue::get(0);
1111 }
1112 }
David Chisnalldb831942010-05-01 12:37:16 +00001113
David Chisnalldb831942010-05-01 12:37:16 +00001114 llvm::Value *cmd = GetSelector(Builder, Sel);
1115
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001116
1117 CallArgList ActualArgs;
1118
Eli Friedman04c9a492011-05-02 17:57:46 +00001119 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1120 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001121 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001122
John McCallde5d3c72012-02-17 03:33:10 +00001123 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001124
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001125 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001126 if (isCategoryImpl) {
1127 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001128 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001129 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001130 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001131 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001132 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001133 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001134 }
David Chisnalldb831942010-05-01 12:37:16 +00001135 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001136 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001137 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001138 // Set up global aliases for the metaclass or class pointer if they do not
1139 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001140 // pointers to the class and metaclass structure created for the runtime
1141 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001142 // super_class pointer from either the class or metaclass structure.
1143 if (IsClassMessage) {
1144 if (!MetaClassPtrAlias) {
1145 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1146 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1147 Class->getNameAsString(), NULL, &TheModule);
1148 }
1149 ReceiverClass = MetaClassPtrAlias;
1150 } else {
1151 if (!ClassPtrAlias) {
1152 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1153 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1154 Class->getNameAsString(), NULL, &TheModule);
1155 }
1156 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001157 }
Chris Lattner71238f62009-04-25 23:19:45 +00001158 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001159 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001160 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001161 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001162 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001163 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001164 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001165 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001166 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001167 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001168 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001169 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001170 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001171
David Chisnalldb831942010-05-01 12:37:16 +00001172 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1173 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001174
David Chisnallc7ef4622011-03-23 22:52:06 +00001175 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnallc7ef4622011-03-23 22:52:06 +00001176
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001177 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001178 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
John McCallde5d3c72012-02-17 03:33:10 +00001179 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001180
David Chisnalldd5c98f2010-05-01 11:15:56 +00001181 llvm::Value *impMD[] = {
1182 llvm::MDString::get(VMContext, Sel.getAsString()),
1183 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1184 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1185 };
Jay Foad6f141652011-04-21 19:59:12 +00001186 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001187
David Chisnall4b02afc2010-05-02 13:41:58 +00001188 llvm::Instruction *call;
John McCallde5d3c72012-02-17 03:33:10 +00001189 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnall4b02afc2010-05-02 13:41:58 +00001190 call->setMetadata(msgSendMDKind, node);
1191 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001192}
1193
Mike Stump1eb44332009-09-09 15:08:12 +00001194/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001195RValue
1196CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001197 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001198 QualType ResultType,
1199 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001200 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001201 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001202 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001203 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001204 CGBuilderTy &Builder = CGF.Builder;
1205
David Chisnall664b7c72010-04-27 15:08:48 +00001206 // Strip out message sends to retain / release in GC mode
David Blaikie4e4d0842012-03-11 07:00:24 +00001207 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001208 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001209 return RValue::get(EnforceType(Builder, Receiver,
1210 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001211 }
1212 if (Sel == ReleaseSel) {
1213 return RValue::get(0);
1214 }
1215 }
David Chisnall664b7c72010-04-27 15:08:48 +00001216
David Chisnall664b7c72010-04-27 15:08:48 +00001217 // If the return type is something that goes in an integer register, the
1218 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1219 // ourselves.
1220 //
1221 // The language spec says the result of this kind of message send is
1222 // undefined, but lots of people seem to have forgotten to read that
1223 // paragraph and insist on sending messages to nil that have structure
1224 // returns. With GCC, this generates a random return value (whatever happens
1225 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001226 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1227 // the stack.
1228 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1229 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001230
1231 llvm::BasicBlock *startBB = 0;
1232 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001233 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001234
1235 if (!isPointerSizedReturn) {
1236 startBB = Builder.GetInsertBlock();
1237 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001238 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001239
1240 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1241 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001242 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001243 CGF.EmitBlock(messageBB);
1244 }
1245
David Chisnall0f436562009-08-17 16:35:33 +00001246 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001247 llvm::Value *cmd;
1248 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001249 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001250 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001251 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001252 cmd = EnforceType(Builder, cmd, SelectorTy);
1253 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001254
David Chisnallc7ef4622011-03-23 22:52:06 +00001255 llvm::Value *impMD[] = {
1256 llvm::MDString::get(VMContext, Sel.getAsString()),
1257 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1258 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1259 };
Jay Foad6f141652011-04-21 19:59:12 +00001260 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001261
David Chisnallc7ef4622011-03-23 22:52:06 +00001262 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001263 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1264 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001265 ActualArgs.addFrom(CallArgs);
John McCallde5d3c72012-02-17 03:33:10 +00001266
1267 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1268
David Chisnall89c30042011-10-24 14:07:03 +00001269 // Get the IMP to call
1270 llvm::Value *imp;
1271
1272 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1273 // functions. These are not supported on all platforms (or all runtimes on a
1274 // given platform), so we
1275 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall89c30042011-10-24 14:07:03 +00001276 case CodeGenOptions::Legacy:
David Chisnall89c30042011-10-24 14:07:03 +00001277 imp = LookupIMP(CGF, Receiver, cmd, node);
1278 break;
1279 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001280 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001281 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1282 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1283 "objc_msgSend_fpret");
John McCallde5d3c72012-02-17 03:33:10 +00001284 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall89c30042011-10-24 14:07:03 +00001285 // The actual types here don't matter - we're going to bitcast the
1286 // function anyway
1287 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1288 "objc_msgSend_stret");
1289 } else {
1290 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1291 "objc_msgSend");
1292 }
1293 }
1294
David Chisnall403bc3f2011-12-01 18:40:09 +00001295 // Reset the receiver in case the lookup modified it
1296 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001297
John McCallde5d3c72012-02-17 03:33:10 +00001298 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnall63e742b2010-05-01 12:56:56 +00001299
David Chisnall4b02afc2010-05-02 13:41:58 +00001300 llvm::Instruction *call;
John McCallde5d3c72012-02-17 03:33:10 +00001301 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001302 0, &call);
1303 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001304
David Chisnalla54da052010-05-20 13:45:48 +00001305
David Chisnall664b7c72010-04-27 15:08:48 +00001306 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001307 messageBB = CGF.Builder.GetInsertBlock();
1308 CGF.Builder.CreateBr(continueBB);
1309 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001310 if (msgRet.isScalar()) {
1311 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001312 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001313 phi->addIncoming(v, messageBB);
1314 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1315 msgRet = RValue::get(phi);
1316 } else if (msgRet.isAggregate()) {
1317 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001318 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001319 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001320 llvm::AllocaInst *NullVal =
1321 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001322 CGF.InitTempAlloca(NullVal,
1323 llvm::Constant::getNullValue(RetTy->getElementType()));
1324 phi->addIncoming(v, messageBB);
1325 phi->addIncoming(NullVal, startBB);
1326 msgRet = RValue::getAggregate(phi);
1327 } else /* isComplex() */ {
1328 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001329 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001330 phi->addIncoming(v.first, messageBB);
1331 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1332 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001333 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001334 phi2->addIncoming(v.second, messageBB);
1335 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1336 startBB);
1337 msgRet = RValue::getComplex(phi, phi2);
1338 }
1339 }
1340 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001341}
1342
Mike Stump1eb44332009-09-09 15:08:12 +00001343/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001344/// objc_category structures.
Bill Wendling795b1002012-02-22 09:30:11 +00001345llvm::Constant *CGObjCGNU::
1346GenerateMethodList(const StringRef &ClassName,
1347 const StringRef &CategoryName,
1348 ArrayRef<Selector> MethodSels,
1349 ArrayRef<llvm::Constant *> MethodTypes,
1350 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001351 if (MethodSels.empty())
1352 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001353 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001354 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001355 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1356 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001357 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001358 NULL);
1359 std::vector<llvm::Constant*> Methods;
1360 std::vector<llvm::Constant*> Elements;
1361 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1362 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001363 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001364 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001365 MethodSels[i],
1366 isClassMethodList));
1367 assert(Method && "Can't generate metadata for method that doesn't exist");
1368 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1369 Elements.push_back(C);
1370 Elements.push_back(MethodTypes[i]);
1371 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001372 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001373 Elements.push_back(Method);
1374 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001375 }
1376
1377 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001378 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001379 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001380 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001381 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001382
1383 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001384 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001385 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1386 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001387 NextPtrTy,
1388 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001389 ObjCMethodArrayTy,
1390 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001391
1392 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001393 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001394 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001395 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001396 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001398 // Create an instance of the structure
1399 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1400}
1401
1402/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendling795b1002012-02-22 09:30:11 +00001403llvm::Constant *CGObjCGNU::
1404GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1405 ArrayRef<llvm::Constant *> IvarTypes,
1406 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001407 if (IvarNames.size() == 0)
1408 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001409 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001410 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001411 PtrToInt8Ty,
1412 PtrToInt8Ty,
1413 IntTy,
1414 NULL);
1415 std::vector<llvm::Constant*> Ivars;
1416 std::vector<llvm::Constant*> Elements;
1417 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1418 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001419 Elements.push_back(IvarNames[i]);
1420 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001421 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001422 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001423 }
1424
1425 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001426 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001427 IvarNames.size());
1428
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001430 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001431 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001432 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001433 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001434 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001435 ObjCIvarArrayTy,
1436 NULL);
1437
1438 // Create an instance of the structure
1439 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1440}
1441
1442/// Generate a class structure
1443llvm::Constant *CGObjCGNU::GenerateClassStructure(
1444 llvm::Constant *MetaClass,
1445 llvm::Constant *SuperClass,
1446 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001447 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001448 llvm::Constant *Version,
1449 llvm::Constant *InstanceSize,
1450 llvm::Constant *IVars,
1451 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001452 llvm::Constant *Protocols,
1453 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001454 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001455 llvm::Constant *StrongIvarBitmap,
1456 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001457 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001458 // Set up the class structure
1459 // Note: Several of these are char*s when they should be ids. This is
1460 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001461 //
1462 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1463 // anyway; the classes will still work with the GNU runtime, they will just
1464 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001465 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001466 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001467 PtrToInt8Ty, // super_class
1468 PtrToInt8Ty, // name
1469 LongTy, // version
1470 LongTy, // info
1471 LongTy, // instance_size
1472 IVars->getType(), // ivars
1473 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001474 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001475 PtrTy, // dtable
1476 PtrTy, // subclass_list
1477 PtrTy, // sibling_class
1478 PtrTy, // protocols
1479 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001480 // New ABI:
1481 LongTy, // abi_version
1482 IvarOffsets->getType(), // ivar_offsets
1483 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001484 IntPtrTy, // strong_pointers
1485 IntPtrTy, // weak_pointers
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001486 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001487 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001488 // Fill in the structure
1489 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001490 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001491 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001492 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001493 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001494 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001495 if (isMeta) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001496 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001497 Elements.push_back(
1498 llvm::ConstantInt::get(LongTy,
1499 td.getTypeSizeInBits(ClassTy) /
1500 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001501 } else
1502 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001503 Elements.push_back(IVars);
1504 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001505 Elements.push_back(NULLPtr);
1506 Elements.push_back(NULLPtr);
1507 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001508 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001509 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001510 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001511 Elements.push_back(IvarOffsets);
1512 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001513 Elements.push_back(StrongIvarBitmap);
1514 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001515 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001516 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001517 // messages in the next ABI. We may already have some weak references to
1518 // this, so check and fix them properly.
1519 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1520 std::string(Name));
1521 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1522 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1523 llvm::GlobalValue::ExternalLinkage);
1524 if (ClassRef) {
1525 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1526 ClassRef->getType()));
1527 ClassRef->removeFromParent();
1528 Class->setName(ClassSym);
1529 }
1530 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001531}
1532
Bill Wendling795b1002012-02-22 09:30:11 +00001533llvm::Constant *CGObjCGNU::
1534GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1535 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001537 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001538 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1539 PtrToInt8Ty,
1540 NULL);
1541 std::vector<llvm::Constant*> Methods;
1542 std::vector<llvm::Constant*> Elements;
1543 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1544 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001545 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001546 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001547 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001548 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001549 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001550 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001551 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001552 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001553 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001554 IntTy, ObjCMethodArrayTy, NULL);
1555 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001556 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001557 Methods.push_back(Array);
1558 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1559}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001560
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001561// Create the protocol list structure used in classes, categories and so on
Bill Wendling795b1002012-02-22 09:30:11 +00001562llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson96e0fc72009-07-29 22:16:19 +00001563 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001564 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001565 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001566 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001567 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001568 ProtocolArrayTy,
1569 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001570 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001571 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1572 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001573 llvm::Constant *protocol = 0;
1574 llvm::StringMap<llvm::Constant*>::iterator value =
1575 ExistingProtocols.find(*iter);
1576 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001577 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001578 } else {
1579 protocol = value->getValue();
1580 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001581 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001582 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001583 Elements.push_back(Ptr);
1584 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001585 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001586 Elements);
1587 Elements.clear();
1588 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001589 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001590 Elements.push_back(ProtocolArray);
1591 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1592}
1593
Mike Stump1eb44332009-09-09 15:08:12 +00001594llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001595 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001596 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001597 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001598 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001599 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001600}
1601
1602llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1603 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001604 SmallVector<std::string, 0> EmptyStringVector;
1605 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001606
1607 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001608 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001609 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1610 // Protocols are objects containing lists of the methods implemented and
1611 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001612 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001613 PtrToInt8Ty,
1614 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001615 MethodList->getType(),
1616 MethodList->getType(),
1617 MethodList->getType(),
1618 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001619 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001620 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001621 // The isa pointer must be set to a magic number so the runtime knows it's
1622 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001623 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001624 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001625 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1626 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001627 Elements.push_back(MethodList);
1628 Elements.push_back(MethodList);
1629 Elements.push_back(MethodList);
1630 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001631 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001632}
1633
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001634void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1635 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001636 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001637
1638 // Use the protocol definition, if there is one.
1639 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1640 PD = Def;
1641
Chris Lattner5f9e2722011-07-23 10:55:15 +00001642 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001643 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1644 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001645 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001646 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1647 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1648 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1649 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001650 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1651 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001652 std::string TypeStr;
1653 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001654 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001655 OptionalInstanceMethodNames.push_back(
1656 MakeConstantString((*iter)->getSelector().getAsString()));
1657 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001658 } else {
1659 InstanceMethodNames.push_back(
1660 MakeConstantString((*iter)->getSelector().getAsString()));
1661 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001662 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001663 }
1664 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001665 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1666 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1667 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1668 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001669 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001670 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1671 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001672 std::string TypeStr;
1673 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001674 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001675 OptionalClassMethodNames.push_back(
1676 MakeConstantString((*iter)->getSelector().getAsString()));
1677 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001678 } else {
1679 ClassMethodNames.push_back(
1680 MakeConstantString((*iter)->getSelector().getAsString()));
1681 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001682 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001683 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001684
1685 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1686 llvm::Constant *InstanceMethodList =
1687 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1688 llvm::Constant *ClassMethodList =
1689 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001690 llvm::Constant *OptionalInstanceMethodList =
1691 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1692 OptionalInstanceMethodTypes);
1693 llvm::Constant *OptionalClassMethodList =
1694 GenerateProtocolMethodList(OptionalClassMethodNames,
1695 OptionalClassMethodTypes);
1696
1697 // Property metadata: name, attributes, isSynthesized, setter name, setter
1698 // types, getter name, getter types.
1699 // The isSynthesized value is always set to 0 in a protocol. It exists to
1700 // simplify the runtime library by allowing it to use the same data
1701 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001702 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001703 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1704 PtrToInt8Ty, NULL);
1705 std::vector<llvm::Constant*> Properties;
1706 std::vector<llvm::Constant*> OptionalProperties;
1707
1708 // Add all of the property methods need adding to the method list and to the
1709 // property metadata list.
1710 for (ObjCContainerDecl::prop_iterator
1711 iter = PD->prop_begin(), endIter = PD->prop_end();
1712 iter != endIter ; iter++) {
1713 std::vector<llvm::Constant*> Fields;
David Blaikie581deb32012-06-06 20:45:41 +00001714 ObjCPropertyDecl *property = *iter;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001715
David Chisnall891dac72012-10-16 15:11:55 +00001716
1717 Fields.push_back(MakePropertyEncodingString(property, PD));
1718
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001719 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1720 property->getPropertyAttributes()));
1721 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1722 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1723 std::string TypeStr;
1724 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1725 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1726 InstanceMethodTypes.push_back(TypeEncoding);
1727 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1728 Fields.push_back(TypeEncoding);
1729 } else {
1730 Fields.push_back(NULLPtr);
1731 Fields.push_back(NULLPtr);
1732 }
1733 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1734 std::string TypeStr;
1735 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1736 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1737 InstanceMethodTypes.push_back(TypeEncoding);
1738 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1739 Fields.push_back(TypeEncoding);
1740 } else {
1741 Fields.push_back(NULLPtr);
1742 Fields.push_back(NULLPtr);
1743 }
1744 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1745 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1746 } else {
1747 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1748 }
1749 }
1750 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1751 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1752 llvm::Constant* PropertyListInitFields[] =
1753 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1754
1755 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001756 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001757 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1758 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1759 PropertyListInit, ".objc_property_list");
1760
1761 llvm::Constant *OptionalPropertyArray =
1762 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1763 OptionalProperties.size()) , OptionalProperties);
1764 llvm::Constant* OptionalPropertyListInitFields[] = {
1765 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1766 OptionalPropertyArray };
1767
1768 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001769 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001770 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1771 OptionalPropertyListInit->getType(), false,
1772 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1773 ".objc_property_list");
1774
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001775 // Protocols are objects containing lists of the methods implemented and
1776 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001777 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001778 PtrToInt8Ty,
1779 ProtocolList->getType(),
1780 InstanceMethodList->getType(),
1781 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001782 OptionalInstanceMethodList->getType(),
1783 OptionalClassMethodList->getType(),
1784 PropertyList->getType(),
1785 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001786 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001787 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001788 // The isa pointer must be set to a magic number so the runtime knows it's
1789 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001790 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001791 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001792 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1793 Elements.push_back(ProtocolList);
1794 Elements.push_back(InstanceMethodList);
1795 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001796 Elements.push_back(OptionalInstanceMethodList);
1797 Elements.push_back(OptionalClassMethodList);
1798 Elements.push_back(PropertyList);
1799 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001800 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001801 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001802 ".objc_protocol"), IdTy);
1803}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001804void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1805 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001806 SmallVector<Selector, 1> MethodSels;
1807 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001808
1809 std::vector<llvm::Constant*> Elements;
1810 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1811 const std::string CategoryName = "AnotherHack";
1812 Elements.push_back(MakeConstantString(CategoryName));
1813 Elements.push_back(MakeConstantString(ClassName));
1814 // Instance method list
1815 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1816 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1817 // Class method list
1818 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1819 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1820 // Protocol list
1821 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1822 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001823 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001824 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001825 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001826 ProtocolArrayTy,
1827 NULL);
1828 std::vector<llvm::Constant*> ProtocolElements;
1829 for (llvm::StringMapIterator<llvm::Constant*> iter =
1830 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1831 iter != endIter ; iter++) {
1832 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1833 PtrTy);
1834 ProtocolElements.push_back(Ptr);
1835 }
1836 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1837 ProtocolElements);
1838 ProtocolElements.clear();
1839 ProtocolElements.push_back(NULLPtr);
1840 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1841 ExistingProtocols.size()));
1842 ProtocolElements.push_back(ProtocolArray);
1843 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1844 ProtocolElements, ".objc_protocol_list"), PtrTy));
1845 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001846 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001847 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1848}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001849
David Chisnall917b28b2011-10-04 15:35:30 +00001850/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1851/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1852/// bits set to their values, LSB first, while larger ones are stored in a
1853/// structure of this / form:
1854///
1855/// struct { int32_t length; int32_t values[length]; };
1856///
1857/// The values in the array are stored in host-endian format, with the least
1858/// significant bit being assumed to come first in the bitfield. Therefore, a
1859/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1860/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +00001861llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001862 int bitCount = bits.size();
David Chisnall9d06ba82011-10-25 10:12:21 +00001863 int ptrBits =
1864 (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
1865 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001866 uint64_t val = 1;
1867 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001868 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001869 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001870 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001871 }
1872 llvm::SmallVector<llvm::Constant*, 8> values;
1873 int v=0;
1874 while (v < bitCount) {
1875 int32_t word = 0;
1876 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1877 if (bits[v]) word |= 1<<i;
1878 v++;
1879 }
1880 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1881 }
1882 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1883 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1884 llvm::Constant *fields[2] = {
1885 llvm::ConstantInt::get(Int32Ty, values.size()),
1886 array };
1887 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1888 NULL), fields);
David Chisnall49de5282011-10-08 08:54:36 +00001889 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00001890 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00001891}
1892
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001893void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001894 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1895 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001896 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001897 SmallVector<Selector, 16> InstanceMethodSels;
1898 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001899 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001900 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001901 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001902 InstanceMethodSels.push_back((*iter)->getSelector());
1903 std::string TypeStr;
1904 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001905 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001906 }
1907
1908 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001909 SmallVector<Selector, 16> ClassMethodSels;
1910 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001912 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001913 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001914 ClassMethodSels.push_back((*iter)->getSelector());
1915 std::string TypeStr;
1916 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001917 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001918 }
1919
1920 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001921 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001922 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1923 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001924 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1925 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001926 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001927
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001928 std::vector<llvm::Constant*> Elements;
1929 Elements.push_back(MakeConstantString(CategoryName));
1930 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001931 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001932 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001933 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001934 false), PtrTy));
1935 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001936 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001937 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001938 PtrTy));
1939 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001940 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001941 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001942 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001943 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001944 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001945}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001946
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001947llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001948 SmallVectorImpl<Selector> &InstanceMethodSels,
1949 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001950 ASTContext &Context = CGM.getContext();
1951 //
1952 // Property metadata: name, attributes, isSynthesized, setter name, setter
1953 // types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00001954 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001955 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1956 PtrToInt8Ty, NULL);
1957 std::vector<llvm::Constant*> Properties;
1958
1959
1960 // Add all of the property methods need adding to the method list and to the
1961 // property metadata list.
1962 for (ObjCImplDecl::propimpl_iterator
1963 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1964 iter != endIter ; iter++) {
1965 std::vector<llvm::Constant*> Fields;
David Blaikie262bc182012-04-30 02:36:29 +00001966 ObjCPropertyDecl *property = iter->getPropertyDecl();
David Blaikie581deb32012-06-06 20:45:41 +00001967 ObjCPropertyImplDecl *propertyImpl = *iter;
David Chisnall42ba04a2010-02-26 01:11:38 +00001968 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1969 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001970
David Chisnall891dac72012-10-16 15:11:55 +00001971 Fields.push_back(MakePropertyEncodingString(property, OID));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001972 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1973 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001974 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001975 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001976 std::string TypeStr;
1977 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1978 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001979 if (isSynthesized) {
1980 InstanceMethodTypes.push_back(TypeEncoding);
1981 InstanceMethodSels.push_back(getter->getSelector());
1982 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001983 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1984 Fields.push_back(TypeEncoding);
1985 } else {
1986 Fields.push_back(NULLPtr);
1987 Fields.push_back(NULLPtr);
1988 }
1989 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001990 std::string TypeStr;
1991 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1992 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001993 if (isSynthesized) {
1994 InstanceMethodTypes.push_back(TypeEncoding);
1995 InstanceMethodSels.push_back(setter->getSelector());
1996 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001997 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1998 Fields.push_back(TypeEncoding);
1999 } else {
2000 Fields.push_back(NULLPtr);
2001 Fields.push_back(NULLPtr);
2002 }
2003 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2004 }
2005 llvm::ArrayType *PropertyArrayTy =
2006 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2007 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2008 Properties);
2009 llvm::Constant* PropertyListInitFields[] =
2010 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2011
2012 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00002013 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002014 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2015 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2016 ".objc_property_list");
2017}
2018
David Chisnall29254f42012-01-31 18:59:20 +00002019void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2020 // Get the class declaration for which the alias is specified.
2021 ObjCInterfaceDecl *ClassDecl =
2022 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2023 std::string ClassName = ClassDecl->getNameAsString();
2024 std::string AliasName = OAD->getNameAsString();
2025 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2026}
2027
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002028void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2029 ASTContext &Context = CGM.getContext();
2030
2031 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002033 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00002034 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002035 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002036 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002037 EmitClassRef(SuperClassName);
2038 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002039
2040 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00002041 ObjCInterfaceDecl *ClassDecl =
2042 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00002043 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002044 // Emit the symbol that is used to generate linker errors if this class is
2045 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002046 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00002047 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002048 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002049 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002050 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00002051 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002052 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00002053 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00002056 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00002057 int instanceSize =
2058 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002059
2060 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002061 SmallVector<llvm::Constant*, 16> IvarNames;
2062 SmallVector<llvm::Constant*, 16> IvarTypes;
2063 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002065 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00002066 SmallVector<bool, 16> WeakIvars;
2067 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002068
Mike Stump1eb44332009-09-09 15:08:12 +00002069 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00002070 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002071 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2072 // class}. The runtime will then set this to the correct value on load.
John McCall260611a2012-06-20 06:18:46 +00002073 if (CGM.getContext().getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002074 instanceSize = 0 - (instanceSize - superInstanceSize);
2075 }
David Chisnall7f63cb02010-04-19 00:45:34 +00002076
Jordy Rosedb8264e2011-07-22 02:08:32 +00002077 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2078 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002079 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00002080 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002081 // Get the type encoding for this ivar
2082 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00002083 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002084 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002085 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00002086 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00002087 uint64_t Offset = BaseOffset;
John McCall260611a2012-06-20 06:18:46 +00002088 if (CGM.getContext().getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002089 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002090 }
David Chisnall63ff7032011-07-07 12:34:51 +00002091 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2092 // Create the direct offset value
2093 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2094 IVD->getNameAsString();
2095 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2096 if (OffsetVar) {
2097 OffsetVar->setInitializer(OffsetValue);
2098 // If this is the real definition, change its linkage type so that
2099 // different modules will use this one, rather than their private
2100 // copy.
2101 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2102 } else
2103 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002104 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002105 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002106 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002107 IVD->getNameAsString());
2108 IvarOffsets.push_back(OffsetValue);
2109 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002110 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2111 switch (lt) {
2112 case Qualifiers::OCL_Strong:
2113 StrongIvars.push_back(true);
2114 WeakIvars.push_back(false);
2115 break;
2116 case Qualifiers::OCL_Weak:
2117 StrongIvars.push_back(false);
2118 WeakIvars.push_back(true);
2119 break;
2120 default:
2121 StrongIvars.push_back(false);
2122 WeakIvars.push_back(false);
2123 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002124 }
David Chisnall917b28b2011-10-04 15:35:30 +00002125 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2126 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002127 llvm::GlobalVariable *IvarOffsetArray =
2128 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2129
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002130
2131 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002132 SmallVector<Selector, 16> InstanceMethodSels;
2133 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002134 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002135 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002136 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002137 InstanceMethodSels.push_back((*iter)->getSelector());
2138 std::string TypeStr;
2139 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002140 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002141 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002142
2143 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2144 InstanceMethodTypes);
2145
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002146
2147 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002148 SmallVector<Selector, 16> ClassMethodSels;
2149 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002150 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002151 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002152 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002153 ClassMethodSels.push_back((*iter)->getSelector());
2154 std::string TypeStr;
2155 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002156 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002157 }
2158 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002159 SmallVector<std::string, 16> Protocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00002160 for (ObjCInterfaceDecl::protocol_iterator
2161 I = ClassDecl->protocol_begin(),
2162 E = ClassDecl->protocol_end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002163 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002164
2165
2166
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002167 // Get the superclass pointer.
2168 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002169 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002170 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2171 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002172 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002173 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002174 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002175 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002176 // Generate the method and instance variable lists
2177 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002178 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002179 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002180 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002181 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2182 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002183 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002184 // we emit a symbol containing the offset for each ivar in the class. This
2185 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2186 // for the legacy ABI, without causing problems. The converse is also
2187 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002188
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002189 // Offset pointer for getting at the correct field in the ivar list when
2190 // setting up the alias. These are: The base address for the global, the
2191 // ivar array (second field), the ivar in this list (set for each ivar), and
2192 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002193 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002194 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002195 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002196 llvm::ConstantInt::get(IndexTy, 2) };
2197
Jordy Rosedb8264e2011-07-22 02:08:32 +00002198 unsigned ivarIndex = 0;
2199 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2200 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002201 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002202 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002203 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002204 // Get the correct ivar field
2205 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002206 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002207 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002208 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2209 if (offset) {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002210 offset->setInitializer(offsetValue);
2211 // If this is the real definition, change its linkage type so that
2212 // different modules will use this one, rather than their private
2213 // copy.
2214 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002215 } else {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002216 // Add a new alias if there isn't one already.
2217 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2218 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2219 (void) offset; // Silence dead store warning.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002220 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002221 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002222 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002223 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002224 //Generate metaclass for class methods
2225 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00002226 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002227 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002228 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002229
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002230 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002231 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002232 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00002233 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002234 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002235 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002236 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002237
2238 // Resolve the class aliases, if they exist.
2239 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002240 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002241 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002242 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002243 ClassPtrAlias = 0;
2244 }
2245 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002246 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002247 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002248 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002249 MetaClassPtrAlias = 0;
2250 }
2251
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002252 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002253 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002254 Classes.push_back(ClassStruct);
2255}
2256
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002257
Mike Stump1eb44332009-09-09 15:08:12 +00002258llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002259 // Only emit an ObjC load function if no Objective-C stuff has been called
2260 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002261 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002262 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002263
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002264 // Add all referenced protocols to a category.
2265 GenerateProtocolHolderCategory();
2266
Chris Lattner2acc6e32011-07-18 04:24:23 +00002267 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002268 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002269 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002270 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002271 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002272 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002273 }
2274
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002275 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002276 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002277 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002278 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002279 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002280 ConstantStrings.size() + 1);
2281 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002282
David Blaikie4e4d0842012-03-11 07:00:24 +00002283 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002284
Daniel Dunbar1b096952009-11-29 02:38:47 +00002285 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002286
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002287 Elements.push_back(MakeConstantString(StringClass,
2288 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002289 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002290 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002291 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002292 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002293 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002294 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002295 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002296 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002297 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002298 Elements.clear();
2299 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002300 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002301 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002302 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002303 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002304 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002305 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002306 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002307 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002308 llvm::Type::getInt16Ty(VMContext),
2309 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002310 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002311
2312 Elements.clear();
2313 // Pointer to an array of selectors used in this module.
2314 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002315 std::vector<llvm::GlobalAlias*> SelectorAliases;
2316 for (SelectorMap::iterator iter = SelectorTable.begin(),
2317 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2318
2319 std::string SelNameStr = iter->first.getAsString();
2320 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2321
Chris Lattner5f9e2722011-07-23 10:55:15 +00002322 SmallVectorImpl<TypedSelector> &Types = iter->second;
2323 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002324 e = Types.end() ; i!=e ; i++) {
2325
2326 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2327 if (!i->first.empty())
2328 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2329
2330 Elements.push_back(SelName);
2331 Elements.push_back(SelectorTypeEncoding);
2332 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2333 Elements.clear();
2334
2335 // Store the selector alias for later replacement
2336 SelectorAliases.push_back(i->second);
2337 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002338 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002339 unsigned SelectorCount = Selectors.size();
2340 // NULL-terminate the selector list. This should not actually be required,
2341 // because the selector list has a length field. Unfortunately, the GCC
2342 // runtime decides to ignore the length field and expects a NULL terminator,
2343 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002344 Elements.push_back(NULLPtr);
2345 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002346 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002347 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002348
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002349 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002350 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2351 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002352 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002353 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002354 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002355
2356 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002357 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2358
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002359 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002360 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002361 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002362 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002363 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002364 // If selectors are defined as an opaque type, cast the pointer to this
2365 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002366 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002367 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2368 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002369 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002370
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002371 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002372 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002373 Classes.size()));
2374 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002375 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002376 Categories.size()));
2377 // Create an array of classes, then categories, then static object instances
2378 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2379 // NULL-terminated list of static object instances (mainly constant strings)
2380 Classes.push_back(Statics);
2381 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002382 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002383 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002384 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002385 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2386
2387 // The symbol table is contained in a module which has some version-checking
2388 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002389 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002390 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002391 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002392 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002393 // Runtime version, used for ABI compatibility checking.
2394 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002395 // sizeof(ModuleTy)
Micah Villmow25a6a842012-10-08 16:25:52 +00002396 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002397 Elements.push_back(
2398 llvm::ConstantInt::get(LongTy,
2399 td.getTypeSizeInBits(ModuleTy) /
2400 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002401
2402 // The path to the source file where this module was declared
2403 SourceManager &SM = CGM.getContext().getSourceManager();
2404 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2405 std::string path =
2406 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2407 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002408 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002409
David Chisnallf0748852011-07-07 11:22:31 +00002410 if (RuntimeVersion >= 10)
David Blaikie4e4d0842012-03-11 07:00:24 +00002411 switch (CGM.getLangOpts().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002412 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002413 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002414 break;
David Chisnallf0748852011-07-07 11:22:31 +00002415 case LangOptions::NonGC:
David Blaikie4e4d0842012-03-11 07:00:24 +00002416 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +00002417 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2418 else
2419 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2420 break;
2421 case LangOptions::HybridGC:
2422 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2423 break;
2424 }
David Chisnalla2120032011-05-22 22:37:08 +00002425
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002426 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2427
2428 // Create the load function calling the runtime entry point with the module
2429 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002430 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002431 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002432 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2433 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002434 llvm::BasicBlock *EntryBB =
2435 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002436 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002437 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002438
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002439 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002440 llvm::FunctionType::get(Builder.getVoidTy(),
2441 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002442 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002443 Builder.CreateCall(Register, Module);
David Chisnall29254f42012-01-31 18:59:20 +00002444
David Chisnalldccaa232012-02-01 19:16:56 +00002445 if (!ClassAliases.empty()) {
David Chisnall29254f42012-01-31 18:59:20 +00002446 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2447 llvm::FunctionType *RegisterAliasTy =
2448 llvm::FunctionType::get(Builder.getVoidTy(),
2449 ArgTypes, false);
2450 llvm::Function *RegisterAlias = llvm::Function::Create(
2451 RegisterAliasTy,
2452 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2453 &TheModule);
2454 llvm::BasicBlock *AliasBB =
2455 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2456 llvm::BasicBlock *NoAliasBB =
2457 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2458
2459 // Branch based on whether the runtime provided class_registerAlias_np()
2460 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2461 llvm::Constant::getNullValue(RegisterAlias->getType()));
2462 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2463
2464 // The true branch (has alias registration fucntion):
2465 Builder.SetInsertPoint(AliasBB);
2466 // Emit alias registration calls:
2467 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2468 iter != ClassAliases.end(); ++iter) {
2469 llvm::Constant *TheClass =
2470 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2471 true);
2472 if (0 != TheClass) {
2473 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2474 Builder.CreateCall2(RegisterAlias, TheClass,
2475 MakeConstantString(iter->second));
2476 }
2477 }
2478 // Jump to end:
2479 Builder.CreateBr(NoAliasBB);
2480
2481 // Missing alias registration function, just return from the function:
2482 Builder.SetInsertPoint(NoAliasBB);
2483 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002484 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002485
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002486 return LoadFunction;
2487}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002488
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002489llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002490 const ObjCContainerDecl *CD) {
2491 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002492 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002493 StringRef CategoryName = OCD ? OCD->getName() : "";
2494 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002495 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002496 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002497
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002498 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002499 llvm::FunctionType *MethodTy =
John McCallde5d3c72012-02-17 03:33:10 +00002500 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002501 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2502 MethodName, isClassMethod);
2503
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002504 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002505 = llvm::Function::Create(MethodTy,
2506 llvm::GlobalValue::InternalLinkage,
2507 FunctionName,
2508 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002509 return Method;
2510}
2511
David Chisnall789ecde2011-05-23 22:33:28 +00002512llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002513 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002514}
2515
David Chisnall789ecde2011-05-23 22:33:28 +00002516llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002517 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002518}
2519
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002520llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2521 bool copy) {
2522 return 0;
2523}
2524
David Chisnall789ecde2011-05-23 22:33:28 +00002525llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002526 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002527}
David Chisnall789ecde2011-05-23 22:33:28 +00002528llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002529 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002530}
Fariborz Jahaniane3173022012-01-06 18:07:23 +00002531llvm::Constant *CGObjCGNU::GetCppAtomicObjectFunction() {
2532 return 0;
2533}
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002534
Daniel Dunbar309a4362009-07-24 07:40:24 +00002535llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002536 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002537}
2538
David Chisnall9f6614e2011-03-23 16:36:54 +00002539void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002540 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002541 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002542}
Chris Lattner5dc08672009-05-08 00:11:50 +00002543
David Chisnall0faa5162009-12-24 02:26:34 +00002544
David Chisnall9f6614e2011-03-23 16:36:54 +00002545void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002546 const ObjCAtTryStmt &S) {
2547 // Unlike the Apple non-fragile runtimes, which also uses
2548 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2549 // EH support isn't a veneer over C++ EH. Instead, exception
2550 // objects are created by __objc_exception_throw and destroyed by
2551 // the personality function; this avoids the need for bracketing
2552 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2553 // (or even _Unwind_DeleteException), but probably doesn't
2554 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002555 //
David Chisnall80558d22011-03-20 21:35:39 +00002556 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002557 // exception handler.
2558 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2559 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002560}
2561
David Chisnall9f6614e2011-03-23 16:36:54 +00002562void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002563 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002564 llvm::Value *ExceptionAsObject;
2565
Chris Lattner5dc08672009-05-08 00:11:50 +00002566 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002567 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002568 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002569 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002570 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002571 "Unexpected rethrow outside @catch block.");
2572 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2573 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002574 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
Eli Friedmanc972c922012-08-10 21:26:17 +00002575 CGF.EmitCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2576 CGF.Builder.CreateUnreachable();
Chris Lattner5dc08672009-05-08 00:11:50 +00002577 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002578}
2579
David Chisnall9f6614e2011-03-23 16:36:54 +00002580llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002581 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002582 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002583 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002584 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002585}
2586
David Chisnall9f6614e2011-03-23 16:36:54 +00002587void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002588 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002589 CGBuilderTy B = CGF.Builder;
2590 src = EnforceType(B, src, IdTy);
2591 dst = EnforceType(B, dst, PtrToIdTy);
2592 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002593}
2594
David Chisnall9f6614e2011-03-23 16:36:54 +00002595void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002596 llvm::Value *src, llvm::Value *dst,
2597 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002598 CGBuilderTy B = CGF.Builder;
2599 src = EnforceType(B, src, IdTy);
2600 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002601 if (!threadlocal)
2602 B.CreateCall2(GlobalAssignFn, src, dst);
2603 else
2604 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002605 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002606}
2607
David Chisnall9f6614e2011-03-23 16:36:54 +00002608void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002609 llvm::Value *src, llvm::Value *dst,
2610 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002611 CGBuilderTy B = CGF.Builder;
2612 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002613 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002614 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002615}
2616
David Chisnall9f6614e2011-03-23 16:36:54 +00002617void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002618 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002619 CGBuilderTy B = CGF.Builder;
2620 src = EnforceType(B, src, IdTy);
2621 dst = EnforceType(B, dst, PtrToIdTy);
2622 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002623}
2624
David Chisnall9f6614e2011-03-23 16:36:54 +00002625void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002626 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002627 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002628 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002629 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002630 DestPtr = EnforceType(B, DestPtr, PtrTy);
2631 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002632
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002633 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002634}
2635
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002636llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2637 const ObjCInterfaceDecl *ID,
2638 const ObjCIvarDecl *Ivar) {
2639 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2640 + '.' + Ivar->getNameAsString();
2641 // Emit the variable and initialize it with what we think the correct value
2642 // is. This allows code compiled with non-fragile ivars to work correctly
2643 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002644 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2645 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002646 // This will cause a run-time crash if we accidentally use it. A value of
2647 // 0 would seem more sensible, but will silently overwrite the isa pointer
2648 // causing a great deal of confusion.
2649 uint64_t Offset = -1;
2650 // We can't call ComputeIvarBaseOffset() here if we have the
2651 // implementation, because it will create an invalid ASTRecordLayout object
2652 // that we are then stuck with forever, so we only initialize the ivar
2653 // offset variable with a guess if we only have the interface. The
2654 // initializer will be reset later anyway, when we are generating the class
2655 // description.
2656 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002657 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002658 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2659
David Chisnall49de5282011-10-08 08:54:36 +00002660 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002661 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002662 // Don't emit the guess in non-PIC code because the linker will not be able
2663 // to replace it with the real version for a library. In non-PIC code you
2664 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002665 // GCC-compiled class.
Chandler Carruth5e219cf2012-04-08 16:40:35 +00002666 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002667 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002668 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002669 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2670 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2671 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2672 IvarOffsetGV, Name);
2673 } else {
2674 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002675 llvm::Type::getInt32PtrTy(VMContext), false,
2676 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002677 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002678 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002679 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002680}
2681
David Chisnall9f6614e2011-03-23 16:36:54 +00002682LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002683 QualType ObjectTy,
2684 llvm::Value *BaseValue,
2685 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002686 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002687 const ObjCInterfaceDecl *ID =
2688 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002689 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2690 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002691}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002692
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002693static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2694 const ObjCInterfaceDecl *OID,
2695 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002696 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2697 next = next->getNextIvar()) {
2698 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002699 return OID;
2700 }
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002702 // Otherwise check in the super class.
2703 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2704 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002706 return 0;
2707}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002708
David Chisnall9f6614e2011-03-23 16:36:54 +00002709llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002710 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002711 const ObjCIvarDecl *Ivar) {
John McCall260611a2012-06-20 06:18:46 +00002712 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002713 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002714 if (RuntimeVersion < 10)
2715 return CGF.Builder.CreateZExtOrBitCast(
2716 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2717 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2718 PtrDiffTy);
2719 std::string name = "__objc_ivar_offset_value_" +
2720 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2721 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2722 if (!Offset)
2723 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002724 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2725 llvm::Constant::getNullValue(IntTy), name);
David Chisnall66148452012-04-06 15:39:12 +00002726 Offset = CGF.Builder.CreateLoad(Offset);
2727 if (Offset->getType() != PtrDiffTy)
2728 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2729 return Offset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002730 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002731 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Richard Trieu243f1082011-09-21 02:46:06 +00002732 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002733}
2734
David Chisnall9f6614e2011-03-23 16:36:54 +00002735CGObjCRuntime *
2736clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall260611a2012-06-20 06:18:46 +00002737 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +00002738 case ObjCRuntime::GNUstep:
David Chisnall9f6614e2011-03-23 16:36:54 +00002739 return new CGObjCGNUstep(CGM);
John McCall260611a2012-06-20 06:18:46 +00002740
David Chisnall11d3f4c2012-07-03 20:49:52 +00002741 case ObjCRuntime::GCC:
John McCall260611a2012-06-20 06:18:46 +00002742 return new CGObjCGCC(CGM);
2743
John McCallf7226fb2012-07-12 02:07:58 +00002744 case ObjCRuntime::ObjFW:
2745 return new CGObjCObjFW(CGM);
2746
John McCall260611a2012-06-20 06:18:46 +00002747 case ObjCRuntime::FragileMacOSX:
2748 case ObjCRuntime::MacOSX:
2749 case ObjCRuntime::iOS:
2750 llvm_unreachable("these runtimes are not GNU runtimes");
2751 }
2752 llvm_unreachable("bad runtime");
Chris Lattner0f984262008-03-01 08:50:34 +00002753}