blob: ba38bfa706cb0bc39e9cc61a5ed01915b8af1f67 [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
Chris Lattner0e62c1c2011-07-23 10:55:15 +000039#include <cstdarg>
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 +000044
Chris Lattnerb7256cd2008-03-01 08:50:34 +000045
Chris Lattnerb7256cd2008-03-01 08:50:34 +000046namespace {
David Chisnall34d00052011-03-26 11:48:37 +000047/// Class that lazily initialises the runtime function. Avoids inserting the
48/// types and the function declaration into a module if they're not used, and
49/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000050class LazyRuntimeFunction {
51 CodeGenModule *CGM;
Chris Lattnera5f58b02011-07-09 17:41:47 +000052 std::vector<llvm::Type*> ArgTys;
David Chisnalld7972f52011-03-23 16:36:54 +000053 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000054 llvm::Constant *Function;
David Chisnalld7972f52011-03-23 16:36:54 +000055 public:
David Chisnall34d00052011-03-26 11:48:37 +000056 /// Constructor leaves this class uninitialized, because it is intended to
57 /// be used as a field in another class and not all of the types that are
58 /// used as arguments will necessarily be available at construction time.
David Chisnalld7972f52011-03-23 16:36:54 +000059 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60
David Chisnall34d00052011-03-26 11:48:37 +000061 /// Initialises the lazy function with the name, return type, and the types
62 /// of the arguments.
David Chisnalld7972f52011-03-23 16:36:54 +000063 END_WITH_NULL
64 void init(CodeGenModule *Mod, const char *name,
Chris Lattnera5f58b02011-07-09 17:41:47 +000065 llvm::Type *RetTy, ...) {
David Chisnalld7972f52011-03-23 16:36:54 +000066 CGM =Mod;
67 FunctionName = name;
68 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000069 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000070 va_list Args;
71 va_start(Args, RetTy);
Chris Lattnera5f58b02011-07-09 17:41:47 +000072 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnalld7972f52011-03-23 16:36:54 +000073 ArgTys.push_back(ArgTy);
74 va_end(Args);
75 // Push the return type on at the end so we can pop it off easily
76 ArgTys.push_back(RetTy);
77 }
David Chisnall34d00052011-03-26 11:48:37 +000078 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 /// LLVM constant.
David Chisnall3fe89562011-05-23 22:33:28 +000080 operator llvm::Constant*() {
David Chisnalld7972f52011-03-23 16:36:54 +000081 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000082 if (0 == FunctionName) return 0;
83 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2192fe52011-07-18 04:24:23 +000084 llvm::Type *RetTy = ArgTys.back();
David Chisnalld7972f52011-03-23 16:36:54 +000085 ArgTys.pop_back();
86 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87 Function =
David Chisnall3fe89562011-05-23 22:33:28 +000088 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000089 // We won't need to use the types again, so we may as well clean up the
90 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +000091 ArgTys.resize(0);
92 }
93 return Function;
94 }
David Chisnall3fe89562011-05-23 22:33:28 +000095 operator llvm::Function*() {
David Chisnallb85775c2011-05-23 23:15:11 +000096 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall3fe89562011-05-23 22:33:28 +000097 }
David Chisnallb85775c2011-05-23 23:15:11 +000098
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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000116 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 Lattnera5f58b02011-07-09 17:41:47 +0000120 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
Chris Lattner2192fe52011-07-18 04:24:23 +0000123 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 Lattnera5f58b02011-07-09 17:41:47 +0000126 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.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000132 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 Lattnera5f58b02011-07-09 17:41:47 +0000137 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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000140 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 Lattnera5f58b02011-07-09 17:41:47 +0000145 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 Lattnera5f58b02011-07-09 17:41:47 +0000149 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...
Jay Foad7c57be32011-07-11 09:56:20 +0000153 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000154 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000155 llvm::IntegerType *SizeTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000157 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 Lattner2192fe52011-07-18 04:24:23 +0000160 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000161 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000162 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());
Jay Foaded8db7d2011-07-21 14:31:17 +0000173 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000174 }
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 }
Jay Foaded8db7d2011-07-21 14:31:17 +0000188 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000189 }
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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000193 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000194 std::vector<llvm::Constant*> &V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000195 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000196 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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000205 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000206 std::vector<llvm::Constant*> &V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000207 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000208 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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000216 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000217 std::vector<llvm::Constant*> &V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000218 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000219 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.
Chris Lattner2192fe52011-07-18 04:24:23 +0000227 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnall76803412011-03-23 22:52:06 +0000228 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.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000270 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000271 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(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000334 const SmallVectorImpl<llvm::Constant *> &IvarNames,
335 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
336 const 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.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
343 const StringRef &CategoryName,
344 const SmallVectorImpl<Selector> &MethodSels,
345 const 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,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 SmallVectorImpl<Selector> &InstanceMethodSels,
355 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(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000359 const 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(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000382 const SmallVectorImpl<llvm::Constant *> &MethodNames,
383 const 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 Chisnall920e83b2011-06-29 13:16:41 +0000394 /// Emits a pointer to the named class
David Chisnall08d67332011-06-30 10:14:37 +0000395 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
396 bool isWeak);
David Chisnall76803412011-03-23 22:52:06 +0000397protected:
David Chisnall34d00052011-03-26 11:48:37 +0000398 /// Looks up the method for sending a message to the specified object. This
399 /// mechanism differs between the GCC and GNU runtimes, so this method must be
400 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000401 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
402 llvm::Value *&Receiver,
403 llvm::Value *cmd,
404 llvm::MDNode *node) = 0;
David Chisnall34d00052011-03-26 11:48:37 +0000405 /// Looks up the method for sending a message to a superclass. This mechanism
406 /// differs between the GCC and GNU runtimes, so this method must be
407 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000408 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
409 llvm::Value *ObjCSuper,
410 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000411public:
David Chisnalld7972f52011-03-23 16:36:54 +0000412 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
413 unsigned protocolClassVersion);
414
David Chisnall481e3a82010-01-23 02:40:42 +0000415 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000416
417 virtual RValue
418 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000419 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000420 QualType ResultType,
421 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000422 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000423 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000424 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000425 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000426 virtual RValue
427 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000428 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000429 QualType ResultType,
430 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000431 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000432 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000433 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000434 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000435 const CallArgList &CallArgs,
436 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000437 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000438 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000439 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
440 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000441 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
442 *Method);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000443 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000444
445 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000446 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000447 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
448 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000449 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000450 const ObjCProtocolDecl *PD);
451 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000452 virtual llvm::Function *ModuleInitFunction();
David Chisnall3fe89562011-05-23 22:33:28 +0000453 virtual llvm::Constant *GetPropertyGetFunction();
454 virtual llvm::Constant *GetPropertySetFunction();
455 virtual llvm::Constant *GetSetStructFunction();
456 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000457 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000458
David Chisnalld7972f52011-03-23 16:36:54 +0000459 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000460 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000461 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000462 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000463 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000464 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000465 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000466 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000467 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000468 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000469 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000470 llvm::Value *src, llvm::Value *dest,
471 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000472 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000473 llvm::Value *src, llvm::Value *dest,
474 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000475 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000476 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000477 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000478 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000479 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000480 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000481 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000482 QualType ObjectTy,
483 llvm::Value *BaseValue,
484 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000485 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000486 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000487 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000488 const ObjCIvarDecl *Ivar);
David Chisnall920e83b2011-06-29 13:16:41 +0000489 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnalld7972f52011-03-23 16:36:54 +0000490 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000491 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000492 return NULLPtr;
493 }
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000494
495 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
496 return 0;
497 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000498};
David Chisnall34d00052011-03-26 11:48:37 +0000499/// Class representing the legacy GCC Objective-C ABI. This is the default when
500/// -fobjc-nonfragile-abi is not specified.
501///
502/// The GCC ABI target actually generates code that is approximately compatible
503/// with the new GNUstep runtime ABI, but refrains from using any features that
504/// would not work with the GCC runtime. For example, clang always generates
505/// the extended form of the class structure, and the extra fields are simply
506/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000507class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000508 /// The GCC ABI message lookup function. Returns an IMP pointing to the
509 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000510 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000511 /// The GCC ABI superclass message lookup function. Takes a pointer to a
512 /// structure describing the receiver and the class, and a selector as
513 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000514 LazyRuntimeFunction MsgLookupSuperFn;
515protected:
516 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
517 llvm::Value *&Receiver,
518 llvm::Value *cmd,
519 llvm::MDNode *node) {
520 CGBuilderTy &Builder = CGF.Builder;
521 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
522 EnforceType(Builder, Receiver, IdTy),
523 EnforceType(Builder, cmd, SelectorTy));
524 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
525 return imp;
526 }
527 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
528 llvm::Value *ObjCSuper,
529 llvm::Value *cmd) {
530 CGBuilderTy &Builder = CGF.Builder;
531 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
532 PtrToObjCSuperTy), cmd};
Jay Foad5bd375a2011-07-15 08:37:34 +0000533 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000534 }
David Chisnalld7972f52011-03-23 16:36:54 +0000535 public:
David Chisnall76803412011-03-23 22:52:06 +0000536 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
537 // IMP objc_msg_lookup(id, SEL);
538 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
539 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
540 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
541 PtrToObjCSuperTy, SelectorTy, NULL);
542 }
David Chisnalld7972f52011-03-23 16:36:54 +0000543};
David Chisnall34d00052011-03-26 11:48:37 +0000544/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000545class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000546 /// The slot lookup function. Returns a pointer to a cacheable structure
547 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000548 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000549 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
550 /// a structure describing the receiver and the class, and a selector as
551 /// arguments. Returns the slot for the corresponding method. Superclass
552 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000553 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall34d00052011-03-26 11:48:37 +0000554 /// Type of an slot structure pointer. This is returned by the various
555 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000556 llvm::Type *SlotTy;
557 protected:
558 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
559 llvm::Value *&Receiver,
560 llvm::Value *cmd,
561 llvm::MDNode *node) {
562 CGBuilderTy &Builder = CGF.Builder;
563 llvm::Function *LookupFn = SlotLookupFn;
564
565 // Store the receiver on the stack so that we can reload it later
566 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
567 Builder.CreateStore(Receiver, ReceiverPtr);
568
569 llvm::Value *self;
570
571 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
572 self = CGF.LoadObjCSelf();
573 } else {
574 self = llvm::ConstantPointerNull::get(IdTy);
575 }
576
577 // The lookup function is guaranteed not to capture the receiver pointer.
578 LookupFn->setDoesNotCapture(1);
579
580 llvm::CallInst *slot =
581 Builder.CreateCall3(LookupFn,
582 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
583 EnforceType(Builder, cmd, SelectorTy),
584 EnforceType(Builder, self, IdTy));
585 slot->setOnlyReadsMemory();
586 slot->setMetadata(msgSendMDKind, node);
587
588 // Load the imp from the slot
589 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
590
591 // The lookup function may have changed the receiver, so make sure we use
592 // the new one.
593 Receiver = Builder.CreateLoad(ReceiverPtr, true);
594 return imp;
595 }
596 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
597 llvm::Value *ObjCSuper,
598 llvm::Value *cmd) {
599 CGBuilderTy &Builder = CGF.Builder;
600 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
601
Jay Foad5bd375a2011-07-15 08:37:34 +0000602 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000603 slot->setOnlyReadsMemory();
604
605 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
606 }
David Chisnalld7972f52011-03-23 16:36:54 +0000607 public:
David Chisnall76803412011-03-23 22:52:06 +0000608 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner845511f2011-06-18 22:49:11 +0000609 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnall76803412011-03-23 22:52:06 +0000610 PtrTy, PtrTy, IntTy, IMPTy, NULL);
611 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
612 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
613 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
614 SelectorTy, IdTy, NULL);
615 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
616 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
617 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000618 // If we're in ObjC++ mode, then we want to make
619 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000620 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000621 // void *__cxa_begin_catch(void *e)
622 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
623 // void __cxa_end_catch(void)
624 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
625 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnallec343e82011-04-05 17:15:18 +0000626 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000627 }
David Chisnall76803412011-03-23 22:52:06 +0000628 }
David Chisnalld7972f52011-03-23 16:36:54 +0000629};
630
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000631} // end anonymous namespace
632
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000633
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000634/// Emits a reference to a dummy variable which is emitted with each class.
635/// This ensures that a linker error will be generated when trying to link
636/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000637void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000638 std::string symbolRef = "__objc_class_ref_" + className;
639 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000640 if (TheModule.getGlobalVariable(symbolRef))
641 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000642 std::string symbolName = "__objc_class_name_" + className;
643 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
644 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000645 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
646 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000647 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000648 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000649 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000650}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000651
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000652static std::string SymbolNameForMethod(const StringRef &ClassName,
653 const StringRef &CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000654 bool isClassMethod) {
655 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000656 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
657 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000658 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000659 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000660}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000661
David Chisnalld7972f52011-03-23 16:36:54 +0000662CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
663 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000664 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
665 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
666 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000667
668 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
669
David Chisnalld7972f52011-03-23 16:36:54 +0000670 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000671 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000672 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000673 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000674 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000675 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000676 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000677 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000678 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000679 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000680
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000681 Int8Ty = llvm::Type::getInt8Ty(VMContext);
682 // C string type. Used in lots of places.
683 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
684
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000685 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000686 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000687 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000688 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000689 QualType selTy = CGM.getContext().getObjCSelType();
690 if (QualType() == selTy) {
691 SelectorTy = PtrToInt8Ty;
692 } else {
693 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
694 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000695
Owen Anderson9793f0e2009-07-29 22:16:19 +0000696 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000697 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattner4bd55962008-03-30 23:03:07 +0000699 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000700 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
701 ASTIdTy = CanQualType();
702 if (UnqualIdTy != QualType()) {
703 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000704 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000705 } else {
706 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000707 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000708 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattner845511f2011-06-18 22:49:11 +0000710 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnall76803412011-03-23 22:52:06 +0000711 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
712
Chris Lattnera5f58b02011-07-09 17:41:47 +0000713 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000714
715 // void objc_exception_throw(id);
716 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000717 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000718 // int objc_sync_enter(id);
719 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
720 // int objc_sync_exit(id);
721 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
722
723 // void objc_enumerationMutation (id)
724 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
725 IdTy, NULL);
726
727 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
728 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
729 PtrDiffTy, BoolTy, NULL);
730 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
731 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
732 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
733 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
734 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
735 PtrDiffTy, BoolTy, BoolTy, NULL);
736 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
737 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
738 PtrDiffTy, BoolTy, BoolTy, NULL);
739
Chris Lattner4bd55962008-03-30 23:03:07 +0000740 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000741 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000742 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
743 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000744
David Chisnalla918b882011-07-07 11:22:31 +0000745 const LangOptions &Opts = CGM.getLangOptions();
746 if ((Opts.getGCMode() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
747 RuntimeVersion = 10;
748
David Chisnalld3858d62011-03-25 11:57:33 +0000749 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnalla918b882011-07-07 11:22:31 +0000750 if (Opts.getGCMode() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000751 // This is a bit of an hack. We should sort this out by having a proper
752 // CGObjCGNUstep subclass for GC, but we may want to really support the old
753 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000754 // Get selectors needed in GC mode
755 RetainSel = GetNullarySelector("retain", CGM.getContext());
756 ReleaseSel = GetNullarySelector("release", CGM.getContext());
757 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
758
759 // Get functions needed in GC mode
760
761 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000762 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
763 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000764 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000765 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
766 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000767 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000768 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
769 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000770 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000771 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000772 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000773 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000774 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000775 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
776 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000777 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000778}
Mike Stumpdd93a192009-07-31 21:31:32 +0000779
David Chisnall920e83b2011-06-29 13:16:41 +0000780llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnall08d67332011-06-30 10:14:37 +0000781 const std::string &Name,
782 bool isWeak) {
David Chisnall920e83b2011-06-29 13:16:41 +0000783 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnalldf349172010-01-08 00:14:31 +0000784 // With the incompatible ABI, this will need to be replaced with a direct
785 // reference to the class symbol. For the compatible nonfragile ABI we are
786 // still performing this lookup at run time but emitting the symbol for the
787 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +0000788 //
789 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
790 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +0000791 if (!isWeak)
792 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000793 ClassName = Builder.CreateStructGEP(ClassName, 0);
794
Chris Lattnera5f58b02011-07-09 17:41:47 +0000795 llvm::Type *ArgTys[] = { PtrToInt8Ty };
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000796 llvm::Constant *ClassLookupFn =
Chris Lattnera5f58b02011-07-09 17:41:47 +0000797 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, ArgTys, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000798 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000799 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000800}
801
David Chisnall920e83b2011-06-29 13:16:41 +0000802// This has to perform the lookup every time, since posing and related
803// techniques can modify the name -> class mapping.
804llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
805 const ObjCInterfaceDecl *OID) {
David Chisnall08d67332011-06-30 10:14:37 +0000806 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +0000807}
808llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnall08d67332011-06-30 10:14:37 +0000809 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +0000810}
811
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000812llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000813 const std::string &TypeEncoding, bool lval) {
814
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000815 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnalld7972f52011-03-23 16:36:54 +0000816 llvm::GlobalAlias *SelValue = 0;
817
818
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000819 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +0000820 e = Types.end() ; i!=e ; i++) {
821 if (i->first == TypeEncoding) {
822 SelValue = i->second;
823 break;
824 }
825 }
826 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000827 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000828 llvm::GlobalValue::PrivateLinkage,
829 ".objc_selector_"+Sel.getAsString(), NULL,
830 &TheModule);
831 Types.push_back(TypedSelector(TypeEncoding, SelValue));
832 }
833
David Chisnall76803412011-03-23 22:52:06 +0000834 if (lval) {
835 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
836 Builder.CreateStore(SelValue, tmp);
837 return tmp;
838 }
839 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000840}
841
842llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
843 bool lval) {
844 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000845}
846
Daniel Dunbar45858d22010-02-03 20:11:42 +0000847llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000848 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000849 std::string SelTypes;
850 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000851 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000852}
853
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000854llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000855 if (!CGM.getLangOptions().CPlusPlus) {
856 if (T->isObjCIdType()
857 || T->isObjCQualifiedIdType()) {
858 // With the old ABI, there was only one kind of catchall, which broke
859 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
860 // a pointer indicating object catchalls, and NULL to indicate real
861 // catchalls
862 if (CGM.getLangOptions().ObjCNonFragileABI) {
863 return MakeConstantString("@id");
864 } else {
865 return 0;
866 }
867 }
868
869 // All other types should be Objective-C interface pointer types.
870 const ObjCObjectPointerType *OPT =
871 T->getAs<ObjCObjectPointerType>();
872 assert(OPT && "Invalid @catch type.");
873 const ObjCInterfaceDecl *IDecl =
874 OPT->getObjectType()->getInterface();
875 assert(IDecl && "Invalid @catch type.");
876 return MakeConstantString(IDecl->getIdentifier()->getName());
877 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000878 // For Objective-C++, we want to provide the ability to catch both C++ and
879 // Objective-C objects in the same function.
880
881 // There's a particular fixed type info for 'id'.
882 if (T->isObjCIdType() ||
883 T->isObjCQualifiedIdType()) {
884 llvm::Constant *IDEHType =
885 CGM.getModule().getGlobalVariable("__objc_id_type_info");
886 if (!IDEHType)
887 IDEHType =
888 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
889 false,
890 llvm::GlobalValue::ExternalLinkage,
891 0, "__objc_id_type_info");
892 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
893 }
894
895 const ObjCObjectPointerType *PT =
896 T->getAs<ObjCObjectPointerType>();
897 assert(PT && "Invalid @catch type.");
898 const ObjCInterfaceType *IT = PT->getInterfaceType();
899 assert(IT && "Invalid @catch type.");
900 std::string className = IT->getDecl()->getIdentifier()->getName();
901
902 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
903
904 // Return the existing typeinfo if it exists
905 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
906 if (typeinfo) return typeinfo;
907
908 // Otherwise create it.
909
910 // vtable for gnustep::libobjc::__objc_class_type_info
911 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
912 // platform's name mangling.
913 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
914 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
915 if (!Vtable) {
916 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
917 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
918 }
919 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foaded8db7d2011-07-21 14:31:17 +0000920 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnalle1d2584d2011-03-20 21:35:39 +0000921 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
922
923 llvm::Constant *typeName =
924 ExportUniqueString(className, "__objc_eh_typename_");
925
926 std::vector<llvm::Constant*> fields;
927 fields.push_back(Vtable);
928 fields.push_back(typeName);
929 llvm::Constant *TI =
Chris Lattner845511f2011-06-18 22:49:11 +0000930 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnalle1d2584d2011-03-20 21:35:39 +0000931 NULL), fields, "__objc_eh_typeinfo_" + className,
932 llvm::GlobalValue::LinkOnceODRLinkage);
933 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000934}
935
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000936/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000937llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000938
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000939 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000940
David Chisnall358e7512010-01-27 12:49:23 +0000941 // Look for an existing one
942 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
943 if (old != ObjCStrings.end())
944 return old->getValue();
945
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000946 std::vector<llvm::Constant*> Ivars;
947 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000948 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000949 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000950 llvm::Constant *ObjCStr = MakeGlobal(
Chris Lattner845511f2011-06-18 22:49:11 +0000951 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000952 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000953 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
954 ObjCStrings[Str] = ObjCStr;
955 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000956 return ObjCStr;
957}
958
959///Generates a message send where the super is the receiver. This is a message
960///send to self with special delivery semantics indicating which class's method
961///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000962RValue
963CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000964 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000965 QualType ResultType,
966 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000967 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000968 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000969 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000970 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000971 const CallArgList &CallArgs,
972 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +0000973 CGBuilderTy &Builder = CGF.Builder;
David Chisnall1254f6e2011-05-23 23:13:25 +0000974 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000975 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +0000976 return RValue::get(EnforceType(Builder, Receiver,
977 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000978 }
979 if (Sel == ReleaseSel) {
980 return RValue::get(0);
981 }
982 }
David Chisnallea529a42010-05-01 12:37:16 +0000983
David Chisnallea529a42010-05-01 12:37:16 +0000984 llvm::Value *cmd = GetSelector(Builder, Sel);
985
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000986
987 CallArgList ActualArgs;
988
Eli Friedman43dca6a2011-05-02 17:57:46 +0000989 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
990 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +0000991 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000992
993 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000994 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000995 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000996
Daniel Dunbar566421c2009-05-04 15:31:17 +0000997 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000998 if (isCategoryImpl) {
999 llvm::Constant *classLookupFunction = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001000 if (IsClassMessage) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001001 llvm::Type *ArgTys[] = { PtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +00001002 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera5f58b02011-07-09 17:41:47 +00001003 IdTy, ArgTys, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001004 } else {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001005 llvm::Type *ArgTys[] = { PtrTy };
Owen Anderson9793f0e2009-07-29 22:16:19 +00001006 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera5f58b02011-07-09 17:41:47 +00001007 IdTy, ArgTys, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001008 }
David Chisnallea529a42010-05-01 12:37:16 +00001009 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001010 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001011 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001012 // Set up global aliases for the metaclass or class pointer if they do not
1013 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001014 // pointers to the class and metaclass structure created for the runtime
1015 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001016 // super_class pointer from either the class or metaclass structure.
1017 if (IsClassMessage) {
1018 if (!MetaClassPtrAlias) {
1019 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1020 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1021 Class->getNameAsString(), NULL, &TheModule);
1022 }
1023 ReceiverClass = MetaClassPtrAlias;
1024 } else {
1025 if (!ClassPtrAlias) {
1026 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1027 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1028 Class->getNameAsString(), NULL, &TheModule);
1029 }
1030 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001031 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001032 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001033 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001034 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001035 llvm::PointerType::getUnqual(
Chris Lattner845511f2011-06-18 22:49:11 +00001036 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001037 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001038 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001039 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001040 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001041 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001042 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson758428f2009-08-05 23:18:46 +00001043 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001044 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001045
David Chisnallea529a42010-05-01 12:37:16 +00001046 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1047 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001048
David Chisnall76803412011-03-23 22:52:06 +00001049 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001050 llvm::FunctionType *impType =
David Chisnall76803412011-03-23 22:52:06 +00001051 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1052
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001053 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001054 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1055 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001056
David Chisnall9eecafa2010-05-01 11:15:56 +00001057 llvm::Value *impMD[] = {
1058 llvm::MDString::get(VMContext, Sel.getAsString()),
1059 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1060 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1061 };
Jay Foadea324f12011-04-21 19:59:12 +00001062 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001063
David Chisnallff5f88c2010-05-02 13:41:58 +00001064 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001065 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001066 0, &call);
1067 call->setMetadata(msgSendMDKind, node);
1068 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001069}
1070
Mike Stump11289f42009-09-09 15:08:12 +00001071/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001072RValue
1073CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001074 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001075 QualType ResultType,
1076 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001077 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001078 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001079 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001080 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001081 CGBuilderTy &Builder = CGF.Builder;
1082
David Chisnall75afda62010-04-27 15:08:48 +00001083 // Strip out message sends to retain / release in GC mode
David Chisnall1254f6e2011-05-23 23:13:25 +00001084 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001085 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001086 return RValue::get(EnforceType(Builder, Receiver,
1087 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001088 }
1089 if (Sel == ReleaseSel) {
1090 return RValue::get(0);
1091 }
1092 }
David Chisnall75afda62010-04-27 15:08:48 +00001093
David Chisnall75afda62010-04-27 15:08:48 +00001094 // If the return type is something that goes in an integer register, the
1095 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1096 // ourselves.
1097 //
1098 // The language spec says the result of this kind of message send is
1099 // undefined, but lots of people seem to have forgotten to read that
1100 // paragraph and insist on sending messages to nil that have structure
1101 // returns. With GCC, this generates a random return value (whatever happens
1102 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001103 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1104 // the stack.
1105 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1106 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001107
1108 llvm::BasicBlock *startBB = 0;
1109 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001110 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001111
1112 if (!isPointerSizedReturn) {
1113 startBB = Builder.GetInsertBlock();
1114 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001115 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001116
1117 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1118 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001119 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001120 CGF.EmitBlock(messageBB);
1121 }
1122
David Chisnall9f57c292009-08-17 16:35:33 +00001123 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001124 llvm::Value *cmd;
1125 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001126 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001127 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001128 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001129 cmd = EnforceType(Builder, cmd, SelectorTy);
1130 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001131
David Chisnall76803412011-03-23 22:52:06 +00001132 llvm::Value *impMD[] = {
1133 llvm::MDString::get(VMContext, Sel.getAsString()),
1134 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1135 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1136 };
Jay Foadea324f12011-04-21 19:59:12 +00001137 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001138
1139 // Get the IMP to call
1140 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1141
1142 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001143 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1144 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001145 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001146
1147 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001148 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001149 FunctionType::ExtInfo());
Chris Lattner2192fe52011-07-18 04:24:23 +00001150 llvm::FunctionType *impType =
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001151 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001152 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001153
1154
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001155 // For sender-aware dispatch, we pass the sender as the third argument to a
1156 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001157 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001158 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001159 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001160 0, &call);
1161 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001162
David Chisnall29cefd12010-05-20 13:45:48 +00001163
David Chisnall75afda62010-04-27 15:08:48 +00001164 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001165 messageBB = CGF.Builder.GetInsertBlock();
1166 CGF.Builder.CreateBr(continueBB);
1167 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001168 if (msgRet.isScalar()) {
1169 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001170 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001171 phi->addIncoming(v, messageBB);
1172 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1173 msgRet = RValue::get(phi);
1174 } else if (msgRet.isAggregate()) {
1175 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001176 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2192fe52011-07-18 04:24:23 +00001177 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001178 llvm::AllocaInst *NullVal =
1179 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001180 CGF.InitTempAlloca(NullVal,
1181 llvm::Constant::getNullValue(RetTy->getElementType()));
1182 phi->addIncoming(v, messageBB);
1183 phi->addIncoming(NullVal, startBB);
1184 msgRet = RValue::getAggregate(phi);
1185 } else /* isComplex() */ {
1186 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001187 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001188 phi->addIncoming(v.first, messageBB);
1189 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1190 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001191 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001192 phi2->addIncoming(v.second, messageBB);
1193 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1194 startBB);
1195 msgRet = RValue::getComplex(phi, phi2);
1196 }
1197 }
1198 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001199}
1200
Mike Stump11289f42009-09-09 15:08:12 +00001201/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001202/// objc_category structures.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001203llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1204 const StringRef &CategoryName,
1205 const SmallVectorImpl<Selector> &MethodSels,
1206 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001207 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001208 if (MethodSels.empty())
1209 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001210 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001211 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001212 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1213 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001214 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001215 NULL);
1216 std::vector<llvm::Constant*> Methods;
1217 std::vector<llvm::Constant*> Elements;
1218 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1219 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001220 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001221 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001222 MethodSels[i],
1223 isClassMethodList));
1224 assert(Method && "Can't generate metadata for method that doesn't exist");
1225 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1226 Elements.push_back(C);
1227 Elements.push_back(MethodTypes[i]);
1228 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001229 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001230 Elements.push_back(Method);
1231 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001232 }
1233
1234 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001235 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001236 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001237 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001238 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001239
1240 // Structure containing list pointer, array and array count
Chris Lattnera5f58b02011-07-09 17:41:47 +00001241 llvm::StructType *ObjCMethodListTy =
1242 llvm::StructType::createNamed(VMContext, "");
1243 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1244 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001245 NextPtrTy,
1246 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001247 ObjCMethodArrayTy,
1248 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001249
1250 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001251 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001252 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001253 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001254 MethodTypes.size()));
1255 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001256
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001257 // Create an instance of the structure
1258 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1259}
1260
1261/// Generates an IvarList. Used in construction of a objc_class.
1262llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001263 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1264 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1265 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001266 if (IvarNames.size() == 0)
1267 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001268 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001269 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001270 PtrToInt8Ty,
1271 PtrToInt8Ty,
1272 IntTy,
1273 NULL);
1274 std::vector<llvm::Constant*> Ivars;
1275 std::vector<llvm::Constant*> Elements;
1276 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1277 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001278 Elements.push_back(IvarNames[i]);
1279 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001280 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001281 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001282 }
1283
1284 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001285 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001286 IvarNames.size());
1287
Mike Stump11289f42009-09-09 15:08:12 +00001288
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001289 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001290 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001291 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001292 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001293 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001294 ObjCIvarArrayTy,
1295 NULL);
1296
1297 // Create an instance of the structure
1298 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1299}
1300
1301/// Generate a class structure
1302llvm::Constant *CGObjCGNU::GenerateClassStructure(
1303 llvm::Constant *MetaClass,
1304 llvm::Constant *SuperClass,
1305 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001306 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001307 llvm::Constant *Version,
1308 llvm::Constant *InstanceSize,
1309 llvm::Constant *IVars,
1310 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001311 llvm::Constant *Protocols,
1312 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001313 llvm::Constant *Properties,
1314 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001315 // Set up the class structure
1316 // Note: Several of these are char*s when they should be ids. This is
1317 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001318 //
1319 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1320 // anyway; the classes will still work with the GNU runtime, they will just
1321 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001322 llvm::StructType *ClassTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001323 PtrToInt8Ty, // class_pointer
1324 PtrToInt8Ty, // super_class
1325 PtrToInt8Ty, // name
1326 LongTy, // version
1327 LongTy, // info
1328 LongTy, // instance_size
1329 IVars->getType(), // ivars
1330 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001331 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001332 PtrTy, // dtable
1333 PtrTy, // subclass_list
1334 PtrTy, // sibling_class
1335 PtrTy, // protocols
1336 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001337 // New ABI:
1338 LongTy, // abi_version
1339 IvarOffsets->getType(), // ivar_offsets
1340 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001341 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001342 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001343 // Fill in the structure
1344 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001345 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001346 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001347 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001348 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001349 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001350 if (isMeta) {
1351 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001352 Elements.push_back(
1353 llvm::ConstantInt::get(LongTy,
1354 td.getTypeSizeInBits(ClassTy) /
1355 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001356 } else
1357 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001358 Elements.push_back(IVars);
1359 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001360 Elements.push_back(NULLPtr);
1361 Elements.push_back(NULLPtr);
1362 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001363 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001364 Elements.push_back(NULLPtr);
1365 Elements.push_back(Zero);
1366 Elements.push_back(IvarOffsets);
1367 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001368 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001369 // This is now an externally visible symbol, so that we can speed up class
1370 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001371 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1372 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001373}
1374
1375llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001376 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1377 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001378 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001379 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001380 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1381 PtrToInt8Ty,
1382 NULL);
1383 std::vector<llvm::Constant*> Methods;
1384 std::vector<llvm::Constant*> Elements;
1385 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1386 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001387 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001388 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001389 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001390 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001391 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001392 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001393 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001394 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001395 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001396 IntTy, ObjCMethodArrayTy, NULL);
1397 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001398 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001399 Methods.push_back(Array);
1400 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1401}
Mike Stumpdd93a192009-07-31 21:31:32 +00001402
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001403// Create the protocol list structure used in classes, categories and so on
1404llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001405 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001406 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001407 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001408 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001409 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001410 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001411 ProtocolArrayTy,
1412 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001413 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001414 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1415 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001416 llvm::Constant *protocol = 0;
1417 llvm::StringMap<llvm::Constant*>::iterator value =
1418 ExistingProtocols.find(*iter);
1419 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001420 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001421 } else {
1422 protocol = value->getValue();
1423 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001424 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001425 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001426 Elements.push_back(Ptr);
1427 }
Owen Anderson47034e12009-07-28 18:33:04 +00001428 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001429 Elements);
1430 Elements.clear();
1431 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001432 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001433 Elements.push_back(ProtocolArray);
1434 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1435}
1436
Mike Stump11289f42009-09-09 15:08:12 +00001437llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001438 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001439 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001440 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001441 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001442 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001443}
1444
1445llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1446 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001447 SmallVector<std::string, 0> EmptyStringVector;
1448 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001449
1450 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001451 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001452 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1453 // Protocols are objects containing lists of the methods implemented and
1454 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001455 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001456 PtrToInt8Ty,
1457 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001458 MethodList->getType(),
1459 MethodList->getType(),
1460 MethodList->getType(),
1461 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001462 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001463 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001464 // The isa pointer must be set to a magic number so the runtime knows it's
1465 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001466 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001467 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1468 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001469 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1470 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001471 Elements.push_back(MethodList);
1472 Elements.push_back(MethodList);
1473 Elements.push_back(MethodList);
1474 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001475 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001476}
1477
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001478void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1479 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001480 std::string ProtocolName = PD->getNameAsString();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001481 SmallVector<std::string, 16> Protocols;
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001482 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1483 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001484 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1486 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1487 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1488 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001489 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1490 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001491 std::string TypeStr;
1492 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001493 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1494 InstanceMethodNames.push_back(
1495 MakeConstantString((*iter)->getSelector().getAsString()));
1496 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1497 } else {
1498 OptionalInstanceMethodNames.push_back(
1499 MakeConstantString((*iter)->getSelector().getAsString()));
1500 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1501 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001502 }
1503 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001504 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1505 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1506 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1507 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001508 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001509 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1510 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001511 std::string TypeStr;
1512 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001513 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1514 ClassMethodNames.push_back(
1515 MakeConstantString((*iter)->getSelector().getAsString()));
1516 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1517 } else {
1518 OptionalClassMethodNames.push_back(
1519 MakeConstantString((*iter)->getSelector().getAsString()));
1520 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1521 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001522 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001523
1524 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1525 llvm::Constant *InstanceMethodList =
1526 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1527 llvm::Constant *ClassMethodList =
1528 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001529 llvm::Constant *OptionalInstanceMethodList =
1530 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1531 OptionalInstanceMethodTypes);
1532 llvm::Constant *OptionalClassMethodList =
1533 GenerateProtocolMethodList(OptionalClassMethodNames,
1534 OptionalClassMethodTypes);
1535
1536 // Property metadata: name, attributes, isSynthesized, setter name, setter
1537 // types, getter name, getter types.
1538 // The isSynthesized value is always set to 0 in a protocol. It exists to
1539 // simplify the runtime library by allowing it to use the same data
1540 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001541 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001542 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1543 PtrToInt8Ty, NULL);
1544 std::vector<llvm::Constant*> Properties;
1545 std::vector<llvm::Constant*> OptionalProperties;
1546
1547 // Add all of the property methods need adding to the method list and to the
1548 // property metadata list.
1549 for (ObjCContainerDecl::prop_iterator
1550 iter = PD->prop_begin(), endIter = PD->prop_end();
1551 iter != endIter ; iter++) {
1552 std::vector<llvm::Constant*> Fields;
1553 ObjCPropertyDecl *property = (*iter);
1554
1555 Fields.push_back(MakeConstantString(property->getNameAsString()));
1556 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1557 property->getPropertyAttributes()));
1558 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1559 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1560 std::string TypeStr;
1561 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1562 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1563 InstanceMethodTypes.push_back(TypeEncoding);
1564 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1565 Fields.push_back(TypeEncoding);
1566 } else {
1567 Fields.push_back(NULLPtr);
1568 Fields.push_back(NULLPtr);
1569 }
1570 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1571 std::string TypeStr;
1572 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1573 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1574 InstanceMethodTypes.push_back(TypeEncoding);
1575 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1576 Fields.push_back(TypeEncoding);
1577 } else {
1578 Fields.push_back(NULLPtr);
1579 Fields.push_back(NULLPtr);
1580 }
1581 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1582 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1583 } else {
1584 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1585 }
1586 }
1587 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1588 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1589 llvm::Constant* PropertyListInitFields[] =
1590 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1591
1592 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001593 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001594 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1595 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1596 PropertyListInit, ".objc_property_list");
1597
1598 llvm::Constant *OptionalPropertyArray =
1599 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1600 OptionalProperties.size()) , OptionalProperties);
1601 llvm::Constant* OptionalPropertyListInitFields[] = {
1602 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1603 OptionalPropertyArray };
1604
1605 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001606 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001607 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1608 OptionalPropertyListInit->getType(), false,
1609 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1610 ".objc_property_list");
1611
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001612 // Protocols are objects containing lists of the methods implemented and
1613 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001614 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001615 PtrToInt8Ty,
1616 ProtocolList->getType(),
1617 InstanceMethodList->getType(),
1618 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001619 OptionalInstanceMethodList->getType(),
1620 OptionalClassMethodList->getType(),
1621 PropertyList->getType(),
1622 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001623 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001624 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001625 // The isa pointer must be set to a magic number so the runtime knows it's
1626 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001627 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001628 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1629 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001630 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1631 Elements.push_back(ProtocolList);
1632 Elements.push_back(InstanceMethodList);
1633 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001634 Elements.push_back(OptionalInstanceMethodList);
1635 Elements.push_back(OptionalClassMethodList);
1636 Elements.push_back(PropertyList);
1637 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001638 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001639 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001640 ".objc_protocol"), IdTy);
1641}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001642void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1643 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001644 SmallVector<Selector, 1> MethodSels;
1645 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001646
1647 std::vector<llvm::Constant*> Elements;
1648 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1649 const std::string CategoryName = "AnotherHack";
1650 Elements.push_back(MakeConstantString(CategoryName));
1651 Elements.push_back(MakeConstantString(ClassName));
1652 // Instance method list
1653 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1654 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1655 // Class method list
1656 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1657 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1658 // Protocol list
1659 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1660 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001661 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001662 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001663 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001664 ProtocolArrayTy,
1665 NULL);
1666 std::vector<llvm::Constant*> ProtocolElements;
1667 for (llvm::StringMapIterator<llvm::Constant*> iter =
1668 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1669 iter != endIter ; iter++) {
1670 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1671 PtrTy);
1672 ProtocolElements.push_back(Ptr);
1673 }
1674 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1675 ProtocolElements);
1676 ProtocolElements.clear();
1677 ProtocolElements.push_back(NULLPtr);
1678 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1679 ExistingProtocols.size()));
1680 ProtocolElements.push_back(ProtocolArray);
1681 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1682 ProtocolElements, ".objc_protocol_list"), PtrTy));
1683 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001684 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001685 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1686}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001687
Daniel Dunbar92992502008-08-15 22:20:32 +00001688void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001689 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1690 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001691 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001692 SmallVector<Selector, 16> InstanceMethodSels;
1693 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001694 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001695 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001696 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001697 InstanceMethodSels.push_back((*iter)->getSelector());
1698 std::string TypeStr;
1699 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001700 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001701 }
1702
1703 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001704 SmallVector<Selector, 16> ClassMethodSels;
1705 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001706 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001707 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001708 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001709 ClassMethodSels.push_back((*iter)->getSelector());
1710 std::string TypeStr;
1711 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001712 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001713 }
1714
1715 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001716 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001717 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1718 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001719 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1720 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001721 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001722
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001723 std::vector<llvm::Constant*> Elements;
1724 Elements.push_back(MakeConstantString(CategoryName));
1725 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001726 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001727 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001728 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001729 false), PtrTy));
1730 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001731 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001732 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001733 PtrTy));
1734 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001735 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001736 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001737 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001738 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001739 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001740}
Daniel Dunbar92992502008-08-15 22:20:32 +00001741
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001742llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001743 SmallVectorImpl<Selector> &InstanceMethodSels,
1744 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001745 ASTContext &Context = CGM.getContext();
1746 //
1747 // Property metadata: name, attributes, isSynthesized, setter name, setter
1748 // types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00001749 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001750 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1751 PtrToInt8Ty, NULL);
1752 std::vector<llvm::Constant*> Properties;
1753
1754
1755 // Add all of the property methods need adding to the method list and to the
1756 // property metadata list.
1757 for (ObjCImplDecl::propimpl_iterator
1758 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1759 iter != endIter ; iter++) {
1760 std::vector<llvm::Constant*> Fields;
1761 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001762 ObjCPropertyImplDecl *propertyImpl = *iter;
1763 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1764 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001765
1766 Fields.push_back(MakeConstantString(property->getNameAsString()));
1767 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1768 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001769 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001770 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001771 std::string TypeStr;
1772 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1773 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001774 if (isSynthesized) {
1775 InstanceMethodTypes.push_back(TypeEncoding);
1776 InstanceMethodSels.push_back(getter->getSelector());
1777 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001778 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1779 Fields.push_back(TypeEncoding);
1780 } else {
1781 Fields.push_back(NULLPtr);
1782 Fields.push_back(NULLPtr);
1783 }
1784 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001785 std::string TypeStr;
1786 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1787 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001788 if (isSynthesized) {
1789 InstanceMethodTypes.push_back(TypeEncoding);
1790 InstanceMethodSels.push_back(setter->getSelector());
1791 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001792 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1793 Fields.push_back(TypeEncoding);
1794 } else {
1795 Fields.push_back(NULLPtr);
1796 Fields.push_back(NULLPtr);
1797 }
1798 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1799 }
1800 llvm::ArrayType *PropertyArrayTy =
1801 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1802 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1803 Properties);
1804 llvm::Constant* PropertyListInitFields[] =
1805 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1806
1807 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001808 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001809 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1810 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1811 ".objc_property_list");
1812}
1813
Daniel Dunbar92992502008-08-15 22:20:32 +00001814void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1815 ASTContext &Context = CGM.getContext();
1816
1817 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001818 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001819 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001820 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001821 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001822 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001823 EmitClassRef(SuperClassName);
1824 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001825
1826 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001827 ObjCInterfaceDecl *ClassDecl =
1828 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001829 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001830 // Emit the symbol that is used to generate linker errors if this class is
1831 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001832 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001833 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001834 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001835 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001836 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001837 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001838 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001839 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001840 }
Mike Stump11289f42009-09-09 15:08:12 +00001841
Daniel Dunbar12119b92009-05-03 10:46:44 +00001842 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001843 int instanceSize =
1844 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001845
1846 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001847 SmallVector<llvm::Constant*, 16> IvarNames;
1848 SmallVector<llvm::Constant*, 16> IvarTypes;
1849 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001850
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001851 std::vector<llvm::Constant*> IvarOffsetValues;
1852
Mike Stump11289f42009-09-09 15:08:12 +00001853 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001854 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001855 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1856 // class}. The runtime will then set this to the correct value on load.
1857 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1858 instanceSize = 0 - (instanceSize - superInstanceSize);
1859 }
David Chisnall18cf7372010-04-19 00:45:34 +00001860
Jordy Rosea91768e2011-07-22 02:08:32 +00001861 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1862 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001863 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001864 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001865 // Get the type encoding for this ivar
1866 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001867 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001868 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001869 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001870 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001871 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001872 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001873 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001874 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00001875 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1876 // Create the direct offset value
1877 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1878 IVD->getNameAsString();
1879 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1880 if (OffsetVar) {
1881 OffsetVar->setInitializer(OffsetValue);
1882 // If this is the real definition, change its linkage type so that
1883 // different modules will use this one, rather than their private
1884 // copy.
1885 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1886 } else
1887 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001888 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00001889 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001890 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00001891 IVD->getNameAsString());
1892 IvarOffsets.push_back(OffsetValue);
1893 IvarOffsetValues.push_back(OffsetVar);
Daniel Dunbar92992502008-08-15 22:20:32 +00001894 }
David Chisnalld7972f52011-03-23 16:36:54 +00001895 llvm::GlobalVariable *IvarOffsetArray =
1896 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1897
Daniel Dunbar92992502008-08-15 22:20:32 +00001898
1899 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001900 SmallVector<Selector, 16> InstanceMethodSels;
1901 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001902 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001903 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001904 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001905 InstanceMethodSels.push_back((*iter)->getSelector());
1906 std::string TypeStr;
1907 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001908 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001909 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001910
1911 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1912 InstanceMethodTypes);
1913
Daniel Dunbar92992502008-08-15 22:20:32 +00001914
1915 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001916 SmallVector<Selector, 16> ClassMethodSels;
1917 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001918 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001919 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001920 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001921 ClassMethodSels.push_back((*iter)->getSelector());
1922 std::string TypeStr;
1923 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001924 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001925 }
1926 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001927 SmallVector<std::string, 16> Protocols;
Daniel Dunbar92992502008-08-15 22:20:32 +00001928 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1929 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1930 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001931 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001932
1933
1934
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001935 // Get the superclass pointer.
1936 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001937 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001938 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1939 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001940 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001941 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001942 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001943 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001944 // Generate the method and instance variable lists
1945 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001946 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001947 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001948 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001949 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1950 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001951 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001952 // we emit a symbol containing the offset for each ivar in the class. This
1953 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1954 // for the legacy ABI, without causing problems. The converse is also
1955 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001956
David Chisnall5778fce2009-08-31 16:41:57 +00001957 // Offset pointer for getting at the correct field in the ivar list when
1958 // setting up the alias. These are: The base address for the global, the
1959 // ivar array (second field), the ivar in this list (set for each ivar), and
1960 // the offset (third field in ivar structure)
Chris Lattner2192fe52011-07-18 04:24:23 +00001961 llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
David Chisnall5778fce2009-08-31 16:41:57 +00001962 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001963 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001964 llvm::ConstantInt::get(IndexTy, 2) };
1965
Jordy Rosea91768e2011-07-22 02:08:32 +00001966 unsigned ivarIndex = 0;
1967 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1968 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00001969 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001970 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00001971 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00001972 // Get the correct ivar field
1973 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001974 IvarList, offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00001975 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001976 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1977 if (offset) {
1978 offset->setInitializer(offsetValue);
1979 // If this is the real definition, change its linkage type so that
1980 // different modules will use this one, rather than their private
1981 // copy.
1982 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1983 } else {
1984 // Add a new alias if there isn't one already.
1985 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1986 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1987 }
Jordy Rosea91768e2011-07-22 02:08:32 +00001988 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00001989 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001990 //Generate metaclass for class methods
1991 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001992 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001993 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001994
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001995 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001996 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001997 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001998 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001999 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002000 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2001 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002002
2003 // Resolve the class aliases, if they exist.
2004 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002005 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002006 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002007 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002008 ClassPtrAlias = 0;
2009 }
2010 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002011 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002012 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002013 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002014 MetaClassPtrAlias = 0;
2015 }
2016
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002017 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002018 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002019 Classes.push_back(ClassStruct);
2020}
2021
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002022
Mike Stump11289f42009-09-09 15:08:12 +00002023llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002024 // Only emit an ObjC load function if no Objective-C stuff has been called
2025 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002026 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002027 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002028
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002029 // Add all referenced protocols to a category.
2030 GenerateProtocolHolderCategory();
2031
Chris Lattner2192fe52011-07-18 04:24:23 +00002032 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002033 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002034 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002035 if (SelStructTy == 0) {
Chris Lattner845511f2011-06-18 22:49:11 +00002036 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002037 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002038 }
2039
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002040 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002041 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002042 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002043 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002044 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002045 ConstantStrings.size() + 1);
2046 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002047
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002048 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002049
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002050 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002051
David Chisnall5778fce2009-08-31 16:41:57 +00002052 Elements.push_back(MakeConstantString(StringClass,
2053 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002054 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002055 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002056 llvm::StructType *StaticsListTy =
Chris Lattner845511f2011-06-18 22:49:11 +00002057 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002058 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002059 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002060 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002061 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002062 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002063 Elements.clear();
2064 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002065 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002066 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002067 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002068 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002069 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002070 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002071 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002072 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002073 llvm::Type::getInt16Ty(VMContext),
2074 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002075 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002076
2077 Elements.clear();
2078 // Pointer to an array of selectors used in this module.
2079 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002080 std::vector<llvm::GlobalAlias*> SelectorAliases;
2081 for (SelectorMap::iterator iter = SelectorTable.begin(),
2082 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2083
2084 std::string SelNameStr = iter->first.getAsString();
2085 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2086
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002087 SmallVectorImpl<TypedSelector> &Types = iter->second;
2088 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002089 e = Types.end() ; i!=e ; i++) {
2090
2091 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2092 if (!i->first.empty())
2093 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2094
2095 Elements.push_back(SelName);
2096 Elements.push_back(SelectorTypeEncoding);
2097 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2098 Elements.clear();
2099
2100 // Store the selector alias for later replacement
2101 SelectorAliases.push_back(i->second);
2102 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002103 }
David Chisnalld7972f52011-03-23 16:36:54 +00002104 unsigned SelectorCount = Selectors.size();
2105 // NULL-terminate the selector list. This should not actually be required,
2106 // because the selector list has a length field. Unfortunately, the GCC
2107 // runtime decides to ignore the length field and expects a NULL terminator,
2108 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002109 Elements.push_back(NULLPtr);
2110 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002111 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002112 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002113
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002114 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002115 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2116 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002117 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002118 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002119 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002120
2121 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002122 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2123
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002124 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00002125 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2126 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002127 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foaded8db7d2011-07-21 14:31:17 +00002128 makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002129 // If selectors are defined as an opaque type, cast the pointer to this
2130 // type.
David Chisnall76803412011-03-23 22:52:06 +00002131 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002132 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2133 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002134 }
David Chisnalld7972f52011-03-23 16:36:54 +00002135
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002136 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002137 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002138 Classes.size()));
2139 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002140 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002141 Categories.size()));
2142 // Create an array of classes, then categories, then static object instances
2143 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2144 // NULL-terminated list of static object instances (mainly constant strings)
2145 Classes.push_back(Statics);
2146 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002147 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002148 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002149 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002150 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2151
2152 // The symbol table is contained in a module which has some version-checking
2153 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002154 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002155 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnalla918b882011-07-07 11:22:31 +00002156 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002157 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002158 // Runtime version, used for ABI compatibility checking.
2159 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002160 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002161 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002162 Elements.push_back(
2163 llvm::ConstantInt::get(LongTy,
2164 td.getTypeSizeInBits(ModuleTy) /
2165 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002166
2167 // The path to the source file where this module was declared
2168 SourceManager &SM = CGM.getContext().getSourceManager();
2169 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2170 std::string path =
2171 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2172 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002173 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002174
David Chisnalla918b882011-07-07 11:22:31 +00002175 if (RuntimeVersion >= 10)
2176 switch (CGM.getLangOptions().getGCMode()) {
2177 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002178 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002179 break;
David Chisnalla918b882011-07-07 11:22:31 +00002180 case LangOptions::NonGC:
2181 if (CGM.getLangOptions().ObjCAutoRefCount)
2182 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2183 else
2184 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2185 break;
2186 case LangOptions::HybridGC:
2187 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2188 break;
2189 }
David Chisnall5c511772011-05-22 22:37:08 +00002190
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002191 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2192
2193 // Create the load function calling the runtime entry point with the module
2194 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002195 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002196 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002197 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2198 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002199 llvm::BasicBlock *EntryBB =
2200 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002201 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002202 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002203
Chris Lattnera5f58b02011-07-09 17:41:47 +00002204 llvm::Type *ArgTys[] = { llvm::PointerType::getUnqual(ModuleTy) };
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002205 llvm::FunctionType *FT =
Chris Lattnera5f58b02011-07-09 17:41:47 +00002206 llvm::FunctionType::get(Builder.getVoidTy(), ArgTys, true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002207 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002208 Builder.CreateCall(Register, Module);
2209 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002210
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002211 return LoadFunction;
2212}
Daniel Dunbar92992502008-08-15 22:20:32 +00002213
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002214llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002215 const ObjCContainerDecl *CD) {
2216 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002217 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002218 StringRef CategoryName = OCD ? OCD->getName() : "";
2219 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002220 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002221 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002222
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002223 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002224 llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002225 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002226 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2227 MethodName, isClassMethod);
2228
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002229 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002230 = llvm::Function::Create(MethodTy,
2231 llvm::GlobalValue::InternalLinkage,
2232 FunctionName,
2233 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002234 return Method;
2235}
2236
David Chisnall3fe89562011-05-23 22:33:28 +00002237llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002238 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002239}
2240
David Chisnall3fe89562011-05-23 22:33:28 +00002241llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002242 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002243}
2244
David Chisnall3fe89562011-05-23 22:33:28 +00002245llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002246 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002247}
David Chisnall3fe89562011-05-23 22:33:28 +00002248llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002249 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002250}
2251
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002252llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002253 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002254}
2255
David Chisnalld7972f52011-03-23 16:36:54 +00002256void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002257 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002258 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002259}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002260
David Chisnall3a509cd2009-12-24 02:26:34 +00002261
David Chisnalld7972f52011-03-23 16:36:54 +00002262void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002263 const ObjCAtTryStmt &S) {
2264 // Unlike the Apple non-fragile runtimes, which also uses
2265 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2266 // EH support isn't a veneer over C++ EH. Instead, exception
2267 // objects are created by __objc_exception_throw and destroyed by
2268 // the personality function; this avoids the need for bracketing
2269 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2270 // (or even _Unwind_DeleteException), but probably doesn't
2271 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002272 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002273 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002274 // exception handler.
2275 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2276 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002277}
2278
David Chisnalld7972f52011-03-23 16:36:54 +00002279void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002280 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002281 llvm::Value *ExceptionAsObject;
2282
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002283 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2284 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002285 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002286 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002287 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002288 "Unexpected rethrow outside @catch block.");
2289 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2290 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002291 ExceptionAsObject =
2292 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002293
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002294 // Note: This may have to be an invoke, if we want to support constructs like:
2295 // @try {
2296 // @throw(obj);
2297 // }
2298 // @catch(id) ...
2299 //
2300 // This is effectively turning @throw into an incredibly-expensive goto, but
2301 // it may happen as a result of inlining followed by missed optimizations, or
2302 // as a result of stupidity.
2303 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2304 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002305 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002306 CGF.Builder.CreateUnreachable();
2307 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +00002308 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2309 ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002310 }
2311 // Clear the insertion point to indicate we are in unreachable code.
2312 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002313}
2314
David Chisnalld7972f52011-03-23 16:36:54 +00002315llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002316 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002317 CGBuilderTy B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002318 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002319 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002320}
2321
David Chisnalld7972f52011-03-23 16:36:54 +00002322void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002323 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002324 CGBuilderTy B = CGF.Builder;
2325 src = EnforceType(B, src, IdTy);
2326 dst = EnforceType(B, dst, PtrToIdTy);
2327 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002328}
2329
David Chisnalld7972f52011-03-23 16:36:54 +00002330void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002331 llvm::Value *src, llvm::Value *dst,
2332 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002333 CGBuilderTy B = CGF.Builder;
2334 src = EnforceType(B, src, IdTy);
2335 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002336 if (!threadlocal)
2337 B.CreateCall2(GlobalAssignFn, src, dst);
2338 else
2339 // FIXME. Add threadloca assign API
2340 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002341}
2342
David Chisnalld7972f52011-03-23 16:36:54 +00002343void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002344 llvm::Value *src, llvm::Value *dst,
2345 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002346 CGBuilderTy B = CGF.Builder;
2347 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002348 dst = EnforceType(B, dst, IdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002349 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002350}
2351
David Chisnalld7972f52011-03-23 16:36:54 +00002352void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002353 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002354 CGBuilderTy B = CGF.Builder;
2355 src = EnforceType(B, src, IdTy);
2356 dst = EnforceType(B, dst, PtrToIdTy);
2357 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002358}
2359
David Chisnalld7972f52011-03-23 16:36:54 +00002360void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002361 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002362 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002363 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002364 CGBuilderTy B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002365 DestPtr = EnforceType(B, DestPtr, PtrTy);
2366 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002367
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002368 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002369}
2370
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002371llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2372 const ObjCInterfaceDecl *ID,
2373 const ObjCIvarDecl *Ivar) {
2374 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2375 + '.' + Ivar->getNameAsString();
2376 // Emit the variable and initialize it with what we think the correct value
2377 // is. This allows code compiled with non-fragile ivars to work correctly
2378 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002379 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2380 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002381 // This will cause a run-time crash if we accidentally use it. A value of
2382 // 0 would seem more sensible, but will silently overwrite the isa pointer
2383 // causing a great deal of confusion.
2384 uint64_t Offset = -1;
2385 // We can't call ComputeIvarBaseOffset() here if we have the
2386 // implementation, because it will create an invalid ASTRecordLayout object
2387 // that we are then stuck with forever, so we only initialize the ivar
2388 // offset variable with a guess if we only have the interface. The
2389 // initializer will be reset later anyway, when we are generating the class
2390 // description.
2391 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002392 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002393 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2394
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002395 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002396 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002397 // Don't emit the guess in non-PIC code because the linker will not be able
2398 // to replace it with the real version for a library. In non-PIC code you
2399 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002400 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002401 if (CGM.getLangOptions().PICLevel) {
2402 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2403 llvm::Type::getInt32Ty(VMContext), false,
2404 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2405 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2406 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2407 IvarOffsetGV, Name);
2408 } else {
2409 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002410 llvm::Type::getInt32PtrTy(VMContext), false,
2411 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002412 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002413 }
David Chisnall5778fce2009-08-31 16:41:57 +00002414 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002415}
2416
David Chisnalld7972f52011-03-23 16:36:54 +00002417LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002418 QualType ObjectTy,
2419 llvm::Value *BaseValue,
2420 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002421 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002422 const ObjCInterfaceDecl *ID =
2423 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002424 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2425 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002426}
Mike Stumpdd93a192009-07-31 21:31:32 +00002427
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002428static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2429 const ObjCInterfaceDecl *OID,
2430 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002431 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2432 next = next->getNextIvar()) {
2433 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002434 return OID;
2435 }
Mike Stump11289f42009-09-09 15:08:12 +00002436
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002437 // Otherwise check in the super class.
2438 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2439 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002440
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002441 return 0;
2442}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002443
David Chisnalld7972f52011-03-23 16:36:54 +00002444llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002445 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002446 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002447 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002448 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002449 if (RuntimeVersion < 10)
2450 return CGF.Builder.CreateZExtOrBitCast(
2451 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2452 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2453 PtrDiffTy);
2454 std::string name = "__objc_ivar_offset_value_" +
2455 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2456 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2457 if (!Offset)
2458 Offset = new llvm::GlobalVariable(TheModule, IntTy,
2459 false, llvm::GlobalValue::CommonLinkage,
2460 0, name);
2461 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002462 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002463 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002464 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002465}
2466
David Chisnalld7972f52011-03-23 16:36:54 +00002467CGObjCRuntime *
2468clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2469 if (CGM.getLangOptions().ObjCNonFragileABI)
2470 return new CGObjCGNUstep(CGM);
2471 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002472}