blob: 49323c58b106f63518734b749a94365fe187a258 [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 Lattner5dc08672009-05-08 00:11:50 +000021
Chris Lattnerdce14062008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnall80558d22011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000038
Chris Lattner5f9e2722011-07-23 10:55:15 +000039#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000040
41
Chris Lattnerdce14062008-06-26 04:19:03 +000042using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000043using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000044
Chris Lattner0f984262008-03-01 08:50:34 +000045
Chris Lattner0f984262008-03-01 08:50:34 +000046namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000047/// Class that lazily initialises the runtime function. Avoids inserting the
48/// types and the function declaration into a module if they're not used, and
49/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000050class LazyRuntimeFunction {
51 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000052 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000053 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000054 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000055 public:
David Chisnall81a65f52011-03-26 11:48:37 +000056 /// Constructor leaves this class uninitialized, because it is intended to
57 /// be used as a field in another class and not all of the types that are
58 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000059 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60
David Chisnall81a65f52011-03-26 11:48:37 +000061 /// Initialises the lazy function with the name, return type, and the types
62 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000063 END_WITH_NULL
64 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000065 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000066 CGM =Mod;
67 FunctionName = name;
68 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000069 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000070 va_list Args;
71 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000072 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000073 ArgTys.push_back(ArgTy);
74 va_end(Args);
75 // Push the return type on at the end so we can pop it off easily
76 ArgTys.push_back(RetTy);
77 }
David Chisnall81a65f52011-03-26 11:48:37 +000078 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000080 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000081 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000082 if (0 == FunctionName) return 0;
83 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000084 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000085 ArgTys.pop_back();
86 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000088 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000089 // We won't need to use the types again, so we may as well clean up the
90 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000091 ArgTys.resize(0);
92 }
93 return Function;
94 }
David Chisnall789ecde2011-05-23 22:33:28 +000095 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000096 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000097 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000098
David Chisnall9f6614e2011-03-23 16:36:54 +000099};
100
101
David Chisnall81a65f52011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
103/// Objective-C support that are specific to the GNU family of runtimes (GCC and
104/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000106protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000107 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000108 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000109 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000110 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000111 /// strut objc_super. Used for sending messages to super. This structure
112 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000113 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000114 /// struct objc_super*. The type of the argument to the superclass message
115 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000116 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000117 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
118 /// SEL is included in a header somewhere, in which case it will be whatever
119 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000120 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000121 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
122 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000123 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000124 /// Pointer to i8 - LLVM type of char*, for all of the places where the
125 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000126 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000127 /// Instance Method Pointer type. This is a pointer to a function that takes,
128 /// at a minimum, an object and a selector, and is the generic type for
129 /// Objective-C methods. Due to differences between variadic / non-variadic
130 /// calling conventions, it must always be cast to the correct type before
131 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000132 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000133 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
134 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
135 /// but if the runtime header declaring it is included then it may be a
136 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000137 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000138 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
139 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000140 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// The clang type of id. Used when using the clang CGCall infrastructure to
142 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000143 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000144 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000145 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000146 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
147 /// used in the code to document the difference between i8* meaning a pointer
148 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000149 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000150 /// LLVM type for C long type. The runtime uses this in a lot of places where
151 /// it should be using intptr_t, but we can't fix this without breaking
152 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000153 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000154 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000155 llvm::IntegerType *SizeTy;
David Chisnall49de5282011-10-08 08:54:36 +0000156 /// LLVM type for C intptr_t.
157 llvm::IntegerType *IntPtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000158 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000159 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000160 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
161 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000162 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000163 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000164 llvm::Type *BoolTy;
David Chisnall917b28b2011-10-04 15:35:30 +0000165 /// 32-bit integer type, to save us needing to look it up every time it's used.
166 llvm::IntegerType *Int32Ty;
167 /// 64-bit integer type, to save us needing to look it up every time it's used.
168 llvm::IntegerType *Int64Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000169 /// Metadata kind used to tie method lookups to message sends. The GNUstep
170 /// runtime provides some LLVM passes that can use this to do things like
171 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000172 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000173 /// Helper function that generates a constant string and returns a pointer to
174 /// the start of the string. The result of this function can be used anywhere
175 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000176 llvm::Constant *MakeConstantString(const std::string &Str,
177 const std::string &Name="") {
178 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000179 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000180 }
David Chisnall81a65f52011-03-26 11:48:37 +0000181 /// Emits a linkonce_odr string, whose name is the prefix followed by the
182 /// string value. This allows the linker to combine the strings between
183 /// different modules. Used for EH typeinfo names, selector strings, and a
184 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000185 llvm::Constant *ExportUniqueString(const std::string &Str,
186 const std::string prefix) {
187 std::string name = prefix + Str;
188 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
189 if (!ConstStr) {
190 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
191 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
192 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
193 }
Jay Foada5c04342011-07-21 14:31:17 +0000194 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000195 }
David Chisnall81a65f52011-03-26 11:48:37 +0000196 /// Generates a global structure, initialized by the elements in the vector.
197 /// The element types must match the types of the structure elements in the
198 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000199 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000200 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000201 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000202 llvm::GlobalValue::LinkageTypes linkage
203 =llvm::GlobalValue::InternalLinkage) {
204 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
205 return new llvm::GlobalVariable(TheModule, Ty, false,
206 linkage, C, Name);
207 }
David Chisnall81a65f52011-03-26 11:48:37 +0000208 /// Generates a global array. The vector must contain the same number of
209 /// elements that the array type declares, of the type specified as the array
210 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000211 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000212 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000213 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000214 llvm::GlobalValue::LinkageTypes linkage
215 =llvm::GlobalValue::InternalLinkage) {
216 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
217 return new llvm::GlobalVariable(TheModule, Ty, false,
218 linkage, C, Name);
219 }
David Chisnall81a65f52011-03-26 11:48:37 +0000220 /// Generates a global array, inferring the array type from the specified
221 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000222 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000223 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000224 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000225 llvm::GlobalValue::LinkageTypes linkage
226 =llvm::GlobalValue::InternalLinkage) {
227 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
228 return MakeGlobal(ArrayTy, V, Name, linkage);
229 }
David Chisnall81a65f52011-03-26 11:48:37 +0000230 /// Ensures that the value has the required type, by inserting a bitcast if
231 /// required. This function lets us avoid inserting bitcasts that are
232 /// redundant.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000233 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnallc7ef4622011-03-23 22:52:06 +0000234 if (V->getType() == Ty) return V;
235 return B.CreateBitCast(V, Ty);
236 }
237 // Some zeros used for GEPs in lots of places.
238 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000239 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000240 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000241 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000242 llvm::LLVMContext &VMContext;
243private:
David Chisnall81a65f52011-03-26 11:48:37 +0000244 /// Placeholder for the class. Lots of things refer to the class before we've
245 /// actually emitted it. We use this alias as a placeholder, and then replace
246 /// it with a pointer to the class structure before finally emitting the
247 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000248 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000249 /// Placeholder for the metaclass. Lots of things refer to the class before
250 /// we've / actually emitted it. We use this alias as a placeholder, and then
251 /// replace / it with a pointer to the metaclass structure before finally
252 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000253 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000254 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000255 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000256 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000257 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000258 /// All of the Objective-C constant strings that have been generated for this
259 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000260 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000261 /// Map from string values to Objective-C constant strings in the output.
262 /// Used to prevent emitting Objective-C strings more than once. This should
263 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000264 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000265 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000266 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000267 /// For each variant of a selector, we store the type encoding and a
268 /// placeholder value. For an untyped selector, the type will be the empty
269 /// string. Selector references are all done via the module's selector table,
270 /// so we create an alias as a placeholder and then replace it with the real
271 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000272 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000273 /// Type of the selector map. This is roughly equivalent to the structure
274 /// used in the GNUstep runtime, which maintains a list of all of the valid
275 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000276 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000277 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000278 /// A map from selectors to selector types. This allows us to emit all
279 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000280 SelectorMap SelectorTable;
281
David Chisnall81a65f52011-03-26 11:48:37 +0000282 /// Selectors related to memory management. When compiling in GC mode, we
283 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000284 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000285 /// Runtime functions used for memory management in GC mode. Note that clang
286 /// supports code generation for calling these functions, but neither GNU
287 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000288 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
289 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000290
David Chisnall9735ca62011-03-25 11:57:33 +0000291protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000292 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000293 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000294 /// Function used for rethrowing exceptions, used at the end of @finally or
295 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000296 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// Function called when entering a catch function. This is required for
298 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000299 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000300 /// Function called when exiting from a catch block. Used to do exception
301 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000302 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000303 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000304 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000305 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000306 LazyRuntimeFunction SyncExitFn;
307
David Chisnall9735ca62011-03-25 11:57:33 +0000308private:
309
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// Function called if fast enumeration detects that the collection is
311 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000312 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000313 /// Function for implementing synthesized property getters that return an
314 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000315 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// Function for implementing synthesized property setters that return an
317 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000318 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000319 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000320 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000321 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000322 LazyRuntimeFunction SetStructPropertyFn;
323
David Chisnall81a65f52011-03-26 11:48:37 +0000324 /// The version of the runtime that this class targets. Must match the
325 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000326 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000327 /// The version of the protocol class. Used to differentiate between ObjC1
328 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
329 /// components and can not contain declared properties. We always emit
330 /// Objective-C 2 property structures, but we have to pretend that they're
331 /// Objective-C 1 property structures when targeting the GCC runtime or it
332 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000333 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000334private:
David Chisnall81a65f52011-03-26 11:48:37 +0000335 /// Generates an instance variable list structure. This is a structure
336 /// containing a size and an array of structures containing instance variable
337 /// metadata. This is used purely for introspection in the fragile ABI. In
338 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000339 llvm::Constant *GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000340 const SmallVectorImpl<llvm::Constant *> &IvarNames,
341 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
342 const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000343 /// Generates a method list structure. This is a structure containing a size
344 /// and an array of structures containing method metadata.
345 ///
346 /// This structure is used by both classes and categories, and contains a next
347 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000348 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
349 const StringRef &CategoryName,
350 const SmallVectorImpl<Selector> &MethodSels,
351 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000352 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000353 /// Emits an empty protocol. This is used for @protocol() where no protocol
354 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
355 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000356 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000357 /// Generates a list of property metadata structures. This follows the same
358 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000359 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000360 SmallVectorImpl<Selector> &InstanceMethodSels,
361 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000362 /// Generates a list of referenced protocols. Classes, categories, and
363 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000364 llvm::Constant *GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000365 const SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000366 /// To ensure that all protocols are seen by the runtime, we add a category on
367 /// a class defined in the runtime, declaring no methods, but adopting the
368 /// protocols. This is a horribly ugly hack, but it allows us to collect all
369 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000370 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000371 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000372 llvm::Constant *GenerateClassStructure(
373 llvm::Constant *MetaClass,
374 llvm::Constant *SuperClass,
375 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000376 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000377 llvm::Constant *Version,
378 llvm::Constant *InstanceSize,
379 llvm::Constant *IVars,
380 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000381 llvm::Constant *Protocols,
382 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000383 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +0000384 llvm::Constant *StrongIvarBitmap,
385 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +0000386 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000387 /// Generates a method list. This is used by protocols to define the required
388 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000389 llvm::Constant *GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 const SmallVectorImpl<llvm::Constant *> &MethodNames,
391 const SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000392 /// Returns a selector with the specified type encoding. An empty string is
393 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000394 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
395 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000396 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000397 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
398 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000399 /// Emits a reference to a class. This allows the linker to object if there
400 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000401 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000402 /// Emits a pointer to the named class
David Chisnalld3fc7292011-06-30 10:14:37 +0000403 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
404 bool isWeak);
David Chisnallc7ef4622011-03-23 22:52:06 +0000405protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000406 /// Looks up the method for sending a message to the specified object. This
407 /// mechanism differs between the GCC and GNU runtimes, so this method must be
408 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000409 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
410 llvm::Value *&Receiver,
411 llvm::Value *cmd,
412 llvm::MDNode *node) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000413 /// Looks up the method for sending a message to a superclass. This
414 /// mechanism differs between the GCC and GNU runtimes, so this method must
415 /// be overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000416 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
417 llvm::Value *ObjCSuper,
418 llvm::Value *cmd) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000419 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
420 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
421 /// bits set to their values, LSB first, while larger ones are stored in a
422 /// structure of this / form:
423 ///
424 /// struct { int32_t length; int32_t values[length]; };
425 ///
426 /// The values in the array are stored in host-endian format, with the least
427 /// significant bit being assumed to come first in the bitfield. Therefore,
428 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
429 /// while a bitfield / with the 63rd bit set will be 1<<64.
430 llvm::Constant *MakeBitField(llvm::SmallVectorImpl<bool> &bits);
Chris Lattner0f984262008-03-01 08:50:34 +0000431public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000432 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
433 unsigned protocolClassVersion);
434
David Chisnall0d13f6f2010-01-23 02:40:42 +0000435 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000436
437 virtual RValue
438 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000439 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000440 QualType ResultType,
441 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000442 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000443 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000444 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000445 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000446 virtual RValue
447 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000448 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000449 QualType ResultType,
450 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000451 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000452 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000453 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000454 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000455 const CallArgList &CallArgs,
456 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000457 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000458 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000459 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
460 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000461 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
462 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000463 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
465 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000466 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000467 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
468 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000469 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000470 const ObjCProtocolDecl *PD);
471 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000472 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000473 virtual llvm::Constant *GetPropertyGetFunction();
474 virtual llvm::Constant *GetPropertySetFunction();
475 virtual llvm::Constant *GetSetStructFunction();
476 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000477 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000478
David Chisnall9f6614e2011-03-23 16:36:54 +0000479 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000480 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000481 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000482 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000483 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000484 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000485 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000486 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000487 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000488 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000489 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000490 llvm::Value *src, llvm::Value *dest,
491 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000492 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000493 llvm::Value *src, llvm::Value *dest,
494 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000495 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000496 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000497 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000498 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000499 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000500 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000501 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000502 QualType ObjectTy,
503 llvm::Value *BaseValue,
504 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000505 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000506 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000507 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000508 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000509 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000510 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000511 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000512 return NULLPtr;
513 }
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000514
515 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
516 return 0;
517 }
Chris Lattner0f984262008-03-01 08:50:34 +0000518};
David Chisnall81a65f52011-03-26 11:48:37 +0000519/// Class representing the legacy GCC Objective-C ABI. This is the default when
520/// -fobjc-nonfragile-abi is not specified.
521///
522/// The GCC ABI target actually generates code that is approximately compatible
523/// with the new GNUstep runtime ABI, but refrains from using any features that
524/// would not work with the GCC runtime. For example, clang always generates
525/// the extended form of the class structure, and the extra fields are simply
526/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000527class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000528 /// The GCC ABI message lookup function. Returns an IMP pointing to the
529 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000530 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000531 /// The GCC ABI superclass message lookup function. Takes a pointer to a
532 /// structure describing the receiver and the class, and a selector as
533 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000534 LazyRuntimeFunction MsgLookupSuperFn;
535protected:
536 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
537 llvm::Value *&Receiver,
538 llvm::Value *cmd,
539 llvm::MDNode *node) {
540 CGBuilderTy &Builder = CGF.Builder;
David Chisnall6f3887e2011-10-28 17:55:06 +0000541 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000542 EnforceType(Builder, Receiver, IdTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000543 EnforceType(Builder, cmd, SelectorTy) };
544 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
545 imp->setMetadata(msgSendMDKind, node);
546 return imp.getInstruction();
David Chisnallc7ef4622011-03-23 22:52:06 +0000547 }
548 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
549 llvm::Value *ObjCSuper,
550 llvm::Value *cmd) {
551 CGBuilderTy &Builder = CGF.Builder;
552 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
553 PtrToObjCSuperTy), cmd};
Jay Foad4c7d9f12011-07-15 08:37:34 +0000554 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000555 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000556 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000557 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
558 // IMP objc_msg_lookup(id, SEL);
559 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
560 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
561 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
562 PtrToObjCSuperTy, SelectorTy, NULL);
563 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000564};
David Chisnall81a65f52011-03-26 11:48:37 +0000565/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000566class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000567 /// The slot lookup function. Returns a pointer to a cacheable structure
568 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000569 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000570 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
571 /// a structure describing the receiver and the class, and a selector as
572 /// arguments. Returns the slot for the corresponding method. Superclass
573 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000574 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000575 /// Type of an slot structure pointer. This is returned by the various
576 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000577 llvm::Type *SlotTy;
578 protected:
579 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
580 llvm::Value *&Receiver,
581 llvm::Value *cmd,
582 llvm::MDNode *node) {
583 CGBuilderTy &Builder = CGF.Builder;
584 llvm::Function *LookupFn = SlotLookupFn;
585
586 // Store the receiver on the stack so that we can reload it later
587 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
588 Builder.CreateStore(Receiver, ReceiverPtr);
589
590 llvm::Value *self;
591
592 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
593 self = CGF.LoadObjCSelf();
594 } else {
595 self = llvm::ConstantPointerNull::get(IdTy);
596 }
597
598 // The lookup function is guaranteed not to capture the receiver pointer.
599 LookupFn->setDoesNotCapture(1);
600
David Chisnall6f3887e2011-10-28 17:55:06 +0000601 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000602 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
603 EnforceType(Builder, cmd, SelectorTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000604 EnforceType(Builder, self, IdTy) };
605 llvm::CallSite slot = CGF.EmitCallOrInvoke(LookupFn, args);
606 slot.setOnlyReadsMemory();
David Chisnallc7ef4622011-03-23 22:52:06 +0000607 slot->setMetadata(msgSendMDKind, node);
608
609 // Load the imp from the slot
David Chisnall6f3887e2011-10-28 17:55:06 +0000610 llvm::Value *imp =
611 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnallc7ef4622011-03-23 22:52:06 +0000612
613 // The lookup function may have changed the receiver, so make sure we use
614 // the new one.
615 Receiver = Builder.CreateLoad(ReceiverPtr, true);
616 return imp;
617 }
618 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
619 llvm::Value *ObjCSuper,
620 llvm::Value *cmd) {
621 CGBuilderTy &Builder = CGF.Builder;
622 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
623
Jay Foad4c7d9f12011-07-15 08:37:34 +0000624 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000625 slot->setOnlyReadsMemory();
626
627 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
628 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000629 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000630 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner7650d952011-06-18 22:49:11 +0000631 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000632 PtrTy, PtrTy, IntTy, IMPTy, NULL);
633 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
634 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
635 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
636 SelectorTy, IdTy, NULL);
637 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
638 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
639 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000640 // If we're in ObjC++ mode, then we want to make
641 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000642 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000643 // void *__cxa_begin_catch(void *e)
644 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
645 // void __cxa_end_catch(void)
David Chisnall4bd5d092011-08-08 17:26:06 +0000646 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000647 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000648 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000649 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000650 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000651};
652
Chris Lattner0f984262008-03-01 08:50:34 +0000653} // end anonymous namespace
654
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000655
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000656/// Emits a reference to a dummy variable which is emitted with each class.
657/// This ensures that a linker error will be generated when trying to link
658/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000659void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000660 std::string symbolRef = "__objc_class_ref_" + className;
661 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000662 if (TheModule.getGlobalVariable(symbolRef))
663 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000664 std::string symbolName = "__objc_class_name_" + className;
665 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
666 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000667 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
668 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000669 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000670 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000671 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000672}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000673
Chris Lattner5f9e2722011-07-23 10:55:15 +0000674static std::string SymbolNameForMethod(const StringRef &ClassName,
675 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000676 bool isClassMethod) {
677 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000678 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
679 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000680 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000681 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000682}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000683
David Chisnall9f6614e2011-03-23 16:36:54 +0000684CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
685 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000686 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
687 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
688 ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000689
690 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
691
David Chisnall9f6614e2011-03-23 16:36:54 +0000692 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000693 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000694 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000695 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000696 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000697 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000698 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000699 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000700 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000701 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000703 Int8Ty = llvm::Type::getInt8Ty(VMContext);
704 // C string type. Used in lots of places.
705 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
706
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000707 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000708 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000709 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000710 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000711 QualType selTy = CGM.getContext().getObjCSelType();
712 if (QualType() == selTy) {
713 SelectorTy = PtrToInt8Ty;
714 } else {
715 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
716 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000717
Owen Anderson96e0fc72009-07-29 22:16:19 +0000718 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000719 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000720
David Chisnall917b28b2011-10-04 15:35:30 +0000721 Int32Ty = llvm::Type::getInt32Ty(VMContext);
722 Int64Ty = llvm::Type::getInt64Ty(VMContext);
723
David Chisnall49de5282011-10-08 08:54:36 +0000724 IntPtrTy =
725 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
726
Chris Lattner391d77a2008-03-30 23:03:07 +0000727 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000728 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
729 ASTIdTy = CanQualType();
730 if (UnqualIdTy != QualType()) {
731 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000732 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000733 } else {
734 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000735 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000736 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner7650d952011-06-18 22:49:11 +0000738 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000739 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
740
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000741 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000742
743 // void objc_exception_throw(id);
744 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000745 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000746 // int objc_sync_enter(id);
747 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
748 // int objc_sync_exit(id);
749 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
750
751 // void objc_enumerationMutation (id)
752 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
753 IdTy, NULL);
754
755 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
756 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
757 PtrDiffTy, BoolTy, NULL);
758 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
759 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
760 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
761 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
762 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
763 PtrDiffTy, BoolTy, BoolTy, NULL);
764 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
765 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
766 PtrDiffTy, BoolTy, BoolTy, NULL);
767
Chris Lattner391d77a2008-03-30 23:03:07 +0000768 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000769 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000770 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
771 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000772
David Chisnallf0748852011-07-07 11:22:31 +0000773 const LangOptions &Opts = CGM.getLangOptions();
Douglas Gregore289d812011-09-13 17:21:33 +0000774 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +0000775 RuntimeVersion = 10;
776
David Chisnall9735ca62011-03-25 11:57:33 +0000777 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +0000778 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000779 // This is a bit of an hack. We should sort this out by having a proper
780 // CGObjCGNUstep subclass for GC, but we may want to really support the old
781 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000782 // Get selectors needed in GC mode
783 RetainSel = GetNullarySelector("retain", CGM.getContext());
784 ReleaseSel = GetNullarySelector("release", CGM.getContext());
785 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
786
787 // Get functions needed in GC mode
788
789 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000790 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
791 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000792 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000793 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
794 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000795 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000796 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
797 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000798 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000799 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000800 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000801 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000802 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000803 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
804 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000805 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000806}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000807
David Chisnallc7aed3b2011-06-29 13:16:41 +0000808llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +0000809 const std::string &Name,
810 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +0000811 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +0000812 // With the incompatible ABI, this will need to be replaced with a direct
813 // reference to the class symbol. For the compatible nonfragile ABI we are
814 // still performing this lookup at run time but emitting the symbol for the
815 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +0000816 //
817 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
818 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +0000819 if (!isWeak)
820 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000821 ClassName = Builder.CreateStructGEP(ClassName, 0);
822
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000823 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +0000824 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000825 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000826 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000827}
828
David Chisnallc7aed3b2011-06-29 13:16:41 +0000829// This has to perform the lookup every time, since posing and related
830// techniques can modify the name -> class mapping.
831llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
832 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000833 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +0000834}
835llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000836 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000837}
838
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000839llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000840 const std::string &TypeEncoding, bool lval) {
841
Chris Lattner5f9e2722011-07-23 10:55:15 +0000842 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +0000843 llvm::GlobalAlias *SelValue = 0;
844
845
Chris Lattner5f9e2722011-07-23 10:55:15 +0000846 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +0000847 e = Types.end() ; i!=e ; i++) {
848 if (i->first == TypeEncoding) {
849 SelValue = i->second;
850 break;
851 }
852 }
853 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000854 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000855 llvm::GlobalValue::PrivateLinkage,
856 ".objc_selector_"+Sel.getAsString(), NULL,
857 &TheModule);
858 Types.push_back(TypedSelector(TypeEncoding, SelValue));
859 }
860
David Chisnallc7ef4622011-03-23 22:52:06 +0000861 if (lval) {
862 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
863 Builder.CreateStore(SelValue, tmp);
864 return tmp;
865 }
866 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000867}
868
869llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
870 bool lval) {
871 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000872}
873
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000874llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000875 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000876 std::string SelTypes;
877 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000878 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000879}
880
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000881llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000882 if (!CGM.getLangOptions().CPlusPlus) {
883 if (T->isObjCIdType()
884 || T->isObjCQualifiedIdType()) {
885 // With the old ABI, there was only one kind of catchall, which broke
886 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
887 // a pointer indicating object catchalls, and NULL to indicate real
888 // catchalls
889 if (CGM.getLangOptions().ObjCNonFragileABI) {
890 return MakeConstantString("@id");
891 } else {
892 return 0;
893 }
894 }
895
896 // All other types should be Objective-C interface pointer types.
897 const ObjCObjectPointerType *OPT =
898 T->getAs<ObjCObjectPointerType>();
899 assert(OPT && "Invalid @catch type.");
900 const ObjCInterfaceDecl *IDecl =
901 OPT->getObjectType()->getInterface();
902 assert(IDecl && "Invalid @catch type.");
903 return MakeConstantString(IDecl->getIdentifier()->getName());
904 }
David Chisnall80558d22011-03-20 21:35:39 +0000905 // For Objective-C++, we want to provide the ability to catch both C++ and
906 // Objective-C objects in the same function.
907
908 // There's a particular fixed type info for 'id'.
909 if (T->isObjCIdType() ||
910 T->isObjCQualifiedIdType()) {
911 llvm::Constant *IDEHType =
912 CGM.getModule().getGlobalVariable("__objc_id_type_info");
913 if (!IDEHType)
914 IDEHType =
915 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
916 false,
917 llvm::GlobalValue::ExternalLinkage,
918 0, "__objc_id_type_info");
919 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
920 }
921
922 const ObjCObjectPointerType *PT =
923 T->getAs<ObjCObjectPointerType>();
924 assert(PT && "Invalid @catch type.");
925 const ObjCInterfaceType *IT = PT->getInterfaceType();
926 assert(IT && "Invalid @catch type.");
927 std::string className = IT->getDecl()->getIdentifier()->getName();
928
929 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
930
931 // Return the existing typeinfo if it exists
932 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
933 if (typeinfo) return typeinfo;
934
935 // Otherwise create it.
936
937 // vtable for gnustep::libobjc::__objc_class_type_info
938 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
939 // platform's name mangling.
940 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
941 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
942 if (!Vtable) {
943 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
944 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
945 }
946 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +0000947 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +0000948 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
949
950 llvm::Constant *typeName =
951 ExportUniqueString(className, "__objc_eh_typename_");
952
953 std::vector<llvm::Constant*> fields;
954 fields.push_back(Vtable);
955 fields.push_back(typeName);
956 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +0000957 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +0000958 NULL), fields, "__objc_eh_typeinfo_" + className,
959 llvm::GlobalValue::LinkOnceODRLinkage);
960 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000961}
962
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000963/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000964llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000965
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000966 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000967
David Chisnall48272a02010-01-27 12:49:23 +0000968 // Look for an existing one
969 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
970 if (old != ObjCStrings.end())
971 return old->getValue();
972
David Chisnall13df6f62012-01-04 12:02:13 +0000973 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
974
975 if (StringClass.empty()) StringClass = "NXConstantString";
976
977 std::string Sym = "_OBJC_CLASS_";
978 Sym += StringClass;
979
980 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
981
982 if (!isa)
983 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
984 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
985 else if (isa->getType() != PtrToIdTy)
986 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
987
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000988 std::vector<llvm::Constant*> Ivars;
David Chisnall13df6f62012-01-04 12:02:13 +0000989 Ivars.push_back(isa);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000990 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000991 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000992 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall13df6f62012-01-04 12:02:13 +0000993 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000994 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000995 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
996 ObjCStrings[Str] = ObjCStr;
997 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000998 return ObjCStr;
999}
1000
1001///Generates a message send where the super is the receiver. This is a message
1002///send to self with special delivery semantics indicating which class's method
1003///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +00001004RValue
1005CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001006 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001007 QualType ResultType,
1008 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001009 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001010 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001011 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001012 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001013 const CallArgList &CallArgs,
1014 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001015 CGBuilderTy &Builder = CGF.Builder;
Douglas Gregore289d812011-09-13 17:21:33 +00001016 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001017 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001018 return RValue::get(EnforceType(Builder, Receiver,
1019 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001020 }
1021 if (Sel == ReleaseSel) {
1022 return RValue::get(0);
1023 }
1024 }
David Chisnalldb831942010-05-01 12:37:16 +00001025
David Chisnalldb831942010-05-01 12:37:16 +00001026 llvm::Value *cmd = GetSelector(Builder, Sel);
1027
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001028
1029 CallArgList ActualArgs;
1030
Eli Friedman04c9a492011-05-02 17:57:46 +00001031 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1032 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001033 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001034
1035 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001036 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001037 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001038
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001039 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001040 if (isCategoryImpl) {
1041 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001042 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001043 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001044 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001045 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001046 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001047 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001048 }
David Chisnalldb831942010-05-01 12:37:16 +00001049 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001050 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001051 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001052 // Set up global aliases for the metaclass or class pointer if they do not
1053 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001054 // pointers to the class and metaclass structure created for the runtime
1055 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001056 // super_class pointer from either the class or metaclass structure.
1057 if (IsClassMessage) {
1058 if (!MetaClassPtrAlias) {
1059 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1060 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1061 Class->getNameAsString(), NULL, &TheModule);
1062 }
1063 ReceiverClass = MetaClassPtrAlias;
1064 } else {
1065 if (!ClassPtrAlias) {
1066 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1067 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1068 Class->getNameAsString(), NULL, &TheModule);
1069 }
1070 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001071 }
Chris Lattner71238f62009-04-25 23:19:45 +00001072 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001073 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001074 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001075 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001076 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001077 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001078 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001079 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001080 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001081 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001082 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001083 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001084 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001085
David Chisnalldb831942010-05-01 12:37:16 +00001086 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1087 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001088
David Chisnallc7ef4622011-03-23 22:52:06 +00001089 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001090 llvm::FunctionType *impType =
David Chisnallc7ef4622011-03-23 22:52:06 +00001091 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1092
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001093 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001094 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1095 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001096
David Chisnalldd5c98f2010-05-01 11:15:56 +00001097 llvm::Value *impMD[] = {
1098 llvm::MDString::get(VMContext, Sel.getAsString()),
1099 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1100 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1101 };
Jay Foad6f141652011-04-21 19:59:12 +00001102 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001103
David Chisnall4b02afc2010-05-02 13:41:58 +00001104 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001105 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001106 0, &call);
1107 call->setMetadata(msgSendMDKind, node);
1108 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001109}
1110
Mike Stump1eb44332009-09-09 15:08:12 +00001111/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001112RValue
1113CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001114 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001115 QualType ResultType,
1116 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001117 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001118 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001119 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001120 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001121 CGBuilderTy &Builder = CGF.Builder;
1122
David Chisnall664b7c72010-04-27 15:08:48 +00001123 // Strip out message sends to retain / release in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +00001124 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001125 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001126 return RValue::get(EnforceType(Builder, Receiver,
1127 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001128 }
1129 if (Sel == ReleaseSel) {
1130 return RValue::get(0);
1131 }
1132 }
David Chisnall664b7c72010-04-27 15:08:48 +00001133
David Chisnall664b7c72010-04-27 15:08:48 +00001134 // If the return type is something that goes in an integer register, the
1135 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1136 // ourselves.
1137 //
1138 // The language spec says the result of this kind of message send is
1139 // undefined, but lots of people seem to have forgotten to read that
1140 // paragraph and insist on sending messages to nil that have structure
1141 // returns. With GCC, this generates a random return value (whatever happens
1142 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001143 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1144 // the stack.
1145 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1146 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001147
1148 llvm::BasicBlock *startBB = 0;
1149 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001150 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001151
1152 if (!isPointerSizedReturn) {
1153 startBB = Builder.GetInsertBlock();
1154 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001155 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001156
1157 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1158 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001159 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001160 CGF.EmitBlock(messageBB);
1161 }
1162
David Chisnall0f436562009-08-17 16:35:33 +00001163 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001164 llvm::Value *cmd;
1165 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001166 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001167 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001168 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001169 cmd = EnforceType(Builder, cmd, SelectorTy);
1170 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001171
David Chisnallc7ef4622011-03-23 22:52:06 +00001172 llvm::Value *impMD[] = {
1173 llvm::MDString::get(VMContext, Sel.getAsString()),
1174 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1175 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1176 };
Jay Foad6f141652011-04-21 19:59:12 +00001177 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001178
David Chisnall89c30042011-10-24 14:07:03 +00001179 CodeGenTypes &Types = CGM.getTypes();
David Chisnallc7ef4622011-03-23 22:52:06 +00001180 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001181 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1182 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001183 ActualArgs.addFrom(CallArgs);
John McCall04a67a62010-02-05 21:31:56 +00001184 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001185 FunctionType::ExtInfo());
David Chisnall89c30042011-10-24 14:07:03 +00001186 // Get the IMP to call
1187 llvm::Value *imp;
1188
1189 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1190 // functions. These are not supported on all platforms (or all runtimes on a
1191 // given platform), so we
1192 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1193 default:
1194 llvm_unreachable("Invalid dispatch method!");
1195 case CodeGenOptions::Legacy:
David Chisnall89c30042011-10-24 14:07:03 +00001196 imp = LookupIMP(CGF, Receiver, cmd, node);
1197 break;
1198 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001199 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001200 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1201 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1202 "objc_msgSend_fpret");
David Chisnall89c30042011-10-24 14:07:03 +00001203 } else if (CGM.ReturnTypeUsesSRet(FnInfo)) {
1204 // The actual types here don't matter - we're going to bitcast the
1205 // function anyway
1206 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1207 "objc_msgSend_stret");
1208 } else {
1209 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1210 "objc_msgSend");
1211 }
1212 }
1213
David Chisnall403bc3f2011-12-01 18:40:09 +00001214 // Reset the receiver in case the lookup modified it
1215 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001216
Chris Lattner2acc6e32011-07-18 04:24:23 +00001217 llvm::FunctionType *impType =
Daniel Dunbar67939662009-09-17 04:01:40 +00001218 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001219 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001220
David Chisnall4b02afc2010-05-02 13:41:58 +00001221 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001222 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001223 0, &call);
1224 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001225
David Chisnalla54da052010-05-20 13:45:48 +00001226
David Chisnall664b7c72010-04-27 15:08:48 +00001227 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001228 messageBB = CGF.Builder.GetInsertBlock();
1229 CGF.Builder.CreateBr(continueBB);
1230 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001231 if (msgRet.isScalar()) {
1232 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001233 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001234 phi->addIncoming(v, messageBB);
1235 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1236 msgRet = RValue::get(phi);
1237 } else if (msgRet.isAggregate()) {
1238 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001239 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001240 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001241 llvm::AllocaInst *NullVal =
1242 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001243 CGF.InitTempAlloca(NullVal,
1244 llvm::Constant::getNullValue(RetTy->getElementType()));
1245 phi->addIncoming(v, messageBB);
1246 phi->addIncoming(NullVal, startBB);
1247 msgRet = RValue::getAggregate(phi);
1248 } else /* isComplex() */ {
1249 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001250 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001251 phi->addIncoming(v.first, messageBB);
1252 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1253 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001254 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001255 phi2->addIncoming(v.second, messageBB);
1256 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1257 startBB);
1258 msgRet = RValue::getComplex(phi, phi2);
1259 }
1260 }
1261 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001262}
1263
Mike Stump1eb44332009-09-09 15:08:12 +00001264/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001265/// objc_category structures.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001266llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1267 const StringRef &CategoryName,
1268 const SmallVectorImpl<Selector> &MethodSels,
1269 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001270 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001271 if (MethodSels.empty())
1272 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001273 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001274 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001275 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1276 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001277 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001278 NULL);
1279 std::vector<llvm::Constant*> Methods;
1280 std::vector<llvm::Constant*> Elements;
1281 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1282 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001283 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001284 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001285 MethodSels[i],
1286 isClassMethodList));
1287 assert(Method && "Can't generate metadata for method that doesn't exist");
1288 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1289 Elements.push_back(C);
1290 Elements.push_back(MethodTypes[i]);
1291 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001292 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001293 Elements.push_back(Method);
1294 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001295 }
1296
1297 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001298 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001299 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001300 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001301 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001302
1303 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001304 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001305 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1306 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001307 NextPtrTy,
1308 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001309 ObjCMethodArrayTy,
1310 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001311
1312 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001313 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001314 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001315 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001316 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001318 // Create an instance of the structure
1319 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1320}
1321
1322/// Generates an IvarList. Used in construction of a objc_class.
1323llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001324 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1325 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1326 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001327 if (IvarNames.size() == 0)
1328 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001329 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001330 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001331 PtrToInt8Ty,
1332 PtrToInt8Ty,
1333 IntTy,
1334 NULL);
1335 std::vector<llvm::Constant*> Ivars;
1336 std::vector<llvm::Constant*> Elements;
1337 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1338 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001339 Elements.push_back(IvarNames[i]);
1340 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001341 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001342 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001343 }
1344
1345 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001346 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001347 IvarNames.size());
1348
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001350 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001351 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001352 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001353 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001354 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001355 ObjCIvarArrayTy,
1356 NULL);
1357
1358 // Create an instance of the structure
1359 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1360}
1361
1362/// Generate a class structure
1363llvm::Constant *CGObjCGNU::GenerateClassStructure(
1364 llvm::Constant *MetaClass,
1365 llvm::Constant *SuperClass,
1366 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001367 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001368 llvm::Constant *Version,
1369 llvm::Constant *InstanceSize,
1370 llvm::Constant *IVars,
1371 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001372 llvm::Constant *Protocols,
1373 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001374 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001375 llvm::Constant *StrongIvarBitmap,
1376 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001377 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001378 // Set up the class structure
1379 // Note: Several of these are char*s when they should be ids. This is
1380 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001381 //
1382 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1383 // anyway; the classes will still work with the GNU runtime, they will just
1384 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001385 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001386 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001387 PtrToInt8Ty, // super_class
1388 PtrToInt8Ty, // name
1389 LongTy, // version
1390 LongTy, // info
1391 LongTy, // instance_size
1392 IVars->getType(), // ivars
1393 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001394 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001395 PtrTy, // dtable
1396 PtrTy, // subclass_list
1397 PtrTy, // sibling_class
1398 PtrTy, // protocols
1399 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001400 // New ABI:
1401 LongTy, // abi_version
1402 IvarOffsets->getType(), // ivar_offsets
1403 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001404 IntPtrTy, // strong_pointers
1405 IntPtrTy, // weak_pointers
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001406 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001407 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001408 // Fill in the structure
1409 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001410 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001411 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001412 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001413 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001414 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001415 if (isMeta) {
1416 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001417 Elements.push_back(
1418 llvm::ConstantInt::get(LongTy,
1419 td.getTypeSizeInBits(ClassTy) /
1420 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001421 } else
1422 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001423 Elements.push_back(IVars);
1424 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001425 Elements.push_back(NULLPtr);
1426 Elements.push_back(NULLPtr);
1427 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001428 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001429 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001430 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001431 Elements.push_back(IvarOffsets);
1432 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001433 Elements.push_back(StrongIvarBitmap);
1434 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001435 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001436 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001437 // messages in the next ABI. We may already have some weak references to
1438 // this, so check and fix them properly.
1439 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1440 std::string(Name));
1441 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1442 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1443 llvm::GlobalValue::ExternalLinkage);
1444 if (ClassRef) {
1445 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1446 ClassRef->getType()));
1447 ClassRef->removeFromParent();
1448 Class->setName(ClassSym);
1449 }
1450 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001451}
1452
1453llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001454 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1455 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001456 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001457 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001458 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1459 PtrToInt8Ty,
1460 NULL);
1461 std::vector<llvm::Constant*> Methods;
1462 std::vector<llvm::Constant*> Elements;
1463 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1464 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001465 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001466 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001467 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001468 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001469 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001470 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001471 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001472 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001473 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001474 IntTy, ObjCMethodArrayTy, NULL);
1475 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001476 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001477 Methods.push_back(Array);
1478 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1479}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001480
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001481// Create the protocol list structure used in classes, categories and so on
1482llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001483 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001484 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001485 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001486 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001487 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001488 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001489 ProtocolArrayTy,
1490 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001491 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001492 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1493 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001494 llvm::Constant *protocol = 0;
1495 llvm::StringMap<llvm::Constant*>::iterator value =
1496 ExistingProtocols.find(*iter);
1497 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001498 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001499 } else {
1500 protocol = value->getValue();
1501 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001502 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001503 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001504 Elements.push_back(Ptr);
1505 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001506 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001507 Elements);
1508 Elements.clear();
1509 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001510 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001511 Elements.push_back(ProtocolArray);
1512 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1513}
1514
Mike Stump1eb44332009-09-09 15:08:12 +00001515llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001516 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001517 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001518 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001519 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001520 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001521}
1522
1523llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1524 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001525 SmallVector<std::string, 0> EmptyStringVector;
1526 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001527
1528 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001529 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001530 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1531 // Protocols are objects containing lists of the methods implemented and
1532 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001533 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001534 PtrToInt8Ty,
1535 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001536 MethodList->getType(),
1537 MethodList->getType(),
1538 MethodList->getType(),
1539 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001540 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001541 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001542 // The isa pointer must be set to a magic number so the runtime knows it's
1543 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001544 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001545 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001546 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1547 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001548 Elements.push_back(MethodList);
1549 Elements.push_back(MethodList);
1550 Elements.push_back(MethodList);
1551 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001552 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001553}
1554
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001555void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1556 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001557 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001558
1559 // Use the protocol definition, if there is one.
1560 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1561 PD = Def;
1562
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001564 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1565 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001566 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001567 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1568 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1569 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1570 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001571 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1572 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001573 std::string TypeStr;
1574 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001575 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1576 InstanceMethodNames.push_back(
1577 MakeConstantString((*iter)->getSelector().getAsString()));
1578 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1579 } else {
1580 OptionalInstanceMethodNames.push_back(
1581 MakeConstantString((*iter)->getSelector().getAsString()));
1582 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1583 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001584 }
1585 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001586 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1587 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1588 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1589 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001590 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001591 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1592 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001593 std::string TypeStr;
1594 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001595 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1596 ClassMethodNames.push_back(
1597 MakeConstantString((*iter)->getSelector().getAsString()));
1598 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1599 } else {
1600 OptionalClassMethodNames.push_back(
1601 MakeConstantString((*iter)->getSelector().getAsString()));
1602 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1603 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001604 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001605
1606 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1607 llvm::Constant *InstanceMethodList =
1608 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1609 llvm::Constant *ClassMethodList =
1610 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001611 llvm::Constant *OptionalInstanceMethodList =
1612 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1613 OptionalInstanceMethodTypes);
1614 llvm::Constant *OptionalClassMethodList =
1615 GenerateProtocolMethodList(OptionalClassMethodNames,
1616 OptionalClassMethodTypes);
1617
1618 // Property metadata: name, attributes, isSynthesized, setter name, setter
1619 // types, getter name, getter types.
1620 // The isSynthesized value is always set to 0 in a protocol. It exists to
1621 // simplify the runtime library by allowing it to use the same data
1622 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001623 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001624 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1625 PtrToInt8Ty, NULL);
1626 std::vector<llvm::Constant*> Properties;
1627 std::vector<llvm::Constant*> OptionalProperties;
1628
1629 // Add all of the property methods need adding to the method list and to the
1630 // property metadata list.
1631 for (ObjCContainerDecl::prop_iterator
1632 iter = PD->prop_begin(), endIter = PD->prop_end();
1633 iter != endIter ; iter++) {
1634 std::vector<llvm::Constant*> Fields;
1635 ObjCPropertyDecl *property = (*iter);
1636
1637 Fields.push_back(MakeConstantString(property->getNameAsString()));
1638 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1639 property->getPropertyAttributes()));
1640 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1641 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1642 std::string TypeStr;
1643 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1644 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1645 InstanceMethodTypes.push_back(TypeEncoding);
1646 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1647 Fields.push_back(TypeEncoding);
1648 } else {
1649 Fields.push_back(NULLPtr);
1650 Fields.push_back(NULLPtr);
1651 }
1652 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1653 std::string TypeStr;
1654 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1655 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1656 InstanceMethodTypes.push_back(TypeEncoding);
1657 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1658 Fields.push_back(TypeEncoding);
1659 } else {
1660 Fields.push_back(NULLPtr);
1661 Fields.push_back(NULLPtr);
1662 }
1663 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1664 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1665 } else {
1666 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1667 }
1668 }
1669 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1670 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1671 llvm::Constant* PropertyListInitFields[] =
1672 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1673
1674 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001675 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001676 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1677 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1678 PropertyListInit, ".objc_property_list");
1679
1680 llvm::Constant *OptionalPropertyArray =
1681 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1682 OptionalProperties.size()) , OptionalProperties);
1683 llvm::Constant* OptionalPropertyListInitFields[] = {
1684 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1685 OptionalPropertyArray };
1686
1687 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001688 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001689 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1690 OptionalPropertyListInit->getType(), false,
1691 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1692 ".objc_property_list");
1693
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001694 // Protocols are objects containing lists of the methods implemented and
1695 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001696 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001697 PtrToInt8Ty,
1698 ProtocolList->getType(),
1699 InstanceMethodList->getType(),
1700 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001701 OptionalInstanceMethodList->getType(),
1702 OptionalClassMethodList->getType(),
1703 PropertyList->getType(),
1704 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001705 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001706 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001707 // The isa pointer must be set to a magic number so the runtime knows it's
1708 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001709 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001710 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001711 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1712 Elements.push_back(ProtocolList);
1713 Elements.push_back(InstanceMethodList);
1714 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001715 Elements.push_back(OptionalInstanceMethodList);
1716 Elements.push_back(OptionalClassMethodList);
1717 Elements.push_back(PropertyList);
1718 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001719 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001720 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001721 ".objc_protocol"), IdTy);
1722}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001723void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1724 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001725 SmallVector<Selector, 1> MethodSels;
1726 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001727
1728 std::vector<llvm::Constant*> Elements;
1729 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1730 const std::string CategoryName = "AnotherHack";
1731 Elements.push_back(MakeConstantString(CategoryName));
1732 Elements.push_back(MakeConstantString(ClassName));
1733 // Instance method list
1734 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1735 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1736 // Class method list
1737 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1738 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1739 // Protocol list
1740 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1741 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001742 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001743 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001744 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001745 ProtocolArrayTy,
1746 NULL);
1747 std::vector<llvm::Constant*> ProtocolElements;
1748 for (llvm::StringMapIterator<llvm::Constant*> iter =
1749 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1750 iter != endIter ; iter++) {
1751 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1752 PtrTy);
1753 ProtocolElements.push_back(Ptr);
1754 }
1755 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1756 ProtocolElements);
1757 ProtocolElements.clear();
1758 ProtocolElements.push_back(NULLPtr);
1759 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1760 ExistingProtocols.size()));
1761 ProtocolElements.push_back(ProtocolArray);
1762 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1763 ProtocolElements, ".objc_protocol_list"), PtrTy));
1764 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001765 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001766 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1767}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001768
David Chisnall917b28b2011-10-04 15:35:30 +00001769/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1770/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1771/// bits set to their values, LSB first, while larger ones are stored in a
1772/// structure of this / form:
1773///
1774/// struct { int32_t length; int32_t values[length]; };
1775///
1776/// The values in the array are stored in host-endian format, with the least
1777/// significant bit being assumed to come first in the bitfield. Therefore, a
1778/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1779/// bitfield / with the 63rd bit set will be 1<<64.
1780llvm::Constant *CGObjCGNU::MakeBitField(llvm::SmallVectorImpl<bool> &bits) {
1781 int bitCount = bits.size();
David Chisnall9d06ba82011-10-25 10:12:21 +00001782 int ptrBits =
1783 (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
1784 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001785 uint64_t val = 1;
1786 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001787 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001788 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001789 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001790 }
1791 llvm::SmallVector<llvm::Constant*, 8> values;
1792 int v=0;
1793 while (v < bitCount) {
1794 int32_t word = 0;
1795 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1796 if (bits[v]) word |= 1<<i;
1797 v++;
1798 }
1799 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1800 }
1801 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1802 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1803 llvm::Constant *fields[2] = {
1804 llvm::ConstantInt::get(Int32Ty, values.size()),
1805 array };
1806 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1807 NULL), fields);
David Chisnall49de5282011-10-08 08:54:36 +00001808 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00001809 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00001810}
1811
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001812void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001813 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1814 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001815 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001816 SmallVector<Selector, 16> InstanceMethodSels;
1817 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001818 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001819 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001820 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001821 InstanceMethodSels.push_back((*iter)->getSelector());
1822 std::string TypeStr;
1823 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001824 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001825 }
1826
1827 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001828 SmallVector<Selector, 16> ClassMethodSels;
1829 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001830 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001831 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001832 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001833 ClassMethodSels.push_back((*iter)->getSelector());
1834 std::string TypeStr;
1835 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001836 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001837 }
1838
1839 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001840 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001841 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1842 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001843 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1844 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001845 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001846
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001847 std::vector<llvm::Constant*> Elements;
1848 Elements.push_back(MakeConstantString(CategoryName));
1849 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001850 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001851 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001852 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001853 false), PtrTy));
1854 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001855 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001856 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001857 PtrTy));
1858 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001859 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001860 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001861 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001862 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001863 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001864}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001865
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001866llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001867 SmallVectorImpl<Selector> &InstanceMethodSels,
1868 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001869 ASTContext &Context = CGM.getContext();
1870 //
1871 // Property metadata: name, attributes, isSynthesized, setter name, setter
1872 // types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00001873 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001874 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1875 PtrToInt8Ty, NULL);
1876 std::vector<llvm::Constant*> Properties;
1877
1878
1879 // Add all of the property methods need adding to the method list and to the
1880 // property metadata list.
1881 for (ObjCImplDecl::propimpl_iterator
1882 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1883 iter != endIter ; iter++) {
1884 std::vector<llvm::Constant*> Fields;
1885 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001886 ObjCPropertyImplDecl *propertyImpl = *iter;
1887 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1888 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001889
1890 Fields.push_back(MakeConstantString(property->getNameAsString()));
1891 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1892 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001893 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001894 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001895 std::string TypeStr;
1896 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1897 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001898 if (isSynthesized) {
1899 InstanceMethodTypes.push_back(TypeEncoding);
1900 InstanceMethodSels.push_back(getter->getSelector());
1901 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001902 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1903 Fields.push_back(TypeEncoding);
1904 } else {
1905 Fields.push_back(NULLPtr);
1906 Fields.push_back(NULLPtr);
1907 }
1908 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001909 std::string TypeStr;
1910 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1911 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001912 if (isSynthesized) {
1913 InstanceMethodTypes.push_back(TypeEncoding);
1914 InstanceMethodSels.push_back(setter->getSelector());
1915 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001916 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1917 Fields.push_back(TypeEncoding);
1918 } else {
1919 Fields.push_back(NULLPtr);
1920 Fields.push_back(NULLPtr);
1921 }
1922 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1923 }
1924 llvm::ArrayType *PropertyArrayTy =
1925 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1926 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1927 Properties);
1928 llvm::Constant* PropertyListInitFields[] =
1929 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1930
1931 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001932 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001933 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1934 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1935 ".objc_property_list");
1936}
1937
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001938void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1939 ASTContext &Context = CGM.getContext();
1940
1941 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001942 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001943 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001944 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001945 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001946 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001947 EmitClassRef(SuperClassName);
1948 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001949
1950 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001951 ObjCInterfaceDecl *ClassDecl =
1952 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001953 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001954 // Emit the symbol that is used to generate linker errors if this class is
1955 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001956 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001957 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001958 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001959 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001960 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001961 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001962 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001963 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001964 }
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001966 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001967 int instanceSize =
1968 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001969
1970 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001971 SmallVector<llvm::Constant*, 16> IvarNames;
1972 SmallVector<llvm::Constant*, 16> IvarTypes;
1973 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001975 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00001976 SmallVector<bool, 16> WeakIvars;
1977 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001978
Mike Stump1eb44332009-09-09 15:08:12 +00001979 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001980 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001981 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1982 // class}. The runtime will then set this to the correct value on load.
1983 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1984 instanceSize = 0 - (instanceSize - superInstanceSize);
1985 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001986
Jordy Rosedb8264e2011-07-22 02:08:32 +00001987 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1988 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001989 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001990 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001991 // Get the type encoding for this ivar
1992 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001993 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001994 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001995 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001996 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001997 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001998 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001999 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002000 }
David Chisnall63ff7032011-07-07 12:34:51 +00002001 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2002 // Create the direct offset value
2003 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2004 IVD->getNameAsString();
2005 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2006 if (OffsetVar) {
2007 OffsetVar->setInitializer(OffsetValue);
2008 // If this is the real definition, change its linkage type so that
2009 // different modules will use this one, rather than their private
2010 // copy.
2011 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2012 } else
2013 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002014 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002015 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002016 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002017 IVD->getNameAsString());
2018 IvarOffsets.push_back(OffsetValue);
2019 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002020 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2021 switch (lt) {
2022 case Qualifiers::OCL_Strong:
2023 StrongIvars.push_back(true);
2024 WeakIvars.push_back(false);
2025 break;
2026 case Qualifiers::OCL_Weak:
2027 StrongIvars.push_back(false);
2028 WeakIvars.push_back(true);
2029 break;
2030 default:
2031 StrongIvars.push_back(false);
2032 WeakIvars.push_back(false);
2033 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002034 }
David Chisnall917b28b2011-10-04 15:35:30 +00002035 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2036 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002037 llvm::GlobalVariable *IvarOffsetArray =
2038 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2039
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002040
2041 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002042 SmallVector<Selector, 16> InstanceMethodSels;
2043 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002044 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002045 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002046 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002047 InstanceMethodSels.push_back((*iter)->getSelector());
2048 std::string TypeStr;
2049 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002050 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002051 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002052
2053 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2054 InstanceMethodTypes);
2055
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002056
2057 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002058 SmallVector<Selector, 16> ClassMethodSels;
2059 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002060 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002061 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002062 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002063 ClassMethodSels.push_back((*iter)->getSelector());
2064 std::string TypeStr;
2065 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002066 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002067 }
2068 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002069 SmallVector<std::string, 16> Protocols;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002070 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
2071 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2072 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002073 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002074
2075
2076
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002077 // Get the superclass pointer.
2078 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002079 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002080 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2081 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002082 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002083 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002084 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002085 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002086 // Generate the method and instance variable lists
2087 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002088 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002089 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002090 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002091 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2092 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002093 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002094 // we emit a symbol containing the offset for each ivar in the class. This
2095 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2096 // for the legacy ABI, without causing problems. The converse is also
2097 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002098
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002099 // Offset pointer for getting at the correct field in the ivar list when
2100 // setting up the alias. These are: The base address for the global, the
2101 // ivar array (second field), the ivar in this list (set for each ivar), and
2102 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002103 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002104 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002105 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002106 llvm::ConstantInt::get(IndexTy, 2) };
2107
Jordy Rosedb8264e2011-07-22 02:08:32 +00002108 unsigned ivarIndex = 0;
2109 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2110 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002111 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002112 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002113 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002114 // Get the correct ivar field
2115 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002116 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002117 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002118 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2119 if (offset) {
2120 offset->setInitializer(offsetValue);
2121 // If this is the real definition, change its linkage type so that
2122 // different modules will use this one, rather than their private
2123 // copy.
2124 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2125 } else {
2126 // Add a new alias if there isn't one already.
2127 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2128 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2129 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002130 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002131 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002132 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002133 //Generate metaclass for class methods
2134 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00002135 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002136 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002137 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002138
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002139 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002140 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002141 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00002142 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002143 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002144 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002145 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002146
2147 // Resolve the class aliases, if they exist.
2148 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002149 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002150 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002151 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002152 ClassPtrAlias = 0;
2153 }
2154 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002155 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002156 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002157 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002158 MetaClassPtrAlias = 0;
2159 }
2160
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002161 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002162 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002163 Classes.push_back(ClassStruct);
2164}
2165
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002166
Mike Stump1eb44332009-09-09 15:08:12 +00002167llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002168 // Only emit an ObjC load function if no Objective-C stuff has been called
2169 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002170 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002171 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002172
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002173 // Add all referenced protocols to a category.
2174 GenerateProtocolHolderCategory();
2175
Chris Lattner2acc6e32011-07-18 04:24:23 +00002176 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002177 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002178 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002179 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002180 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002181 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002182 }
2183
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002184 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002185 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002186 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002187 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002188 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002189 ConstantStrings.size() + 1);
2190 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002191
Chris Lattner5f9e2722011-07-23 10:55:15 +00002192 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002193
Daniel Dunbar1b096952009-11-29 02:38:47 +00002194 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002195
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002196 Elements.push_back(MakeConstantString(StringClass,
2197 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002198 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002199 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002200 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002201 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002202 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002203 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002204 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002205 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002206 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002207 Elements.clear();
2208 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002209 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002210 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002211 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002212 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002213 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002214 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002215 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002216 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002217 llvm::Type::getInt16Ty(VMContext),
2218 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002219 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002220
2221 Elements.clear();
2222 // Pointer to an array of selectors used in this module.
2223 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002224 std::vector<llvm::GlobalAlias*> SelectorAliases;
2225 for (SelectorMap::iterator iter = SelectorTable.begin(),
2226 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2227
2228 std::string SelNameStr = iter->first.getAsString();
2229 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2230
Chris Lattner5f9e2722011-07-23 10:55:15 +00002231 SmallVectorImpl<TypedSelector> &Types = iter->second;
2232 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002233 e = Types.end() ; i!=e ; i++) {
2234
2235 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2236 if (!i->first.empty())
2237 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2238
2239 Elements.push_back(SelName);
2240 Elements.push_back(SelectorTypeEncoding);
2241 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2242 Elements.clear();
2243
2244 // Store the selector alias for later replacement
2245 SelectorAliases.push_back(i->second);
2246 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002247 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002248 unsigned SelectorCount = Selectors.size();
2249 // NULL-terminate the selector list. This should not actually be required,
2250 // because the selector list has a length field. Unfortunately, the GCC
2251 // runtime decides to ignore the length field and expects a NULL terminator,
2252 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002253 Elements.push_back(NULLPtr);
2254 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002255 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002256 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002257
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002258 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002259 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2260 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002261 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002262 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002263 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002264
2265 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002266 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2267
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002268 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002269 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002270 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002271 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002272 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002273 // If selectors are defined as an opaque type, cast the pointer to this
2274 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002275 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002276 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2277 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002278 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002279
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002280 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002281 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002282 Classes.size()));
2283 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002284 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002285 Categories.size()));
2286 // Create an array of classes, then categories, then static object instances
2287 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2288 // NULL-terminated list of static object instances (mainly constant strings)
2289 Classes.push_back(Statics);
2290 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002291 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002292 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002293 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002294 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2295
2296 // The symbol table is contained in a module which has some version-checking
2297 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002298 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002299 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002300 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002301 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002302 // Runtime version, used for ABI compatibility checking.
2303 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002304 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002305 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002306 Elements.push_back(
2307 llvm::ConstantInt::get(LongTy,
2308 td.getTypeSizeInBits(ModuleTy) /
2309 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002310
2311 // The path to the source file where this module was declared
2312 SourceManager &SM = CGM.getContext().getSourceManager();
2313 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2314 std::string path =
2315 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2316 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002317 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002318
David Chisnallf0748852011-07-07 11:22:31 +00002319 if (RuntimeVersion >= 10)
Douglas Gregore289d812011-09-13 17:21:33 +00002320 switch (CGM.getLangOptions().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002321 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002322 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002323 break;
David Chisnallf0748852011-07-07 11:22:31 +00002324 case LangOptions::NonGC:
2325 if (CGM.getLangOptions().ObjCAutoRefCount)
2326 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2327 else
2328 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2329 break;
2330 case LangOptions::HybridGC:
2331 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2332 break;
2333 }
David Chisnalla2120032011-05-22 22:37:08 +00002334
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002335 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2336
2337 // Create the load function calling the runtime entry point with the module
2338 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002339 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002340 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002341 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2342 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002343 llvm::BasicBlock *EntryBB =
2344 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002345 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002346 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002347
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002348 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002349 llvm::FunctionType::get(Builder.getVoidTy(),
2350 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002351 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002352 Builder.CreateCall(Register, Module);
2353 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002354
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002355 return LoadFunction;
2356}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002357
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002358llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002359 const ObjCContainerDecl *CD) {
2360 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002361 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002362 StringRef CategoryName = OCD ? OCD->getName() : "";
2363 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002364 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002365 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002366
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002367 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002368 llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002369 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002370 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2371 MethodName, isClassMethod);
2372
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002373 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002374 = llvm::Function::Create(MethodTy,
2375 llvm::GlobalValue::InternalLinkage,
2376 FunctionName,
2377 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002378 return Method;
2379}
2380
David Chisnall789ecde2011-05-23 22:33:28 +00002381llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002382 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002383}
2384
David Chisnall789ecde2011-05-23 22:33:28 +00002385llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002386 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002387}
2388
David Chisnall789ecde2011-05-23 22:33:28 +00002389llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002390 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002391}
David Chisnall789ecde2011-05-23 22:33:28 +00002392llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002393 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002394}
2395
Daniel Dunbar309a4362009-07-24 07:40:24 +00002396llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002397 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002398}
2399
David Chisnall9f6614e2011-03-23 16:36:54 +00002400void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002401 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002402 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002403}
Chris Lattner5dc08672009-05-08 00:11:50 +00002404
David Chisnall0faa5162009-12-24 02:26:34 +00002405
David Chisnall9f6614e2011-03-23 16:36:54 +00002406void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002407 const ObjCAtTryStmt &S) {
2408 // Unlike the Apple non-fragile runtimes, which also uses
2409 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2410 // EH support isn't a veneer over C++ EH. Instead, exception
2411 // objects are created by __objc_exception_throw and destroyed by
2412 // the personality function; this avoids the need for bracketing
2413 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2414 // (or even _Unwind_DeleteException), but probably doesn't
2415 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002416 //
David Chisnall80558d22011-03-20 21:35:39 +00002417 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002418 // exception handler.
2419 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2420 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002421}
2422
David Chisnall9f6614e2011-03-23 16:36:54 +00002423void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002424 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002425 llvm::Value *ExceptionAsObject;
2426
Chris Lattner5dc08672009-05-08 00:11:50 +00002427 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002428 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002429 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002430 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002431 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002432 "Unexpected rethrow outside @catch block.");
2433 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2434 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002435 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Chris Lattner5dc08672009-05-08 00:11:50 +00002437 // Note: This may have to be an invoke, if we want to support constructs like:
2438 // @try {
2439 // @throw(obj);
2440 // }
2441 // @catch(id) ...
2442 //
2443 // This is effectively turning @throw into an incredibly-expensive goto, but
2444 // it may happen as a result of inlining followed by missed optimizations, or
2445 // as a result of stupidity.
2446 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2447 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002448 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002449 CGF.Builder.CreateUnreachable();
2450 } else {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002451 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2452 ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002453 }
2454 // Clear the insertion point to indicate we are in unreachable code.
2455 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002456}
2457
David Chisnall9f6614e2011-03-23 16:36:54 +00002458llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002459 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002460 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002461 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002462 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002463}
2464
David Chisnall9f6614e2011-03-23 16:36:54 +00002465void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002466 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002467 CGBuilderTy B = CGF.Builder;
2468 src = EnforceType(B, src, IdTy);
2469 dst = EnforceType(B, dst, PtrToIdTy);
2470 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002471}
2472
David Chisnall9f6614e2011-03-23 16:36:54 +00002473void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002474 llvm::Value *src, llvm::Value *dst,
2475 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002476 CGBuilderTy B = CGF.Builder;
2477 src = EnforceType(B, src, IdTy);
2478 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002479 if (!threadlocal)
2480 B.CreateCall2(GlobalAssignFn, src, dst);
2481 else
2482 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002483 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002484}
2485
David Chisnall9f6614e2011-03-23 16:36:54 +00002486void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002487 llvm::Value *src, llvm::Value *dst,
2488 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002489 CGBuilderTy B = CGF.Builder;
2490 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002491 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002492 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002493}
2494
David Chisnall9f6614e2011-03-23 16:36:54 +00002495void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002496 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002497 CGBuilderTy B = CGF.Builder;
2498 src = EnforceType(B, src, IdTy);
2499 dst = EnforceType(B, dst, PtrToIdTy);
2500 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002501}
2502
David Chisnall9f6614e2011-03-23 16:36:54 +00002503void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002504 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002505 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002506 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002507 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002508 DestPtr = EnforceType(B, DestPtr, PtrTy);
2509 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002510
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002511 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002512}
2513
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002514llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2515 const ObjCInterfaceDecl *ID,
2516 const ObjCIvarDecl *Ivar) {
2517 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2518 + '.' + Ivar->getNameAsString();
2519 // Emit the variable and initialize it with what we think the correct value
2520 // is. This allows code compiled with non-fragile ivars to work correctly
2521 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002522 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2523 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002524 // This will cause a run-time crash if we accidentally use it. A value of
2525 // 0 would seem more sensible, but will silently overwrite the isa pointer
2526 // causing a great deal of confusion.
2527 uint64_t Offset = -1;
2528 // We can't call ComputeIvarBaseOffset() here if we have the
2529 // implementation, because it will create an invalid ASTRecordLayout object
2530 // that we are then stuck with forever, so we only initialize the ivar
2531 // offset variable with a guess if we only have the interface. The
2532 // initializer will be reset later anyway, when we are generating the class
2533 // description.
2534 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002535 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002536 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2537
David Chisnall49de5282011-10-08 08:54:36 +00002538 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002539 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002540 // Don't emit the guess in non-PIC code because the linker will not be able
2541 // to replace it with the real version for a library. In non-PIC code you
2542 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002543 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002544 if (CGM.getLangOptions().PICLevel) {
2545 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002546 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002547 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2548 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2549 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2550 IvarOffsetGV, Name);
2551 } else {
2552 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002553 llvm::Type::getInt32PtrTy(VMContext), false,
2554 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002555 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002556 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002557 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002558}
2559
David Chisnall9f6614e2011-03-23 16:36:54 +00002560LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002561 QualType ObjectTy,
2562 llvm::Value *BaseValue,
2563 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002564 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002565 const ObjCInterfaceDecl *ID =
2566 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002567 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2568 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002569}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002570
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002571static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2572 const ObjCInterfaceDecl *OID,
2573 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002574 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2575 next = next->getNextIvar()) {
2576 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002577 return OID;
2578 }
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002580 // Otherwise check in the super class.
2581 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2582 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002584 return 0;
2585}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002586
David Chisnall9f6614e2011-03-23 16:36:54 +00002587llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002588 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002589 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002590 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002591 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002592 if (RuntimeVersion < 10)
2593 return CGF.Builder.CreateZExtOrBitCast(
2594 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2595 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2596 PtrDiffTy);
2597 std::string name = "__objc_ivar_offset_value_" +
2598 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2599 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2600 if (!Offset)
2601 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002602 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2603 llvm::Constant::getNullValue(IntTy), name);
David Chisnall63ff7032011-07-07 12:34:51 +00002604 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002605 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002606 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Richard Trieu243f1082011-09-21 02:46:06 +00002607 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002608}
2609
David Chisnall9f6614e2011-03-23 16:36:54 +00002610CGObjCRuntime *
2611clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2612 if (CGM.getLangOptions().ObjCNonFragileABI)
2613 return new CGObjCGNUstep(CGM);
2614 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002615}