blob: 82a0f9b12269c0bdb8bf885759c83950d23edfb6 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000021
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnalle1d2584d2011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000038
David Chisnalld7972f52011-03-23 16:36:54 +000039#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000040
41
Chris Lattner87ab27d2008-06-26 04:19:03 +000042using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000043using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000044using llvm::dyn_cast;
45
Chris Lattnerb7256cd2008-03-01 08:50:34 +000046
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047namespace {
David Chisnall34d00052011-03-26 11:48:37 +000048/// Class that lazily initialises the runtime function. Avoids inserting the
49/// types and the function declaration into a module if they're not used, and
50/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000051class LazyRuntimeFunction {
52 CodeGenModule *CGM;
53 std::vector<const llvm::Type*> ArgTys;
54 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000055 llvm::Constant *Function;
David Chisnalld7972f52011-03-23 16:36:54 +000056 public:
David Chisnall34d00052011-03-26 11:48:37 +000057 /// Constructor leaves this class uninitialized, because it is intended to
58 /// be used as a field in another class and not all of the types that are
59 /// used as arguments will necessarily be available at construction time.
David Chisnalld7972f52011-03-23 16:36:54 +000060 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
61
David Chisnall34d00052011-03-26 11:48:37 +000062 /// Initialises the lazy function with the name, return type, and the types
63 /// of the arguments.
David Chisnalld7972f52011-03-23 16:36:54 +000064 END_WITH_NULL
65 void init(CodeGenModule *Mod, const char *name,
66 const llvm::Type *RetTy, ...) {
67 CGM =Mod;
68 FunctionName = name;
69 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000070 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000071 va_list Args;
72 va_start(Args, RetTy);
73 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
74 ArgTys.push_back(ArgTy);
75 va_end(Args);
76 // Push the return type on at the end so we can pop it off easily
77 ArgTys.push_back(RetTy);
78 }
David Chisnall34d00052011-03-26 11:48:37 +000079 /// Overloaded cast operator, allows the class to be implicitly cast to an
80 /// LLVM constant.
David Chisnall3fe89562011-05-23 22:33:28 +000081 operator llvm::Constant*() {
David Chisnalld7972f52011-03-23 16:36:54 +000082 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000083 if (0 == FunctionName) return 0;
84 // We put the return type on the end of the vector, so pop it back off
David Chisnalld7972f52011-03-23 16:36:54 +000085 const llvm::Type *RetTy = ArgTys.back();
86 ArgTys.pop_back();
87 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
88 Function =
David Chisnall3fe89562011-05-23 22:33:28 +000089 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000090 // We won't need to use the types again, so we may as well clean up the
91 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +000092 ArgTys.resize(0);
93 }
94 return Function;
95 }
David Chisnall3fe89562011-05-23 22:33:28 +000096 operator llvm::Function*() {
97 return dyn_cast<llvm::Function>((llvm::Constant*)this);
98 }
David Chisnalld7972f52011-03-23 16:36:54 +000099};
100
101
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000106protected:
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// The module that is using this class
David Chisnalld7972f52011-03-23 16:36:54 +0000108 CodeGenModule &CGM;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000110 llvm::Module &TheModule;
David Chisnall34d00052011-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.
David Chisnall76803412011-03-23 22:52:06 +0000113 const llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// struct objc_super*. The type of the argument to the superclass message
115 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000116 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-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 Lattner8d3f4a42009-01-27 05:06:01 +0000120 const llvm::PointerType *SelectorTy;
David Chisnall34d00052011-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
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000123 const llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-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 Lattner8d3f4a42009-01-27 05:06:01 +0000126 const llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-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.
David Chisnall76803412011-03-23 22:52:06 +0000132 const llvm::PointerType *IMPTy;
David Chisnall34d00052011-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 Lattner8d3f4a42009-01-27 05:06:01 +0000137 const llvm::PointerType *IdTy;
David Chisnall34d00052011-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.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000140 const llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-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 McCall2da83a32010-02-26 00:48:12 +0000143 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// LLVM type for C int type.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000145 const llvm::IntegerType *IntTy;
David Chisnall34d00052011-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 Lattner8d3f4a42009-01-27 05:06:01 +0000149 const llvm::PointerType *PtrTy;
David Chisnall34d00052011-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...
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000153 const llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000154 /// LLVM type for C size_t. Used in various runtime data structures.
David Chisnall168b80f2010-12-26 22:13:16 +0000155 const llvm::IntegerType *SizeTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
David Chisnall168b80f2010-12-26 22:13:16 +0000157 const llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
159 /// variables.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000160 const llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000161 /// LLVM type for Objective-C BOOL type.
David Chisnall168b80f2010-12-26 22:13:16 +0000162 const llvm::Type *BoolTy;
David Chisnall34d00052011-03-26 11:48:37 +0000163 /// Metadata kind used to tie method lookups to message sends. The GNUstep
164 /// runtime provides some LLVM passes that can use this to do things like
165 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000166 unsigned msgSendMDKind;
David Chisnall34d00052011-03-26 11:48:37 +0000167 /// Helper function that generates a constant string and returns a pointer to
168 /// the start of the string. The result of this function can be used anywhere
169 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000170 llvm::Constant *MakeConstantString(const std::string &Str,
171 const std::string &Name="") {
172 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
173 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
174 }
David Chisnall34d00052011-03-26 11:48:37 +0000175 /// Emits a linkonce_odr string, whose name is the prefix followed by the
176 /// string value. This allows the linker to combine the strings between
177 /// different modules. Used for EH typeinfo names, selector strings, and a
178 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000179 llvm::Constant *ExportUniqueString(const std::string &Str,
180 const std::string prefix) {
181 std::string name = prefix + Str;
182 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
183 if (!ConstStr) {
184 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
185 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
186 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
187 }
188 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
189 }
David Chisnall34d00052011-03-26 11:48:37 +0000190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
192 /// first argument.
David Chisnall76803412011-03-23 22:52:06 +0000193 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000194 std::vector<llvm::Constant*> &V,
195 llvm::StringRef Name="",
196 llvm::GlobalValue::LinkageTypes linkage
197 =llvm::GlobalValue::InternalLinkage) {
198 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
199 return new llvm::GlobalVariable(TheModule, Ty, false,
200 linkage, C, Name);
201 }
David Chisnall34d00052011-03-26 11:48:37 +0000202 /// Generates a global array. The vector must contain the same number of
203 /// elements that the array type declares, of the type specified as the array
204 /// element type.
David Chisnall76803412011-03-23 22:52:06 +0000205 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000206 std::vector<llvm::Constant*> &V,
207 llvm::StringRef Name="",
208 llvm::GlobalValue::LinkageTypes linkage
209 =llvm::GlobalValue::InternalLinkage) {
210 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
211 return new llvm::GlobalVariable(TheModule, Ty, false,
212 linkage, C, Name);
213 }
David Chisnall34d00052011-03-26 11:48:37 +0000214 /// Generates a global array, inferring the array type from the specified
215 /// element type and the size of the initialiser.
David Chisnall76803412011-03-23 22:52:06 +0000216 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000217 std::vector<llvm::Constant*> &V,
218 llvm::StringRef Name="",
219 llvm::GlobalValue::LinkageTypes linkage
220 =llvm::GlobalValue::InternalLinkage) {
221 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
222 return MakeGlobal(ArrayTy, V, Name, linkage);
223 }
David Chisnall34d00052011-03-26 11:48:37 +0000224 /// Ensures that the value has the required type, by inserting a bitcast if
225 /// required. This function lets us avoid inserting bitcasts that are
226 /// redundant.
David Chisnall76803412011-03-23 22:52:06 +0000227 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
228 if (V->getType() == Ty) return V;
229 return B.CreateBitCast(V, Ty);
230 }
231 // Some zeros used for GEPs in lots of places.
232 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000233 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000234 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000235 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000236 llvm::LLVMContext &VMContext;
237private:
David Chisnall34d00052011-03-26 11:48:37 +0000238 /// Placeholder for the class. Lots of things refer to the class before we've
239 /// actually emitted it. We use this alias as a placeholder, and then replace
240 /// it with a pointer to the class structure before finally emitting the
241 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000242 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000243 /// Placeholder for the metaclass. Lots of things refer to the class before
244 /// we've / actually emitted it. We use this alias as a placeholder, and then
245 /// replace / it with a pointer to the metaclass structure before finally
246 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000247 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000248 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000249 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000250 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000251 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000252 /// All of the Objective-C constant strings that have been generated for this
253 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000254 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000255 /// Map from string values to Objective-C constant strings in the output.
256 /// Used to prevent emitting Objective-C strings more than once. This should
257 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000258 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000259 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000260 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000261 /// For each variant of a selector, we store the type encoding and a
262 /// placeholder value. For an untyped selector, the type will be the empty
263 /// string. Selector references are all done via the module's selector table,
264 /// so we create an alias as a placeholder and then replace it with the real
265 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000266 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000267 /// Type of the selector map. This is roughly equivalent to the structure
268 /// used in the GNUstep runtime, which maintains a list of all of the valid
269 /// types for a selector in a table.
David Chisnalld7972f52011-03-23 16:36:54 +0000270 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
271 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000272 /// A map from selectors to selector types. This allows us to emit all
273 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000274 SelectorMap SelectorTable;
275
David Chisnall34d00052011-03-26 11:48:37 +0000276 /// Selectors related to memory management. When compiling in GC mode, we
277 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000278 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000279 /// Runtime functions used for memory management in GC mode. Note that clang
280 /// supports code generation for calling these functions, but neither GNU
281 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000282 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
283 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000284
David Chisnalld3858d62011-03-25 11:57:33 +0000285protected:
David Chisnall34d00052011-03-26 11:48:37 +0000286 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000287 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000288 /// Function used for rethrowing exceptions, used at the end of @finally or
289 /// @synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000290 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000291 /// Function called when entering a catch function. This is required for
292 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000293 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000294 /// Function called when exiting from a catch block. Used to do exception
295 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000296 LazyRuntimeFunction ExitCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000297 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000298 LazyRuntimeFunction SyncEnterFn;
David Chisnall34d00052011-03-26 11:48:37 +0000299 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000300 LazyRuntimeFunction SyncExitFn;
301
David Chisnalld3858d62011-03-25 11:57:33 +0000302private:
303
David Chisnall34d00052011-03-26 11:48:37 +0000304 /// Function called if fast enumeration detects that the collection is
305 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000306 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000307 /// Function for implementing synthesized property getters that return an
308 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000309 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000310 /// Function for implementing synthesized property setters that return an
311 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000312 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000313 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000314 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000315 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000316 LazyRuntimeFunction SetStructPropertyFn;
317
David Chisnall34d00052011-03-26 11:48:37 +0000318 /// The version of the runtime that this class targets. Must match the
319 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000320 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000321 /// The version of the protocol class. Used to differentiate between ObjC1
322 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
323 /// components and can not contain declared properties. We always emit
324 /// Objective-C 2 property structures, but we have to pretend that they're
325 /// Objective-C 1 property structures when targeting the GCC runtime or it
326 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000327 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000328private:
David Chisnall34d00052011-03-26 11:48:37 +0000329 /// Generates an instance variable list structure. This is a structure
330 /// containing a size and an array of structures containing instance variable
331 /// metadata. This is used purely for introspection in the fragile ABI. In
332 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000333 llvm::Constant *GenerateIvarList(
334 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
335 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
336 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall34d00052011-03-26 11:48:37 +0000337 /// Generates a method list structure. This is a structure containing a size
338 /// and an array of structures containing method metadata.
339 ///
340 /// This structure is used by both classes and categories, and contains a next
341 /// pointer allowing them to be chained together in a linked list.
David Chisnalld7972f52011-03-23 16:36:54 +0000342 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
343 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000344 const llvm::SmallVectorImpl<Selector> &MethodSels,
345 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000346 bool isClassMethodList);
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Emits an empty protocol. This is used for @protocol() where no protocol
348 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
349 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000350 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-03-26 11:48:37 +0000351 /// Generates a list of property metadata structures. This follows the same
352 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000353 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
354 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
355 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000356 /// Generates a list of referenced protocols. Classes, categories, and
357 /// protocols all use this structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000358 llvm::Constant *GenerateProtocolList(
359 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnall34d00052011-03-26 11:48:37 +0000360 /// To ensure that all protocols are seen by the runtime, we add a category on
361 /// a class defined in the runtime, declaring no methods, but adopting the
362 /// protocols. This is a horribly ugly hack, but it allows us to collect all
363 /// of the protocols without changing the ABI.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000364 void GenerateProtocolHolderCategory(void);
David Chisnall34d00052011-03-26 11:48:37 +0000365 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000366 llvm::Constant *GenerateClassStructure(
367 llvm::Constant *MetaClass,
368 llvm::Constant *SuperClass,
369 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000370 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000371 llvm::Constant *Version,
372 llvm::Constant *InstanceSize,
373 llvm::Constant *IVars,
374 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000375 llvm::Constant *Protocols,
376 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000377 llvm::Constant *Properties,
378 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000379 /// Generates a method list. This is used by protocols to define the required
380 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000381 llvm::Constant *GenerateProtocolMethodList(
382 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
383 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000384 /// Returns a selector with the specified type encoding. An empty string is
385 /// used to return an untyped selector (with the types field set to NULL).
David Chisnalld7972f52011-03-23 16:36:54 +0000386 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
387 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000388 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000389 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
390 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000391 /// Emits a reference to a class. This allows the linker to object if there
392 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000393 void EmitClassRef(const std::string &className);
David Chisnall76803412011-03-23 22:52:06 +0000394protected:
David Chisnall34d00052011-03-26 11:48:37 +0000395 /// Looks up the method for sending a message to the specified object. This
396 /// mechanism differs between the GCC and GNU runtimes, so this method must be
397 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000398 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
399 llvm::Value *&Receiver,
400 llvm::Value *cmd,
401 llvm::MDNode *node) = 0;
David Chisnall34d00052011-03-26 11:48:37 +0000402 /// Looks up the method for sending a message to a superclass. This mechanism
403 /// differs between the GCC and GNU runtimes, so this method must be
404 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000405 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
406 llvm::Value *ObjCSuper,
407 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000408public:
David Chisnalld7972f52011-03-23 16:36:54 +0000409 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
410 unsigned protocolClassVersion);
411
David Chisnall481e3a82010-01-23 02:40:42 +0000412 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000413
414 virtual RValue
415 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000416 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000417 QualType ResultType,
418 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000419 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000420 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000421 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000422 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000423 virtual RValue
424 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000425 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000426 QualType ResultType,
427 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000428 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000429 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000430 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000431 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000432 const CallArgList &CallArgs,
433 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000434 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000435 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000436 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
437 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000438 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
439 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000440 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000441
442 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000443 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000444 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
445 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000446 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000447 const ObjCProtocolDecl *PD);
448 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000449 virtual llvm::Function *ModuleInitFunction();
David Chisnall3fe89562011-05-23 22:33:28 +0000450 virtual llvm::Constant *GetPropertyGetFunction();
451 virtual llvm::Constant *GetPropertySetFunction();
452 virtual llvm::Constant *GetSetStructFunction();
453 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000454 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000455
David Chisnalld7972f52011-03-23 16:36:54 +0000456 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000457 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000458 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000459 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000460 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000461 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000462 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000463 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000464 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000465 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000466 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000467 llvm::Value *src, llvm::Value *dest,
468 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000469 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000470 llvm::Value *src, llvm::Value *dest,
471 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000472 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000473 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000474 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000475 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000476 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000477 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000478 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000479 QualType ObjectTy,
480 llvm::Value *BaseValue,
481 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000482 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000483 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000484 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000485 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000486 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000487 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000488 return NULLPtr;
489 }
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000490
491 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
492 return 0;
493 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000494};
David Chisnall34d00052011-03-26 11:48:37 +0000495/// Class representing the legacy GCC Objective-C ABI. This is the default when
496/// -fobjc-nonfragile-abi is not specified.
497///
498/// The GCC ABI target actually generates code that is approximately compatible
499/// with the new GNUstep runtime ABI, but refrains from using any features that
500/// would not work with the GCC runtime. For example, clang always generates
501/// the extended form of the class structure, and the extra fields are simply
502/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000503class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000504 /// The GCC ABI message lookup function. Returns an IMP pointing to the
505 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000506 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000507 /// The GCC ABI superclass message lookup function. Takes a pointer to a
508 /// structure describing the receiver and the class, and a selector as
509 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000510 LazyRuntimeFunction MsgLookupSuperFn;
511protected:
512 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
513 llvm::Value *&Receiver,
514 llvm::Value *cmd,
515 llvm::MDNode *node) {
516 CGBuilderTy &Builder = CGF.Builder;
517 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
518 EnforceType(Builder, Receiver, IdTy),
519 EnforceType(Builder, cmd, SelectorTy));
520 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
521 return imp;
522 }
523 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
524 llvm::Value *ObjCSuper,
525 llvm::Value *cmd) {
526 CGBuilderTy &Builder = CGF.Builder;
527 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
528 PtrToObjCSuperTy), cmd};
529 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
530 }
David Chisnalld7972f52011-03-23 16:36:54 +0000531 public:
David Chisnall76803412011-03-23 22:52:06 +0000532 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
533 // IMP objc_msg_lookup(id, SEL);
534 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
535 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
536 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
537 PtrToObjCSuperTy, SelectorTy, NULL);
538 }
David Chisnalld7972f52011-03-23 16:36:54 +0000539};
David Chisnall34d00052011-03-26 11:48:37 +0000540/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000541class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000542 /// The slot lookup function. Returns a pointer to a cacheable structure
543 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000544 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000545 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
546 /// a structure describing the receiver and the class, and a selector as
547 /// arguments. Returns the slot for the corresponding method. Superclass
548 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000549 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall34d00052011-03-26 11:48:37 +0000550 /// Type of an slot structure pointer. This is returned by the various
551 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000552 llvm::Type *SlotTy;
553 protected:
554 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
555 llvm::Value *&Receiver,
556 llvm::Value *cmd,
557 llvm::MDNode *node) {
558 CGBuilderTy &Builder = CGF.Builder;
559 llvm::Function *LookupFn = SlotLookupFn;
560
561 // Store the receiver on the stack so that we can reload it later
562 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
563 Builder.CreateStore(Receiver, ReceiverPtr);
564
565 llvm::Value *self;
566
567 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
568 self = CGF.LoadObjCSelf();
569 } else {
570 self = llvm::ConstantPointerNull::get(IdTy);
571 }
572
573 // The lookup function is guaranteed not to capture the receiver pointer.
574 LookupFn->setDoesNotCapture(1);
575
576 llvm::CallInst *slot =
577 Builder.CreateCall3(LookupFn,
578 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
579 EnforceType(Builder, cmd, SelectorTy),
580 EnforceType(Builder, self, IdTy));
581 slot->setOnlyReadsMemory();
582 slot->setMetadata(msgSendMDKind, node);
583
584 // Load the imp from the slot
585 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
586
587 // The lookup function may have changed the receiver, so make sure we use
588 // the new one.
589 Receiver = Builder.CreateLoad(ReceiverPtr, true);
590 return imp;
591 }
592 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
593 llvm::Value *ObjCSuper,
594 llvm::Value *cmd) {
595 CGBuilderTy &Builder = CGF.Builder;
596 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
597
598 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
599 lookupArgs+2);
600 slot->setOnlyReadsMemory();
601
602 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
603 }
David Chisnalld7972f52011-03-23 16:36:54 +0000604 public:
David Chisnall76803412011-03-23 22:52:06 +0000605 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
606 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
607 PtrTy, PtrTy, IntTy, IMPTy, NULL);
608 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
609 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
610 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
611 SelectorTy, IdTy, NULL);
612 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
613 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
614 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000615 // If we're in ObjC++ mode, then we want to make
616 if (CGM.getLangOptions().CPlusPlus) {
617 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
618 // void *__cxa_begin_catch(void *e)
619 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
620 // void __cxa_end_catch(void)
621 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
622 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnallec343e82011-04-05 17:15:18 +0000623 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000624 }
David Chisnall76803412011-03-23 22:52:06 +0000625 }
David Chisnalld7972f52011-03-23 16:36:54 +0000626};
627
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000628} // end anonymous namespace
629
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000630
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000631/// Emits a reference to a dummy variable which is emitted with each class.
632/// This ensures that a linker error will be generated when trying to link
633/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000634void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000635 std::string symbolRef = "__objc_class_ref_" + className;
636 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000637 if (TheModule.getGlobalVariable(symbolRef))
638 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000639 std::string symbolName = "__objc_class_name_" + className;
640 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
641 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000642 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
643 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000644 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000645 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000646 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000647}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000648
David Chisnalld7972f52011-03-23 16:36:54 +0000649static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
650 const llvm::StringRef &CategoryName, const Selector MethodName,
651 bool isClassMethod) {
652 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000653 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
654 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000655 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
656 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000657}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000658
David Chisnalld7972f52011-03-23 16:36:54 +0000659CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
660 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000661 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
662 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
663 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000664
665 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
666
David Chisnalld7972f52011-03-23 16:36:54 +0000667 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000668 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000669 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000670 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000671 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000672 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000673 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000674 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000675 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000676 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000678 Int8Ty = llvm::Type::getInt8Ty(VMContext);
679 // C string type. Used in lots of places.
680 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
681
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000682 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000683 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000684 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000685 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000686 QualType selTy = CGM.getContext().getObjCSelType();
687 if (QualType() == selTy) {
688 SelectorTy = PtrToInt8Ty;
689 } else {
690 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
691 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000692
Owen Anderson9793f0e2009-07-29 22:16:19 +0000693 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000694 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner4bd55962008-03-30 23:03:07 +0000696 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000697 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
698 ASTIdTy = CanQualType();
699 if (UnqualIdTy != QualType()) {
700 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000701 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000702 } else {
703 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000704 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000705 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000706
David Chisnall76803412011-03-23 22:52:06 +0000707 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
708 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
709
David Chisnalld7972f52011-03-23 16:36:54 +0000710 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
711
712 // void objc_exception_throw(id);
713 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000714 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000715 // int objc_sync_enter(id);
716 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
717 // int objc_sync_exit(id);
718 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
719
720 // void objc_enumerationMutation (id)
721 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
722 IdTy, NULL);
723
724 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
725 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
726 PtrDiffTy, BoolTy, NULL);
727 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
728 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
729 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
730 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
731 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
732 PtrDiffTy, BoolTy, BoolTy, NULL);
733 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
734 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
735 PtrDiffTy, BoolTy, BoolTy, NULL);
736
Chris Lattner4bd55962008-03-30 23:03:07 +0000737 // IMP type
738 std::vector<const llvm::Type*> IMPArgs;
739 IMPArgs.push_back(IdTy);
740 IMPArgs.push_back(SelectorTy);
David Chisnall76803412011-03-23 22:52:06 +0000741 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
742 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000743
David Chisnalld3858d62011-03-25 11:57:33 +0000744 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000745 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000746 // This is a bit of an hack. We should sort this out by having a proper
747 // CGObjCGNUstep subclass for GC, but we may want to really support the old
748 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
749 RuntimeVersion = 10;
David Chisnall5bb4efd2010-02-03 15:59:02 +0000750 // Get selectors needed in GC mode
751 RetainSel = GetNullarySelector("retain", CGM.getContext());
752 ReleaseSel = GetNullarySelector("release", CGM.getContext());
753 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
754
755 // Get functions needed in GC mode
756
757 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000758 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
759 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000760 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000761 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
762 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000763 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000764 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
765 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000766 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000767 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000768 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000769 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000770 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000771 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
772 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000773 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000774}
Mike Stumpdd93a192009-07-31 21:31:32 +0000775
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000776// This has to perform the lookup every time, since posing and related
777// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000778llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000779 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000780 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000781 // With the incompatible ABI, this will need to be replaced with a direct
782 // reference to the class symbol. For the compatible nonfragile ABI we are
783 // still performing this lookup at run time but emitting the symbol for the
784 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000785 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000786 ClassName = Builder.CreateStructGEP(ClassName, 0);
787
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000788 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000789 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000790 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000791 Params,
792 true),
793 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000794 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000795}
796
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000797llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000798 const std::string &TypeEncoding, bool lval) {
799
800 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
801 llvm::GlobalAlias *SelValue = 0;
802
803
804 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
805 e = Types.end() ; i!=e ; i++) {
806 if (i->first == TypeEncoding) {
807 SelValue = i->second;
808 break;
809 }
810 }
811 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000812 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000813 llvm::GlobalValue::PrivateLinkage,
814 ".objc_selector_"+Sel.getAsString(), NULL,
815 &TheModule);
816 Types.push_back(TypedSelector(TypeEncoding, SelValue));
817 }
818
David Chisnall76803412011-03-23 22:52:06 +0000819 if (lval) {
820 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
821 Builder.CreateStore(SelValue, tmp);
822 return tmp;
823 }
824 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000825}
826
827llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
828 bool lval) {
829 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000830}
831
Daniel Dunbar45858d22010-02-03 20:11:42 +0000832llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000833 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000834 std::string SelTypes;
835 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000836 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000837}
838
John McCall2ca705e2010-07-24 00:37:23 +0000839llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000840 if (!CGM.getLangOptions().CPlusPlus) {
841 if (T->isObjCIdType()
842 || T->isObjCQualifiedIdType()) {
843 // With the old ABI, there was only one kind of catchall, which broke
844 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
845 // a pointer indicating object catchalls, and NULL to indicate real
846 // catchalls
847 if (CGM.getLangOptions().ObjCNonFragileABI) {
848 return MakeConstantString("@id");
849 } else {
850 return 0;
851 }
852 }
853
854 // All other types should be Objective-C interface pointer types.
855 const ObjCObjectPointerType *OPT =
856 T->getAs<ObjCObjectPointerType>();
857 assert(OPT && "Invalid @catch type.");
858 const ObjCInterfaceDecl *IDecl =
859 OPT->getObjectType()->getInterface();
860 assert(IDecl && "Invalid @catch type.");
861 return MakeConstantString(IDecl->getIdentifier()->getName());
862 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000863 // For Objective-C++, we want to provide the ability to catch both C++ and
864 // Objective-C objects in the same function.
865
866 // There's a particular fixed type info for 'id'.
867 if (T->isObjCIdType() ||
868 T->isObjCQualifiedIdType()) {
869 llvm::Constant *IDEHType =
870 CGM.getModule().getGlobalVariable("__objc_id_type_info");
871 if (!IDEHType)
872 IDEHType =
873 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
874 false,
875 llvm::GlobalValue::ExternalLinkage,
876 0, "__objc_id_type_info");
877 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
878 }
879
880 const ObjCObjectPointerType *PT =
881 T->getAs<ObjCObjectPointerType>();
882 assert(PT && "Invalid @catch type.");
883 const ObjCInterfaceType *IT = PT->getInterfaceType();
884 assert(IT && "Invalid @catch type.");
885 std::string className = IT->getDecl()->getIdentifier()->getName();
886
887 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
888
889 // Return the existing typeinfo if it exists
890 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
891 if (typeinfo) return typeinfo;
892
893 // Otherwise create it.
894
895 // vtable for gnustep::libobjc::__objc_class_type_info
896 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
897 // platform's name mangling.
898 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
899 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
900 if (!Vtable) {
901 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
902 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
903 }
904 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
905 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
906 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
907
908 llvm::Constant *typeName =
909 ExportUniqueString(className, "__objc_eh_typename_");
910
911 std::vector<llvm::Constant*> fields;
912 fields.push_back(Vtable);
913 fields.push_back(typeName);
914 llvm::Constant *TI =
915 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
916 NULL), fields, "__objc_eh_typeinfo_" + className,
917 llvm::GlobalValue::LinkOnceODRLinkage);
918 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000919}
920
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000921/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000922llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000923
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000924 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000925
David Chisnall358e7512010-01-27 12:49:23 +0000926 // Look for an existing one
927 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
928 if (old != ObjCStrings.end())
929 return old->getValue();
930
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000931 std::vector<llvm::Constant*> Ivars;
932 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000933 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000934 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000935 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000936 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000937 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000938 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
939 ObjCStrings[Str] = ObjCStr;
940 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000941 return ObjCStr;
942}
943
944///Generates a message send where the super is the receiver. This is a message
945///send to self with special delivery semantics indicating which class's method
946///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000947RValue
948CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000949 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000950 QualType ResultType,
951 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000952 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000953 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000954 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000955 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000956 const CallArgList &CallArgs,
957 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000958 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
959 if (Sel == RetainSel || Sel == AutoreleaseSel) {
960 return RValue::get(Receiver);
961 }
962 if (Sel == ReleaseSel) {
963 return RValue::get(0);
964 }
965 }
David Chisnallea529a42010-05-01 12:37:16 +0000966
967 CGBuilderTy &Builder = CGF.Builder;
968 llvm::Value *cmd = GetSelector(Builder, Sel);
969
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000970
971 CallArgList ActualArgs;
972
Eli Friedman43dca6a2011-05-02 17:57:46 +0000973 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
974 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000975 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
976
977 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000978 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000979 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000980
Daniel Dunbar566421c2009-05-04 15:31:17 +0000981 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000982 if (isCategoryImpl) {
983 llvm::Constant *classLookupFunction = 0;
984 std::vector<const llvm::Type*> Params;
985 Params.push_back(PtrTy);
986 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000987 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000988 IdTy, Params, true), "objc_get_meta_class");
989 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000990 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000991 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000992 }
David Chisnallea529a42010-05-01 12:37:16 +0000993 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000994 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000995 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000996 // Set up global aliases for the metaclass or class pointer if they do not
997 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000998 // pointers to the class and metaclass structure created for the runtime
999 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001000 // super_class pointer from either the class or metaclass structure.
1001 if (IsClassMessage) {
1002 if (!MetaClassPtrAlias) {
1003 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1004 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1005 Class->getNameAsString(), NULL, &TheModule);
1006 }
1007 ReceiverClass = MetaClassPtrAlias;
1008 } else {
1009 if (!ClassPtrAlias) {
1010 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1011 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1012 Class->getNameAsString(), NULL, &TheModule);
1013 }
1014 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001015 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001016 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001017 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001018 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001019 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +00001020 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001021 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001022 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001023 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001024 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001025 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +00001026 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
1027 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001028 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001029
David Chisnallea529a42010-05-01 12:37:16 +00001030 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1031 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001032
David Chisnall76803412011-03-23 22:52:06 +00001033 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1034 const llvm::FunctionType *impType =
1035 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1036
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001037 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001038 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1039 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001040
David Chisnall9eecafa2010-05-01 11:15:56 +00001041 llvm::Value *impMD[] = {
1042 llvm::MDString::get(VMContext, Sel.getAsString()),
1043 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1044 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1045 };
Jay Foadea324f12011-04-21 19:59:12 +00001046 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001047
David Chisnallff5f88c2010-05-02 13:41:58 +00001048 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001049 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001050 0, &call);
1051 call->setMetadata(msgSendMDKind, node);
1052 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001053}
1054
Mike Stump11289f42009-09-09 15:08:12 +00001055/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001056RValue
1057CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001058 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001059 QualType ResultType,
1060 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001061 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001062 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001063 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001064 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +00001065 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +00001066 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1067 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1068 return RValue::get(Receiver);
1069 }
1070 if (Sel == ReleaseSel) {
1071 return RValue::get(0);
1072 }
1073 }
David Chisnall75afda62010-04-27 15:08:48 +00001074
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001075 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +00001076
1077 // If the return type is something that goes in an integer register, the
1078 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1079 // ourselves.
1080 //
1081 // The language spec says the result of this kind of message send is
1082 // undefined, but lots of people seem to have forgotten to read that
1083 // paragraph and insist on sending messages to nil that have structure
1084 // returns. With GCC, this generates a random return value (whatever happens
1085 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001086 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1087 // the stack.
1088 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1089 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001090
1091 llvm::BasicBlock *startBB = 0;
1092 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001093 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001094
1095 if (!isPointerSizedReturn) {
1096 startBB = Builder.GetInsertBlock();
1097 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001098 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001099
1100 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1101 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001102 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001103 CGF.EmitBlock(messageBB);
1104 }
1105
David Chisnall9f57c292009-08-17 16:35:33 +00001106 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001107 llvm::Value *cmd;
1108 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001109 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001110 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001111 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001112 cmd = EnforceType(Builder, cmd, SelectorTy);
1113 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001114
David Chisnall76803412011-03-23 22:52:06 +00001115 llvm::Value *impMD[] = {
1116 llvm::MDString::get(VMContext, Sel.getAsString()),
1117 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1118 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1119 };
Jay Foadea324f12011-04-21 19:59:12 +00001120 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001121
1122 // Get the IMP to call
1123 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1124
1125 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001126 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1127 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001128 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1129
1130 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001131 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001132 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001133 const llvm::FunctionType *impType =
1134 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001135 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001136
1137
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001138 // For sender-aware dispatch, we pass the sender as the third argument to a
1139 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001140 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001141 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001142 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001143 0, &call);
1144 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001145
David Chisnall29cefd12010-05-20 13:45:48 +00001146
David Chisnall75afda62010-04-27 15:08:48 +00001147 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001148 messageBB = CGF.Builder.GetInsertBlock();
1149 CGF.Builder.CreateBr(continueBB);
1150 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001151 if (msgRet.isScalar()) {
1152 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001153 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001154 phi->addIncoming(v, messageBB);
1155 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1156 msgRet = RValue::get(phi);
1157 } else if (msgRet.isAggregate()) {
1158 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001159 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001160 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001161 llvm::AllocaInst *NullVal =
1162 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001163 CGF.InitTempAlloca(NullVal,
1164 llvm::Constant::getNullValue(RetTy->getElementType()));
1165 phi->addIncoming(v, messageBB);
1166 phi->addIncoming(NullVal, startBB);
1167 msgRet = RValue::getAggregate(phi);
1168 } else /* isComplex() */ {
1169 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001170 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001171 phi->addIncoming(v.first, messageBB);
1172 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1173 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001174 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001175 phi2->addIncoming(v.second, messageBB);
1176 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1177 startBB);
1178 msgRet = RValue::getComplex(phi, phi2);
1179 }
1180 }
1181 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001182}
1183
Mike Stump11289f42009-09-09 15:08:12 +00001184/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001185/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +00001186llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1187 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +00001188 const llvm::SmallVectorImpl<Selector> &MethodSels,
1189 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001190 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001191 if (MethodSels.empty())
1192 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001193 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001194 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001195 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1196 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001197 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001198 NULL);
1199 std::vector<llvm::Constant*> Methods;
1200 std::vector<llvm::Constant*> Elements;
1201 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1202 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001203 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001204 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001205 MethodSels[i],
1206 isClassMethodList));
1207 assert(Method && "Can't generate metadata for method that doesn't exist");
1208 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1209 Elements.push_back(C);
1210 Elements.push_back(MethodTypes[i]);
1211 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001212 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001213 Elements.push_back(Method);
1214 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001215 }
1216
1217 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001218 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001219 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001220 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001221 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001222
1223 // Structure containing list pointer, array and array count
1224 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001225 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001226 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001227 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001228 NextPtrTy,
1229 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001230 ObjCMethodArrayTy,
1231 NULL);
1232 // Refine next pointer type to concrete type
1233 llvm::cast<llvm::OpaqueType>(
1234 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1235 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1236
1237 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001238 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001239 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001240 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001241 MethodTypes.size()));
1242 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001243
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001244 // Create an instance of the structure
1245 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1246}
1247
1248/// Generates an IvarList. Used in construction of a objc_class.
1249llvm::Constant *CGObjCGNU::GenerateIvarList(
1250 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1251 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1252 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001253 if (IvarNames.size() == 0)
1254 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001255 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001256 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001257 PtrToInt8Ty,
1258 PtrToInt8Ty,
1259 IntTy,
1260 NULL);
1261 std::vector<llvm::Constant*> Ivars;
1262 std::vector<llvm::Constant*> Elements;
1263 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1264 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001265 Elements.push_back(IvarNames[i]);
1266 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001267 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001268 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001269 }
1270
1271 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001272 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001273 IvarNames.size());
1274
Mike Stump11289f42009-09-09 15:08:12 +00001275
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001276 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001277 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001278 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001279 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001280 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001281 ObjCIvarArrayTy,
1282 NULL);
1283
1284 // Create an instance of the structure
1285 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1286}
1287
1288/// Generate a class structure
1289llvm::Constant *CGObjCGNU::GenerateClassStructure(
1290 llvm::Constant *MetaClass,
1291 llvm::Constant *SuperClass,
1292 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001293 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001294 llvm::Constant *Version,
1295 llvm::Constant *InstanceSize,
1296 llvm::Constant *IVars,
1297 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001298 llvm::Constant *Protocols,
1299 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001300 llvm::Constant *Properties,
1301 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001302 // Set up the class structure
1303 // Note: Several of these are char*s when they should be ids. This is
1304 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001305 //
1306 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1307 // anyway; the classes will still work with the GNU runtime, they will just
1308 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001309 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001310 PtrToInt8Ty, // class_pointer
1311 PtrToInt8Ty, // super_class
1312 PtrToInt8Ty, // name
1313 LongTy, // version
1314 LongTy, // info
1315 LongTy, // instance_size
1316 IVars->getType(), // ivars
1317 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001318 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001319 PtrTy, // dtable
1320 PtrTy, // subclass_list
1321 PtrTy, // sibling_class
1322 PtrTy, // protocols
1323 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001324 // New ABI:
1325 LongTy, // abi_version
1326 IvarOffsets->getType(), // ivar_offsets
1327 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001328 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001329 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001330 // Fill in the structure
1331 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001332 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001333 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001334 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001335 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001336 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001337 if (isMeta) {
1338 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001339 Elements.push_back(
1340 llvm::ConstantInt::get(LongTy,
1341 td.getTypeSizeInBits(ClassTy) /
1342 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001343 } else
1344 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001345 Elements.push_back(IVars);
1346 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001347 Elements.push_back(NULLPtr);
1348 Elements.push_back(NULLPtr);
1349 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001350 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001351 Elements.push_back(NULLPtr);
1352 Elements.push_back(Zero);
1353 Elements.push_back(IvarOffsets);
1354 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001355 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001356 // This is now an externally visible symbol, so that we can speed up class
1357 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001358 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1359 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001360}
1361
1362llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1363 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1364 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001365 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001366 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001367 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1368 PtrToInt8Ty,
1369 NULL);
1370 std::vector<llvm::Constant*> Methods;
1371 std::vector<llvm::Constant*> Elements;
1372 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1373 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001374 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001375 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001376 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001377 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001378 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001379 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001380 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001381 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001382 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001383 IntTy, ObjCMethodArrayTy, NULL);
1384 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001385 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001386 Methods.push_back(Array);
1387 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1388}
Mike Stumpdd93a192009-07-31 21:31:32 +00001389
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001390// Create the protocol list structure used in classes, categories and so on
1391llvm::Constant *CGObjCGNU::GenerateProtocolList(
1392 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001393 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001394 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001395 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001396 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001397 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001398 ProtocolArrayTy,
1399 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001400 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001401 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1402 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001403 llvm::Constant *protocol = 0;
1404 llvm::StringMap<llvm::Constant*>::iterator value =
1405 ExistingProtocols.find(*iter);
1406 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001407 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001408 } else {
1409 protocol = value->getValue();
1410 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001411 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001412 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001413 Elements.push_back(Ptr);
1414 }
Owen Anderson47034e12009-07-28 18:33:04 +00001415 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001416 Elements);
1417 Elements.clear();
1418 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001419 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001420 Elements.push_back(ProtocolArray);
1421 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1422}
1423
Mike Stump11289f42009-09-09 15:08:12 +00001424llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001425 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001426 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001427 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001428 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001429 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001430}
1431
1432llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1433 const std::string &ProtocolName) {
1434 llvm::SmallVector<std::string, 0> EmptyStringVector;
1435 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1436
1437 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001438 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001439 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1440 // Protocols are objects containing lists of the methods implemented and
1441 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001442 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001443 PtrToInt8Ty,
1444 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001445 MethodList->getType(),
1446 MethodList->getType(),
1447 MethodList->getType(),
1448 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001449 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001450 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001451 // The isa pointer must be set to a magic number so the runtime knows it's
1452 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001453 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001454 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1455 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001456 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1457 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001458 Elements.push_back(MethodList);
1459 Elements.push_back(MethodList);
1460 Elements.push_back(MethodList);
1461 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001462 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001463}
1464
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001465void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1466 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001467 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001468 llvm::SmallVector<std::string, 16> Protocols;
1469 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1470 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001471 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001472 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1473 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001474 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1475 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001476 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1477 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001478 std::string TypeStr;
1479 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001480 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1481 InstanceMethodNames.push_back(
1482 MakeConstantString((*iter)->getSelector().getAsString()));
1483 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1484 } else {
1485 OptionalInstanceMethodNames.push_back(
1486 MakeConstantString((*iter)->getSelector().getAsString()));
1487 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1488 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001489 }
1490 // Collect information about class methods:
1491 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1492 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001493 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1494 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001495 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001496 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1497 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001498 std::string TypeStr;
1499 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001500 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1501 ClassMethodNames.push_back(
1502 MakeConstantString((*iter)->getSelector().getAsString()));
1503 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1504 } else {
1505 OptionalClassMethodNames.push_back(
1506 MakeConstantString((*iter)->getSelector().getAsString()));
1507 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1508 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001509 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001510
1511 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1512 llvm::Constant *InstanceMethodList =
1513 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1514 llvm::Constant *ClassMethodList =
1515 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001516 llvm::Constant *OptionalInstanceMethodList =
1517 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1518 OptionalInstanceMethodTypes);
1519 llvm::Constant *OptionalClassMethodList =
1520 GenerateProtocolMethodList(OptionalClassMethodNames,
1521 OptionalClassMethodTypes);
1522
1523 // Property metadata: name, attributes, isSynthesized, setter name, setter
1524 // types, getter name, getter types.
1525 // The isSynthesized value is always set to 0 in a protocol. It exists to
1526 // simplify the runtime library by allowing it to use the same data
1527 // structures for protocol metadata everywhere.
1528 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1529 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1530 PtrToInt8Ty, NULL);
1531 std::vector<llvm::Constant*> Properties;
1532 std::vector<llvm::Constant*> OptionalProperties;
1533
1534 // Add all of the property methods need adding to the method list and to the
1535 // property metadata list.
1536 for (ObjCContainerDecl::prop_iterator
1537 iter = PD->prop_begin(), endIter = PD->prop_end();
1538 iter != endIter ; iter++) {
1539 std::vector<llvm::Constant*> Fields;
1540 ObjCPropertyDecl *property = (*iter);
1541
1542 Fields.push_back(MakeConstantString(property->getNameAsString()));
1543 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1544 property->getPropertyAttributes()));
1545 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1546 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1547 std::string TypeStr;
1548 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1549 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1550 InstanceMethodTypes.push_back(TypeEncoding);
1551 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1552 Fields.push_back(TypeEncoding);
1553 } else {
1554 Fields.push_back(NULLPtr);
1555 Fields.push_back(NULLPtr);
1556 }
1557 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1558 std::string TypeStr;
1559 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1560 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1561 InstanceMethodTypes.push_back(TypeEncoding);
1562 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1563 Fields.push_back(TypeEncoding);
1564 } else {
1565 Fields.push_back(NULLPtr);
1566 Fields.push_back(NULLPtr);
1567 }
1568 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1569 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1570 } else {
1571 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1572 }
1573 }
1574 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1575 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1576 llvm::Constant* PropertyListInitFields[] =
1577 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1578
1579 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001580 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001581 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1582 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1583 PropertyListInit, ".objc_property_list");
1584
1585 llvm::Constant *OptionalPropertyArray =
1586 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1587 OptionalProperties.size()) , OptionalProperties);
1588 llvm::Constant* OptionalPropertyListInitFields[] = {
1589 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1590 OptionalPropertyArray };
1591
1592 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001593 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001594 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1595 OptionalPropertyListInit->getType(), false,
1596 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1597 ".objc_property_list");
1598
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001599 // Protocols are objects containing lists of the methods implemented and
1600 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001601 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001602 PtrToInt8Ty,
1603 ProtocolList->getType(),
1604 InstanceMethodList->getType(),
1605 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001606 OptionalInstanceMethodList->getType(),
1607 OptionalClassMethodList->getType(),
1608 PropertyList->getType(),
1609 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001610 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001611 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001612 // The isa pointer must be set to a magic number so the runtime knows it's
1613 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001614 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001615 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1616 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001617 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1618 Elements.push_back(ProtocolList);
1619 Elements.push_back(InstanceMethodList);
1620 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001621 Elements.push_back(OptionalInstanceMethodList);
1622 Elements.push_back(OptionalClassMethodList);
1623 Elements.push_back(PropertyList);
1624 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001625 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001626 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001627 ".objc_protocol"), IdTy);
1628}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001629void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1630 // Collect information about instance methods
1631 llvm::SmallVector<Selector, 1> MethodSels;
1632 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1633
1634 std::vector<llvm::Constant*> Elements;
1635 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1636 const std::string CategoryName = "AnotherHack";
1637 Elements.push_back(MakeConstantString(CategoryName));
1638 Elements.push_back(MakeConstantString(ClassName));
1639 // Instance method list
1640 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1641 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1642 // Class method list
1643 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1644 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1645 // Protocol list
1646 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1647 ExistingProtocols.size());
1648 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1649 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001650 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001651 ProtocolArrayTy,
1652 NULL);
1653 std::vector<llvm::Constant*> ProtocolElements;
1654 for (llvm::StringMapIterator<llvm::Constant*> iter =
1655 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1656 iter != endIter ; iter++) {
1657 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1658 PtrTy);
1659 ProtocolElements.push_back(Ptr);
1660 }
1661 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1662 ProtocolElements);
1663 ProtocolElements.clear();
1664 ProtocolElements.push_back(NULLPtr);
1665 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1666 ExistingProtocols.size()));
1667 ProtocolElements.push_back(ProtocolArray);
1668 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1669 ProtocolElements, ".objc_protocol_list"), PtrTy));
1670 Categories.push_back(llvm::ConstantExpr::getBitCast(
1671 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1672 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1673}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001674
Daniel Dunbar92992502008-08-15 22:20:32 +00001675void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001676 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1677 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001678 // Collect information about instance methods
1679 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1680 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001681 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001682 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001683 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001684 InstanceMethodSels.push_back((*iter)->getSelector());
1685 std::string TypeStr;
1686 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001687 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001688 }
1689
1690 // Collect information about class methods
1691 llvm::SmallVector<Selector, 16> ClassMethodSels;
1692 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001693 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001694 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001695 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001696 ClassMethodSels.push_back((*iter)->getSelector());
1697 std::string TypeStr;
1698 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001699 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001700 }
1701
1702 // Collect the names of referenced protocols
1703 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001704 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1705 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001706 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1707 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001708 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001709
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001710 std::vector<llvm::Constant*> Elements;
1711 Elements.push_back(MakeConstantString(CategoryName));
1712 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001713 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001714 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001715 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001716 false), PtrTy));
1717 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001718 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001719 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001720 PtrTy));
1721 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001722 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001723 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001724 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001725 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001726 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001727}
Daniel Dunbar92992502008-08-15 22:20:32 +00001728
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001729llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1730 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1731 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1732 ASTContext &Context = CGM.getContext();
1733 //
1734 // Property metadata: name, attributes, isSynthesized, setter name, setter
1735 // types, getter name, getter types.
1736 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1737 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1738 PtrToInt8Ty, NULL);
1739 std::vector<llvm::Constant*> Properties;
1740
1741
1742 // Add all of the property methods need adding to the method list and to the
1743 // property metadata list.
1744 for (ObjCImplDecl::propimpl_iterator
1745 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1746 iter != endIter ; iter++) {
1747 std::vector<llvm::Constant*> Fields;
1748 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001749 ObjCPropertyImplDecl *propertyImpl = *iter;
1750 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1751 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001752
1753 Fields.push_back(MakeConstantString(property->getNameAsString()));
1754 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1755 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001756 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001757 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001758 std::string TypeStr;
1759 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1760 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001761 if (isSynthesized) {
1762 InstanceMethodTypes.push_back(TypeEncoding);
1763 InstanceMethodSels.push_back(getter->getSelector());
1764 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001765 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1766 Fields.push_back(TypeEncoding);
1767 } else {
1768 Fields.push_back(NULLPtr);
1769 Fields.push_back(NULLPtr);
1770 }
1771 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001772 std::string TypeStr;
1773 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1774 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001775 if (isSynthesized) {
1776 InstanceMethodTypes.push_back(TypeEncoding);
1777 InstanceMethodSels.push_back(setter->getSelector());
1778 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001779 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1780 Fields.push_back(TypeEncoding);
1781 } else {
1782 Fields.push_back(NULLPtr);
1783 Fields.push_back(NULLPtr);
1784 }
1785 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1786 }
1787 llvm::ArrayType *PropertyArrayTy =
1788 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1789 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1790 Properties);
1791 llvm::Constant* PropertyListInitFields[] =
1792 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1793
1794 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001795 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001796 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1797 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1798 ".objc_property_list");
1799}
1800
Daniel Dunbar92992502008-08-15 22:20:32 +00001801void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1802 ASTContext &Context = CGM.getContext();
1803
1804 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001805 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001806 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001807 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001808 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001809 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001810 EmitClassRef(SuperClassName);
1811 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001812
1813 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001814 ObjCInterfaceDecl *ClassDecl =
1815 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001816 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001817 // Emit the symbol that is used to generate linker errors if this class is
1818 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001819 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001820 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001821 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001822 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001823 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001824 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001825 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001826 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001827 }
Mike Stump11289f42009-09-09 15:08:12 +00001828
Daniel Dunbar12119b92009-05-03 10:46:44 +00001829 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001830 int instanceSize =
1831 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001832
1833 // Collect information about instance variables.
1834 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1835 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1836 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001837
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001838 std::vector<llvm::Constant*> IvarOffsetValues;
1839
Mike Stump11289f42009-09-09 15:08:12 +00001840 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001841 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001842 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1843 // class}. The runtime will then set this to the correct value on load.
1844 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1845 instanceSize = 0 - (instanceSize - superInstanceSize);
1846 }
David Chisnall18cf7372010-04-19 00:45:34 +00001847
1848 // Collect declared and synthesized ivars.
1849 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1850 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1851
1852 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1853 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001854 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001855 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001856 // Get the type encoding for this ivar
1857 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001858 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001859 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001860 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001861 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001862 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001863 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001864 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001865 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001866 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001867 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001868 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1869 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00001870 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001871 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001872 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001873 }
David Chisnalld7972f52011-03-23 16:36:54 +00001874 llvm::GlobalVariable *IvarOffsetArray =
1875 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1876
Daniel Dunbar92992502008-08-15 22:20:32 +00001877
1878 // Collect information about instance methods
1879 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1880 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001881 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001882 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001883 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001884 InstanceMethodSels.push_back((*iter)->getSelector());
1885 std::string TypeStr;
1886 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001887 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001888 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001889
1890 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1891 InstanceMethodTypes);
1892
Daniel Dunbar92992502008-08-15 22:20:32 +00001893
1894 // Collect information about class methods
1895 llvm::SmallVector<Selector, 16> ClassMethodSels;
1896 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001897 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001898 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001899 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001900 ClassMethodSels.push_back((*iter)->getSelector());
1901 std::string TypeStr;
1902 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001903 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001904 }
1905 // Collect the names of referenced protocols
1906 llvm::SmallVector<std::string, 16> Protocols;
1907 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1908 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1909 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001910 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001911
1912
1913
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001914 // Get the superclass pointer.
1915 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001916 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001917 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1918 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001919 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001920 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001921 // Empty vector used to construct empty method lists
1922 llvm::SmallVector<llvm::Constant*, 1> empty;
1923 // Generate the method and instance variable lists
1924 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001925 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001926 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001927 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001928 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1929 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001930 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001931 // we emit a symbol containing the offset for each ivar in the class. This
1932 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1933 // for the legacy ABI, without causing problems. The converse is also
1934 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001935
David Chisnall5778fce2009-08-31 16:41:57 +00001936 // Offset pointer for getting at the correct field in the ivar list when
1937 // setting up the alias. These are: The base address for the global, the
1938 // ivar array (second field), the ivar in this list (set for each ivar), and
1939 // the offset (third field in ivar structure)
1940 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1941 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001942 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001943 llvm::ConstantInt::get(IndexTy, 2) };
1944
David Chisnalle8431a72010-11-03 16:12:44 +00001945
1946 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1947 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00001948 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001949 + IVD->getNameAsString();
1950 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00001951 // Get the correct ivar field
1952 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1953 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00001954 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001955 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1956 if (offset) {
1957 offset->setInitializer(offsetValue);
1958 // If this is the real definition, change its linkage type so that
1959 // different modules will use this one, rather than their private
1960 // copy.
1961 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1962 } else {
1963 // Add a new alias if there isn't one already.
1964 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1965 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1966 }
1967 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001968 //Generate metaclass for class methods
1969 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001970 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001971 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001972
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001973 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001974 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001975 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001976 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001977 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001978 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1979 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001980
1981 // Resolve the class aliases, if they exist.
1982 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001983 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001984 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001985 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001986 ClassPtrAlias = 0;
1987 }
1988 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001989 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001990 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001991 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001992 MetaClassPtrAlias = 0;
1993 }
1994
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001995 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001996 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001997 Classes.push_back(ClassStruct);
1998}
1999
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002000
Mike Stump11289f42009-09-09 15:08:12 +00002001llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002002 // Only emit an ObjC load function if no Objective-C stuff has been called
2003 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002004 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002005 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002006
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002007 // Add all referenced protocols to a category.
2008 GenerateProtocolHolderCategory();
2009
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002010 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2011 SelectorTy->getElementType());
2012 const llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002013 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00002014 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
2015 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002016 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002017 }
2018
Eli Friedman412c6682008-06-01 16:00:02 +00002019 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002020 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00002021 TheModule.addTypeName(".objc_id", IdTy);
2022 TheModule.addTypeName(".objc_imp", IMPTy);
2023
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002024 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002025 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002026 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002027 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002028 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002029 ConstantStrings.size() + 1);
2030 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002031
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002032 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002033
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002034 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002035
David Chisnall5778fce2009-08-31 16:41:57 +00002036 Elements.push_back(MakeConstantString(StringClass,
2037 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002038 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002039 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002040 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00002041 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002042 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002043 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002044 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002045 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002046 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002047 Elements.clear();
2048 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002049 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002050 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002051 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002052 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002053 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002054 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002055 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00002056 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00002057 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002058 llvm::Type::getInt16Ty(VMContext),
2059 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002060 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002061
2062 Elements.clear();
2063 // Pointer to an array of selectors used in this module.
2064 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002065 std::vector<llvm::GlobalAlias*> SelectorAliases;
2066 for (SelectorMap::iterator iter = SelectorTable.begin(),
2067 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2068
2069 std::string SelNameStr = iter->first.getAsString();
2070 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2071
2072 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2073 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2074 e = Types.end() ; i!=e ; i++) {
2075
2076 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2077 if (!i->first.empty())
2078 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2079
2080 Elements.push_back(SelName);
2081 Elements.push_back(SelectorTypeEncoding);
2082 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2083 Elements.clear();
2084
2085 // Store the selector alias for later replacement
2086 SelectorAliases.push_back(i->second);
2087 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002088 }
David Chisnalld7972f52011-03-23 16:36:54 +00002089 unsigned SelectorCount = Selectors.size();
2090 // NULL-terminate the selector list. This should not actually be required,
2091 // because the selector list has a length field. Unfortunately, the GCC
2092 // runtime decides to ignore the length field and expects a NULL terminator,
2093 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002094 Elements.push_back(NULLPtr);
2095 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002096 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002097 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002098
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002099 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002100 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2101 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002102 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002103 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002104 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002105
2106 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002107 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2108
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002109 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00002110 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2111 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002112 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2113 Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002114 // If selectors are defined as an opaque type, cast the pointer to this
2115 // type.
David Chisnall76803412011-03-23 22:52:06 +00002116 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002117 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2118 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002119 }
David Chisnalld7972f52011-03-23 16:36:54 +00002120
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002121 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002122 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002123 Classes.size()));
2124 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002125 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002126 Categories.size()));
2127 // Create an array of classes, then categories, then static object instances
2128 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2129 // NULL-terminated list of static object instances (mainly constant strings)
2130 Classes.push_back(Statics);
2131 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002132 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002133 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002134 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002135 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2136
2137 // The symbol table is contained in a module which has some version-checking
2138 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00002139 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002140 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2141 (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) ? NULL : IntTy,
2142 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002143 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002144 // Runtime version, used for ABI compatibility checking.
2145 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002146 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002147 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002148 Elements.push_back(
2149 llvm::ConstantInt::get(LongTy,
2150 td.getTypeSizeInBits(ModuleTy) /
2151 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002152
2153 // The path to the source file where this module was declared
2154 SourceManager &SM = CGM.getContext().getSourceManager();
2155 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2156 std::string path =
2157 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2158 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002159 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002160
2161 switch (CGM.getLangOptions().getGCMode()) {
2162 case LangOptions::GCOnly:
2163 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2164 case LangOptions::NonGC:
2165 break;
2166 case LangOptions::HybridGC:
2167 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2168 }
2169
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002170 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2171
2172 // Create the load function calling the runtime entry point with the module
2173 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002174 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002175 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002176 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2177 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002178 llvm::BasicBlock *EntryBB =
2179 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002180 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002181 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002182
2183 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002184 llvm::PointerType::getUnqual(ModuleTy));
2185 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00002186 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002187 Builder.CreateCall(Register, Module);
2188 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002189
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002190 return LoadFunction;
2191}
Daniel Dunbar92992502008-08-15 22:20:32 +00002192
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002193llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002194 const ObjCContainerDecl *CD) {
2195 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002196 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00002197 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2198 llvm::StringRef ClassName = CD->getName();
2199 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002200 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002201
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002202 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00002203 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002204 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002205 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2206 MethodName, isClassMethod);
2207
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002208 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002209 = llvm::Function::Create(MethodTy,
2210 llvm::GlobalValue::InternalLinkage,
2211 FunctionName,
2212 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002213 return Method;
2214}
2215
David Chisnall3fe89562011-05-23 22:33:28 +00002216llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002217 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002218}
2219
David Chisnall3fe89562011-05-23 22:33:28 +00002220llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002221 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002222}
2223
David Chisnall3fe89562011-05-23 22:33:28 +00002224llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002225 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002226}
David Chisnall3fe89562011-05-23 22:33:28 +00002227llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002228 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002229}
2230
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002231llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002232 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002233}
2234
David Chisnalld7972f52011-03-23 16:36:54 +00002235void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002236 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002237 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002238}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002239
David Chisnall3a509cd2009-12-24 02:26:34 +00002240
David Chisnalld7972f52011-03-23 16:36:54 +00002241void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002242 const ObjCAtTryStmt &S) {
2243 // Unlike the Apple non-fragile runtimes, which also uses
2244 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2245 // EH support isn't a veneer over C++ EH. Instead, exception
2246 // objects are created by __objc_exception_throw and destroyed by
2247 // the personality function; this avoids the need for bracketing
2248 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2249 // (or even _Unwind_DeleteException), but probably doesn't
2250 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002251 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002252 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002253 // exception handler.
2254 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2255 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002256}
2257
David Chisnalld7972f52011-03-23 16:36:54 +00002258void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002259 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002260 llvm::Value *ExceptionAsObject;
2261
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002262 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2263 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002264 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002265 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002266 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002267 "Unexpected rethrow outside @catch block.");
2268 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2269 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002270 ExceptionAsObject =
2271 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002272
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002273 // Note: This may have to be an invoke, if we want to support constructs like:
2274 // @try {
2275 // @throw(obj);
2276 // }
2277 // @catch(id) ...
2278 //
2279 // This is effectively turning @throw into an incredibly-expensive goto, but
2280 // it may happen as a result of inlining followed by missed optimizations, or
2281 // as a result of stupidity.
2282 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2283 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002284 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002285 CGF.Builder.CreateUnreachable();
2286 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002287 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002288 &ExceptionAsObject+1);
2289 }
2290 // Clear the insertion point to indicate we are in unreachable code.
2291 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002292}
2293
David Chisnalld7972f52011-03-23 16:36:54 +00002294llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002295 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002296 CGBuilderTy B = CGF.Builder;
2297 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2298 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002299}
2300
David Chisnalld7972f52011-03-23 16:36:54 +00002301void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002302 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002303 CGBuilderTy B = CGF.Builder;
2304 src = EnforceType(B, src, IdTy);
2305 dst = EnforceType(B, dst, PtrToIdTy);
2306 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002307}
2308
David Chisnalld7972f52011-03-23 16:36:54 +00002309void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002310 llvm::Value *src, llvm::Value *dst,
2311 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002312 CGBuilderTy B = CGF.Builder;
2313 src = EnforceType(B, src, IdTy);
2314 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002315 if (!threadlocal)
2316 B.CreateCall2(GlobalAssignFn, src, dst);
2317 else
2318 // FIXME. Add threadloca assign API
2319 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002320}
2321
David Chisnalld7972f52011-03-23 16:36:54 +00002322void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002323 llvm::Value *src, llvm::Value *dst,
2324 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002325 CGBuilderTy B = CGF.Builder;
2326 src = EnforceType(B, src, IdTy);
2327 dst = EnforceType(B, dst, PtrToIdTy);
2328 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002329}
2330
David Chisnalld7972f52011-03-23 16:36:54 +00002331void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002332 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002333 CGBuilderTy B = CGF.Builder;
2334 src = EnforceType(B, src, IdTy);
2335 dst = EnforceType(B, dst, PtrToIdTy);
2336 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002337}
2338
David Chisnalld7972f52011-03-23 16:36:54 +00002339void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002340 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002341 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002342 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002343 CGBuilderTy B = CGF.Builder;
2344 DestPtr = EnforceType(B, DestPtr, IdTy);
2345 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2346
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002347 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002348}
2349
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002350llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2351 const ObjCInterfaceDecl *ID,
2352 const ObjCIvarDecl *Ivar) {
2353 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2354 + '.' + Ivar->getNameAsString();
2355 // Emit the variable and initialize it with what we think the correct value
2356 // is. This allows code compiled with non-fragile ivars to work correctly
2357 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002358 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2359 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002360 // This will cause a run-time crash if we accidentally use it. A value of
2361 // 0 would seem more sensible, but will silently overwrite the isa pointer
2362 // causing a great deal of confusion.
2363 uint64_t Offset = -1;
2364 // We can't call ComputeIvarBaseOffset() here if we have the
2365 // implementation, because it will create an invalid ASTRecordLayout object
2366 // that we are then stuck with forever, so we only initialize the ivar
2367 // offset variable with a guess if we only have the interface. The
2368 // initializer will be reset later anyway, when we are generating the class
2369 // description.
2370 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002371 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002372 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2373
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002374 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002375 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002376 // Don't emit the guess in non-PIC code because the linker will not be able
2377 // to replace it with the real version for a library. In non-PIC code you
2378 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002379 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002380 if (CGM.getLangOptions().PICLevel) {
2381 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2382 llvm::Type::getInt32Ty(VMContext), false,
2383 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2384 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2385 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2386 IvarOffsetGV, Name);
2387 } else {
2388 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002389 llvm::Type::getInt32PtrTy(VMContext), false,
2390 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002391 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002392 }
David Chisnall5778fce2009-08-31 16:41:57 +00002393 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002394}
2395
David Chisnalld7972f52011-03-23 16:36:54 +00002396LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002397 QualType ObjectTy,
2398 llvm::Value *BaseValue,
2399 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002400 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002401 const ObjCInterfaceDecl *ID =
2402 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002403 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2404 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002405}
Mike Stumpdd93a192009-07-31 21:31:32 +00002406
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002407static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2408 const ObjCInterfaceDecl *OID,
2409 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002410 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002411 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002412 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2413 if (OIVD == Ivars[k])
2414 return OID;
2415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002417 // Otherwise check in the super class.
2418 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2419 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002420
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002421 return 0;
2422}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002423
David Chisnalld7972f52011-03-23 16:36:54 +00002424llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002425 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002426 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002427 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002428 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002429 return CGF.Builder.CreateZExtOrBitCast(
2430 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2431 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2432 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002433 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002434 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002435 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002436}
2437
David Chisnalld7972f52011-03-23 16:36:54 +00002438CGObjCRuntime *
2439clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2440 if (CGM.getLangOptions().ObjCNonFragileABI)
2441 return new CGObjCGNUstep(CGM);
2442 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002443}