blob: 2f740aa6cf36c353146624aa9443f0335e0bf9e0 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000021
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnalle1d2584d2011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000038
David Chisnalld7972f52011-03-23 16:36:54 +000039#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000040
41
Chris Lattner87ab27d2008-06-26 04:19:03 +000042using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000043using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000044using llvm::dyn_cast;
45
Chris Lattnerb7256cd2008-03-01 08:50:34 +000046
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047namespace {
David Chisnall34d00052011-03-26 11:48:37 +000048/// Class that lazily initialises the runtime function. Avoids inserting the
49/// types and the function declaration into a module if they're not used, and
50/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000051class LazyRuntimeFunction {
52 CodeGenModule *CGM;
53 std::vector<const llvm::Type*> ArgTys;
54 const char *FunctionName;
55 llvm::Function *Function;
56 public:
David Chisnall34d00052011-03-26 11:48:37 +000057 /// Constructor leaves this class uninitialized, because it is intended to
58 /// be used as a field in another class and not all of the types that are
59 /// used as arguments will necessarily be available at construction time.
David Chisnalld7972f52011-03-23 16:36:54 +000060 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
61
David Chisnall34d00052011-03-26 11:48:37 +000062 /// Initialises the lazy function with the name, return type, and the types
63 /// of the arguments.
David Chisnalld7972f52011-03-23 16:36:54 +000064 END_WITH_NULL
65 void init(CodeGenModule *Mod, const char *name,
66 const llvm::Type *RetTy, ...) {
67 CGM =Mod;
68 FunctionName = name;
69 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000070 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000071 va_list Args;
72 va_start(Args, RetTy);
73 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
74 ArgTys.push_back(ArgTy);
75 va_end(Args);
76 // Push the return type on at the end so we can pop it off easily
77 ArgTys.push_back(RetTy);
78 }
David Chisnall34d00052011-03-26 11:48:37 +000079 /// Overloaded cast operator, allows the class to be implicitly cast to an
80 /// LLVM constant.
David Chisnalld7972f52011-03-23 16:36:54 +000081 operator llvm::Function*() {
82 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000083 if (0 == FunctionName) return 0;
84 // We put the return type on the end of the vector, so pop it back off
David Chisnalld7972f52011-03-23 16:36:54 +000085 const llvm::Type *RetTy = ArgTys.back();
86 ArgTys.pop_back();
87 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
88 Function =
89 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000090 // We won't need to use the types again, so we may as well clean up the
91 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +000092 ArgTys.resize(0);
93 }
94 return Function;
95 }
96};
97
98
David Chisnall34d00052011-03-26 11:48:37 +000099/// GNU Objective-C runtime code generation. This class implements the parts of
100/// Objective-C support that are specific to the GNU family of runtimes (GCC and
101/// GNUstep).
David Chisnalld7972f52011-03-23 16:36:54 +0000102class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000103protected:
David Chisnall34d00052011-03-26 11:48:37 +0000104 /// The module that is using this class
David Chisnalld7972f52011-03-23 16:36:54 +0000105 CodeGenModule &CGM;
David Chisnall34d00052011-03-26 11:48:37 +0000106 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000107 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000108 /// strut objc_super. Used for sending messages to super. This structure
109 /// contains the receiver (object) and the expected class.
David Chisnall76803412011-03-23 22:52:06 +0000110 const llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// struct objc_super*. The type of the argument to the superclass message
112 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000113 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
115 /// SEL is included in a header somewhere, in which case it will be whatever
116 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000117 const llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000118 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
119 /// places where it's used
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000120 const llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000121 /// Pointer to i8 - LLVM type of char*, for all of the places where the
122 /// runtime needs to deal with C strings.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000123 const llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000124 /// Instance Method Pointer type. This is a pointer to a function that takes,
125 /// at a minimum, an object and a selector, and is the generic type for
126 /// Objective-C methods. Due to differences between variadic / non-variadic
127 /// calling conventions, it must always be cast to the correct type before
128 /// actually being used.
David Chisnall76803412011-03-23 22:52:06 +0000129 const llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000130 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
131 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
132 /// but if the runtime header declaring it is included then it may be a
133 /// pointer to a structure.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000134 const llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
136 /// message lookup function and some GC-related functions.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000137 const llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000138 /// The clang type of id. Used when using the clang CGCall infrastructure to
139 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000140 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000141 /// LLVM type for C int type.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000142 const llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
144 /// used in the code to document the difference between i8* meaning a pointer
145 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000146 const llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000147 /// LLVM type for C long type. The runtime uses this in a lot of places where
148 /// it should be using intptr_t, but we can't fix this without breaking
149 /// compatibility with GCC...
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000150 const llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000151 /// LLVM type for C size_t. Used in various runtime data structures.
David Chisnall168b80f2010-12-26 22:13:16 +0000152 const llvm::IntegerType *SizeTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
David Chisnall168b80f2010-12-26 22:13:16 +0000154 const llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 /// variables.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000157 const llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// LLVM type for Objective-C BOOL type.
David Chisnall168b80f2010-12-26 22:13:16 +0000159 const llvm::Type *BoolTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// Metadata kind used to tie method lookups to message sends. The GNUstep
161 /// runtime provides some LLVM passes that can use this to do things like
162 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000163 unsigned msgSendMDKind;
David Chisnall34d00052011-03-26 11:48:37 +0000164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000167 llvm::Constant *MakeConstantString(const std::string &Str,
168 const std::string &Name="") {
169 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
170 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
171 }
David Chisnall34d00052011-03-26 11:48:37 +0000172 /// Emits a linkonce_odr string, whose name is the prefix followed by the
173 /// string value. This allows the linker to combine the strings between
174 /// different modules. Used for EH typeinfo names, selector strings, and a
175 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000176 llvm::Constant *ExportUniqueString(const std::string &Str,
177 const std::string prefix) {
178 std::string name = prefix + Str;
179 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
180 if (!ConstStr) {
181 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
182 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
183 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
184 }
185 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
186 }
David Chisnall34d00052011-03-26 11:48:37 +0000187 /// Generates a global structure, initialized by the elements in the vector.
188 /// The element types must match the types of the structure elements in the
189 /// first argument.
David Chisnall76803412011-03-23 22:52:06 +0000190 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000191 std::vector<llvm::Constant*> &V,
192 llvm::StringRef Name="",
193 llvm::GlobalValue::LinkageTypes linkage
194 =llvm::GlobalValue::InternalLinkage) {
195 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
196 return new llvm::GlobalVariable(TheModule, Ty, false,
197 linkage, C, Name);
198 }
David Chisnall34d00052011-03-26 11:48:37 +0000199 /// Generates a global array. The vector must contain the same number of
200 /// elements that the array type declares, of the type specified as the array
201 /// element type.
David Chisnall76803412011-03-23 22:52:06 +0000202 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000203 std::vector<llvm::Constant*> &V,
204 llvm::StringRef Name="",
205 llvm::GlobalValue::LinkageTypes linkage
206 =llvm::GlobalValue::InternalLinkage) {
207 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
208 return new llvm::GlobalVariable(TheModule, Ty, false,
209 linkage, C, Name);
210 }
David Chisnall34d00052011-03-26 11:48:37 +0000211 /// Generates a global array, inferring the array type from the specified
212 /// element type and the size of the initialiser.
David Chisnall76803412011-03-23 22:52:06 +0000213 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000214 std::vector<llvm::Constant*> &V,
215 llvm::StringRef Name="",
216 llvm::GlobalValue::LinkageTypes linkage
217 =llvm::GlobalValue::InternalLinkage) {
218 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
219 return MakeGlobal(ArrayTy, V, Name, linkage);
220 }
David Chisnall34d00052011-03-26 11:48:37 +0000221 /// Ensures that the value has the required type, by inserting a bitcast if
222 /// required. This function lets us avoid inserting bitcasts that are
223 /// redundant.
David Chisnall76803412011-03-23 22:52:06 +0000224 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
225 if (V->getType() == Ty) return V;
226 return B.CreateBitCast(V, Ty);
227 }
228 // Some zeros used for GEPs in lots of places.
229 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000230 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000231 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000232 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000233 llvm::LLVMContext &VMContext;
234private:
David Chisnall34d00052011-03-26 11:48:37 +0000235 /// Placeholder for the class. Lots of things refer to the class before we've
236 /// actually emitted it. We use this alias as a placeholder, and then replace
237 /// it with a pointer to the class structure before finally emitting the
238 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000239 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000240 /// Placeholder for the metaclass. Lots of things refer to the class before
241 /// we've / actually emitted it. We use this alias as a placeholder, and then
242 /// replace / it with a pointer to the metaclass structure before finally
243 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000244 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000245 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000246 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000247 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000248 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000249 /// All of the Objective-C constant strings that have been generated for this
250 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000251 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000252 /// Map from string values to Objective-C constant strings in the output.
253 /// Used to prevent emitting Objective-C strings more than once. This should
254 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000255 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000256 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000257 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000258 /// For each variant of a selector, we store the type encoding and a
259 /// placeholder value. For an untyped selector, the type will be the empty
260 /// string. Selector references are all done via the module's selector table,
261 /// so we create an alias as a placeholder and then replace it with the real
262 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000263 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000264 /// Type of the selector map. This is roughly equivalent to the structure
265 /// used in the GNUstep runtime, which maintains a list of all of the valid
266 /// types for a selector in a table.
David Chisnalld7972f52011-03-23 16:36:54 +0000267 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
268 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000269 /// A map from selectors to selector types. This allows us to emit all
270 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000271 SelectorMap SelectorTable;
272
David Chisnall34d00052011-03-26 11:48:37 +0000273 /// Selectors related to memory management. When compiling in GC mode, we
274 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000275 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000276 /// Runtime functions used for memory management in GC mode. Note that clang
277 /// supports code generation for calling these functions, but neither GNU
278 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000279 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
280 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000281
David Chisnalld3858d62011-03-25 11:57:33 +0000282protected:
David Chisnall34d00052011-03-26 11:48:37 +0000283 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000284 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000285 /// Function used for rethrowing exceptions, used at the end of @finally or
286 /// @synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000287 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000288 /// Function called when entering a catch function. This is required for
289 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000290 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000291 /// Function called when exiting from a catch block. Used to do exception
292 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000293 LazyRuntimeFunction ExitCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000294 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000295 LazyRuntimeFunction SyncEnterFn;
David Chisnall34d00052011-03-26 11:48:37 +0000296 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000297 LazyRuntimeFunction SyncExitFn;
298
David Chisnalld3858d62011-03-25 11:57:33 +0000299private:
300
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// Function called if fast enumeration detects that the collection is
302 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000303 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000304 /// Function for implementing synthesized property getters that return an
305 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000306 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000307 /// Function for implementing synthesized property setters that return an
308 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000309 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000310 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000311 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000312 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000313 LazyRuntimeFunction SetStructPropertyFn;
314
David Chisnall34d00052011-03-26 11:48:37 +0000315 /// The version of the runtime that this class targets. Must match the
316 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000317 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000318 /// The version of the protocol class. Used to differentiate between ObjC1
319 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
320 /// components and can not contain declared properties. We always emit
321 /// Objective-C 2 property structures, but we have to pretend that they're
322 /// Objective-C 1 property structures when targeting the GCC runtime or it
323 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000324 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000325private:
David Chisnall34d00052011-03-26 11:48:37 +0000326 /// Generates an instance variable list structure. This is a structure
327 /// containing a size and an array of structures containing instance variable
328 /// metadata. This is used purely for introspection in the fragile ABI. In
329 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000330 llvm::Constant *GenerateIvarList(
331 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
332 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
333 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall34d00052011-03-26 11:48:37 +0000334 /// Generates a method list structure. This is a structure containing a size
335 /// and an array of structures containing method metadata.
336 ///
337 /// This structure is used by both classes and categories, and contains a next
338 /// pointer allowing them to be chained together in a linked list.
David Chisnalld7972f52011-03-23 16:36:54 +0000339 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
340 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000341 const llvm::SmallVectorImpl<Selector> &MethodSels,
342 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000343 bool isClassMethodList);
David Chisnall34d00052011-03-26 11:48:37 +0000344 /// Emits an empty protocol. This is used for @protocol() where no protocol
345 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
346 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000347 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-03-26 11:48:37 +0000348 /// Generates a list of property metadata structures. This follows the same
349 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000350 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
351 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
352 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// Generates a list of referenced protocols. Classes, categories, and
354 /// protocols all use this structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000355 llvm::Constant *GenerateProtocolList(
356 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnall34d00052011-03-26 11:48:37 +0000357 /// To ensure that all protocols are seen by the runtime, we add a category on
358 /// a class defined in the runtime, declaring no methods, but adopting the
359 /// protocols. This is a horribly ugly hack, but it allows us to collect all
360 /// of the protocols without changing the ABI.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000361 void GenerateProtocolHolderCategory(void);
David Chisnall34d00052011-03-26 11:48:37 +0000362 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000363 llvm::Constant *GenerateClassStructure(
364 llvm::Constant *MetaClass,
365 llvm::Constant *SuperClass,
366 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000367 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000368 llvm::Constant *Version,
369 llvm::Constant *InstanceSize,
370 llvm::Constant *IVars,
371 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000372 llvm::Constant *Protocols,
373 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000374 llvm::Constant *Properties,
375 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000376 /// Generates a method list. This is used by protocols to define the required
377 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000378 llvm::Constant *GenerateProtocolMethodList(
379 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
380 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000381 /// Returns a selector with the specified type encoding. An empty string is
382 /// used to return an untyped selector (with the types field set to NULL).
David Chisnalld7972f52011-03-23 16:36:54 +0000383 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
384 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000386 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
387 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000388 /// Emits a reference to a class. This allows the linker to object if there
389 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000390 void EmitClassRef(const std::string &className);
David Chisnall76803412011-03-23 22:52:06 +0000391protected:
David Chisnall34d00052011-03-26 11:48:37 +0000392 /// Looks up the method for sending a message to the specified object. This
393 /// mechanism differs between the GCC and GNU runtimes, so this method must be
394 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000395 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
396 llvm::Value *&Receiver,
397 llvm::Value *cmd,
398 llvm::MDNode *node) = 0;
David Chisnall34d00052011-03-26 11:48:37 +0000399 /// Looks up the method for sending a message to a superclass. This mechanism
400 /// differs between the GCC and GNU runtimes, so this method must be
401 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000402 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
403 llvm::Value *ObjCSuper,
404 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000405public:
David Chisnalld7972f52011-03-23 16:36:54 +0000406 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
407 unsigned protocolClassVersion);
408
David Chisnall481e3a82010-01-23 02:40:42 +0000409 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000410
411 virtual RValue
412 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000413 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000414 QualType ResultType,
415 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000416 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000417 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000418 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000419 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000420 virtual RValue
421 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000422 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000423 QualType ResultType,
424 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000425 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000426 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000427 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000428 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000429 const CallArgList &CallArgs,
430 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000431 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000432 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000433 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
434 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000435 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
436 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000437 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000438
439 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000440 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000441 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
442 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000443 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000444 const ObjCProtocolDecl *PD);
445 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000446 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000447 virtual llvm::Function *GetPropertyGetFunction();
448 virtual llvm::Function *GetPropertySetFunction();
David Chisnall168b80f2010-12-26 22:13:16 +0000449 virtual llvm::Function *GetSetStructFunction();
450 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000451 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000452
David Chisnalld7972f52011-03-23 16:36:54 +0000453 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000454 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000455 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000456 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000457 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000458 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000459 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000460 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000461 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000462 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000463 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000464 llvm::Value *src, llvm::Value *dest,
465 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000466 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000467 llvm::Value *src, llvm::Value *dest,
468 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000469 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000470 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000471 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000472 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000473 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000474 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000475 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000476 QualType ObjectTy,
477 llvm::Value *BaseValue,
478 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000479 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000480 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000481 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000482 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000483 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000484 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000485 return NULLPtr;
486 }
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000487
488 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
489 return 0;
490 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000491};
David Chisnall34d00052011-03-26 11:48:37 +0000492/// Class representing the legacy GCC Objective-C ABI. This is the default when
493/// -fobjc-nonfragile-abi is not specified.
494///
495/// The GCC ABI target actually generates code that is approximately compatible
496/// with the new GNUstep runtime ABI, but refrains from using any features that
497/// would not work with the GCC runtime. For example, clang always generates
498/// the extended form of the class structure, and the extra fields are simply
499/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000500class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000501 /// The GCC ABI message lookup function. Returns an IMP pointing to the
502 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000503 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000504 /// The GCC ABI superclass message lookup function. Takes a pointer to a
505 /// structure describing the receiver and the class, and a selector as
506 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000507 LazyRuntimeFunction MsgLookupSuperFn;
508protected:
509 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
510 llvm::Value *&Receiver,
511 llvm::Value *cmd,
512 llvm::MDNode *node) {
513 CGBuilderTy &Builder = CGF.Builder;
514 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
515 EnforceType(Builder, Receiver, IdTy),
516 EnforceType(Builder, cmd, SelectorTy));
517 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
518 return imp;
519 }
520 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
521 llvm::Value *ObjCSuper,
522 llvm::Value *cmd) {
523 CGBuilderTy &Builder = CGF.Builder;
524 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
525 PtrToObjCSuperTy), cmd};
526 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
527 }
David Chisnalld7972f52011-03-23 16:36:54 +0000528 public:
David Chisnall76803412011-03-23 22:52:06 +0000529 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
530 // IMP objc_msg_lookup(id, SEL);
531 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
532 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
533 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
534 PtrToObjCSuperTy, SelectorTy, NULL);
535 }
David Chisnalld7972f52011-03-23 16:36:54 +0000536};
David Chisnall34d00052011-03-26 11:48:37 +0000537/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000538class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000539 /// The slot lookup function. Returns a pointer to a cacheable structure
540 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000541 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000542 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
543 /// a structure describing the receiver and the class, and a selector as
544 /// arguments. Returns the slot for the corresponding method. Superclass
545 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000546 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall34d00052011-03-26 11:48:37 +0000547 /// Type of an slot structure pointer. This is returned by the various
548 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000549 llvm::Type *SlotTy;
550 protected:
551 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
552 llvm::Value *&Receiver,
553 llvm::Value *cmd,
554 llvm::MDNode *node) {
555 CGBuilderTy &Builder = CGF.Builder;
556 llvm::Function *LookupFn = SlotLookupFn;
557
558 // Store the receiver on the stack so that we can reload it later
559 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
560 Builder.CreateStore(Receiver, ReceiverPtr);
561
562 llvm::Value *self;
563
564 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
565 self = CGF.LoadObjCSelf();
566 } else {
567 self = llvm::ConstantPointerNull::get(IdTy);
568 }
569
570 // The lookup function is guaranteed not to capture the receiver pointer.
571 LookupFn->setDoesNotCapture(1);
572
573 llvm::CallInst *slot =
574 Builder.CreateCall3(LookupFn,
575 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
576 EnforceType(Builder, cmd, SelectorTy),
577 EnforceType(Builder, self, IdTy));
578 slot->setOnlyReadsMemory();
579 slot->setMetadata(msgSendMDKind, node);
580
581 // Load the imp from the slot
582 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
583
584 // The lookup function may have changed the receiver, so make sure we use
585 // the new one.
586 Receiver = Builder.CreateLoad(ReceiverPtr, true);
587 return imp;
588 }
589 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
590 llvm::Value *ObjCSuper,
591 llvm::Value *cmd) {
592 CGBuilderTy &Builder = CGF.Builder;
593 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
594
595 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
596 lookupArgs+2);
597 slot->setOnlyReadsMemory();
598
599 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
600 }
David Chisnalld7972f52011-03-23 16:36:54 +0000601 public:
David Chisnall76803412011-03-23 22:52:06 +0000602 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
603 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
604 PtrTy, PtrTy, IntTy, IMPTy, NULL);
605 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
606 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
607 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
608 SelectorTy, IdTy, NULL);
609 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
610 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
611 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000612 // If we're in ObjC++ mode, then we want to make
613 if (CGM.getLangOptions().CPlusPlus) {
614 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
615 // void *__cxa_begin_catch(void *e)
616 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
617 // void __cxa_end_catch(void)
618 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
619 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnallec343e82011-04-05 17:15:18 +0000620 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000621 }
David Chisnall76803412011-03-23 22:52:06 +0000622 }
David Chisnalld7972f52011-03-23 16:36:54 +0000623};
624
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000625} // end anonymous namespace
626
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000627
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000628/// Emits a reference to a dummy variable which is emitted with each class.
629/// This ensures that a linker error will be generated when trying to link
630/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000631void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000632 std::string symbolRef = "__objc_class_ref_" + className;
633 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000634 if (TheModule.getGlobalVariable(symbolRef))
635 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000636 std::string symbolName = "__objc_class_name_" + className;
637 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
638 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000639 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
640 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000641 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000642 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000643 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000644}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000645
David Chisnalld7972f52011-03-23 16:36:54 +0000646static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
647 const llvm::StringRef &CategoryName, const Selector MethodName,
648 bool isClassMethod) {
649 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000650 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
651 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000652 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
653 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000654}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000655
David Chisnalld7972f52011-03-23 16:36:54 +0000656CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
657 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000658 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
659 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
660 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000661
662 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
663
David Chisnalld7972f52011-03-23 16:36:54 +0000664 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000665 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000666 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000667 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000668 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000669 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000670 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000671 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000672 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000673 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000674
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000675 Int8Ty = llvm::Type::getInt8Ty(VMContext);
676 // C string type. Used in lots of places.
677 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
678
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000679 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000680 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000681 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000682 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000683 QualType selTy = CGM.getContext().getObjCSelType();
684 if (QualType() == selTy) {
685 SelectorTy = PtrToInt8Ty;
686 } else {
687 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
688 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000689
Owen Anderson9793f0e2009-07-29 22:16:19 +0000690 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000691 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattner4bd55962008-03-30 23:03:07 +0000693 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000694 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
695 ASTIdTy = CanQualType();
696 if (UnqualIdTy != QualType()) {
697 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000698 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000699 } else {
700 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000701 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000702 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000703
David Chisnall76803412011-03-23 22:52:06 +0000704 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
705 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
706
David Chisnalld7972f52011-03-23 16:36:54 +0000707 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
708
709 // void objc_exception_throw(id);
710 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000711 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000712 // int objc_sync_enter(id);
713 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
714 // int objc_sync_exit(id);
715 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
716
717 // void objc_enumerationMutation (id)
718 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
719 IdTy, NULL);
720
721 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
722 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
723 PtrDiffTy, BoolTy, NULL);
724 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
725 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
726 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
727 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
728 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
729 PtrDiffTy, BoolTy, BoolTy, NULL);
730 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
731 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
732 PtrDiffTy, BoolTy, BoolTy, NULL);
733
Chris Lattner4bd55962008-03-30 23:03:07 +0000734 // IMP type
735 std::vector<const llvm::Type*> IMPArgs;
736 IMPArgs.push_back(IdTy);
737 IMPArgs.push_back(SelectorTy);
David Chisnall76803412011-03-23 22:52:06 +0000738 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
739 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000740
David Chisnalld3858d62011-03-25 11:57:33 +0000741 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000742 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000743 // This is a bit of an hack. We should sort this out by having a proper
744 // CGObjCGNUstep subclass for GC, but we may want to really support the old
745 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
746 RuntimeVersion = 10;
David Chisnall5bb4efd2010-02-03 15:59:02 +0000747 // Get selectors needed in GC mode
748 RetainSel = GetNullarySelector("retain", CGM.getContext());
749 ReleaseSel = GetNullarySelector("release", CGM.getContext());
750 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
751
752 // Get functions needed in GC mode
753
754 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000755 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
756 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000757 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000758 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
759 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000760 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000761 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
762 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000763 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000764 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000765 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000766 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000767 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000768 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
769 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000770 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000771}
Mike Stumpdd93a192009-07-31 21:31:32 +0000772
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000773// This has to perform the lookup every time, since posing and related
774// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000775llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000776 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000777 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000778 // With the incompatible ABI, this will need to be replaced with a direct
779 // reference to the class symbol. For the compatible nonfragile ABI we are
780 // still performing this lookup at run time but emitting the symbol for the
781 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000782 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000783 ClassName = Builder.CreateStructGEP(ClassName, 0);
784
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000785 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000786 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000787 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000788 Params,
789 true),
790 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000791 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000792}
793
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000794llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000795 const std::string &TypeEncoding, bool lval) {
796
797 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
798 llvm::GlobalAlias *SelValue = 0;
799
800
801 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
802 e = Types.end() ; i!=e ; i++) {
803 if (i->first == TypeEncoding) {
804 SelValue = i->second;
805 break;
806 }
807 }
808 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000809 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000810 llvm::GlobalValue::PrivateLinkage,
811 ".objc_selector_"+Sel.getAsString(), NULL,
812 &TheModule);
813 Types.push_back(TypedSelector(TypeEncoding, SelValue));
814 }
815
David Chisnall76803412011-03-23 22:52:06 +0000816 if (lval) {
817 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
818 Builder.CreateStore(SelValue, tmp);
819 return tmp;
820 }
821 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000822}
823
824llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
825 bool lval) {
826 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000827}
828
Daniel Dunbar45858d22010-02-03 20:11:42 +0000829llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000830 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000831 std::string SelTypes;
832 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000833 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000834}
835
John McCall2ca705e2010-07-24 00:37:23 +0000836llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000837 if (!CGM.getLangOptions().CPlusPlus) {
838 if (T->isObjCIdType()
839 || T->isObjCQualifiedIdType()) {
840 // With the old ABI, there was only one kind of catchall, which broke
841 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
842 // a pointer indicating object catchalls, and NULL to indicate real
843 // catchalls
844 if (CGM.getLangOptions().ObjCNonFragileABI) {
845 return MakeConstantString("@id");
846 } else {
847 return 0;
848 }
849 }
850
851 // All other types should be Objective-C interface pointer types.
852 const ObjCObjectPointerType *OPT =
853 T->getAs<ObjCObjectPointerType>();
854 assert(OPT && "Invalid @catch type.");
855 const ObjCInterfaceDecl *IDecl =
856 OPT->getObjectType()->getInterface();
857 assert(IDecl && "Invalid @catch type.");
858 return MakeConstantString(IDecl->getIdentifier()->getName());
859 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000860 // For Objective-C++, we want to provide the ability to catch both C++ and
861 // Objective-C objects in the same function.
862
863 // There's a particular fixed type info for 'id'.
864 if (T->isObjCIdType() ||
865 T->isObjCQualifiedIdType()) {
866 llvm::Constant *IDEHType =
867 CGM.getModule().getGlobalVariable("__objc_id_type_info");
868 if (!IDEHType)
869 IDEHType =
870 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
871 false,
872 llvm::GlobalValue::ExternalLinkage,
873 0, "__objc_id_type_info");
874 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
875 }
876
877 const ObjCObjectPointerType *PT =
878 T->getAs<ObjCObjectPointerType>();
879 assert(PT && "Invalid @catch type.");
880 const ObjCInterfaceType *IT = PT->getInterfaceType();
881 assert(IT && "Invalid @catch type.");
882 std::string className = IT->getDecl()->getIdentifier()->getName();
883
884 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
885
886 // Return the existing typeinfo if it exists
887 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
888 if (typeinfo) return typeinfo;
889
890 // Otherwise create it.
891
892 // vtable for gnustep::libobjc::__objc_class_type_info
893 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
894 // platform's name mangling.
895 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
896 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
897 if (!Vtable) {
898 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
899 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
900 }
901 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
902 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
903 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
904
905 llvm::Constant *typeName =
906 ExportUniqueString(className, "__objc_eh_typename_");
907
908 std::vector<llvm::Constant*> fields;
909 fields.push_back(Vtable);
910 fields.push_back(typeName);
911 llvm::Constant *TI =
912 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
913 NULL), fields, "__objc_eh_typeinfo_" + className,
914 llvm::GlobalValue::LinkOnceODRLinkage);
915 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000916}
917
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000918/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000919llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000920
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000921 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000922
David Chisnall358e7512010-01-27 12:49:23 +0000923 // Look for an existing one
924 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
925 if (old != ObjCStrings.end())
926 return old->getValue();
927
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000928 std::vector<llvm::Constant*> Ivars;
929 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000930 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000931 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000932 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000933 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000934 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000935 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
936 ObjCStrings[Str] = ObjCStr;
937 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000938 return ObjCStr;
939}
940
941///Generates a message send where the super is the receiver. This is a message
942///send to self with special delivery semantics indicating which class's method
943///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000944RValue
945CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000946 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000947 QualType ResultType,
948 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000949 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000950 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000951 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000952 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000953 const CallArgList &CallArgs,
954 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000955 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
956 if (Sel == RetainSel || Sel == AutoreleaseSel) {
957 return RValue::get(Receiver);
958 }
959 if (Sel == ReleaseSel) {
960 return RValue::get(0);
961 }
962 }
David Chisnallea529a42010-05-01 12:37:16 +0000963
964 CGBuilderTy &Builder = CGF.Builder;
965 llvm::Value *cmd = GetSelector(Builder, Sel);
966
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000967
968 CallArgList ActualArgs;
969
Eli Friedman43dca6a2011-05-02 17:57:46 +0000970 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
971 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000972 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
973
974 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000975 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000976 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000977
Daniel Dunbar566421c2009-05-04 15:31:17 +0000978 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000979 if (isCategoryImpl) {
980 llvm::Constant *classLookupFunction = 0;
981 std::vector<const llvm::Type*> Params;
982 Params.push_back(PtrTy);
983 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000984 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000985 IdTy, Params, true), "objc_get_meta_class");
986 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000987 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000988 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000989 }
David Chisnallea529a42010-05-01 12:37:16 +0000990 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000991 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000992 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000993 // Set up global aliases for the metaclass or class pointer if they do not
994 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000995 // pointers to the class and metaclass structure created for the runtime
996 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000997 // super_class pointer from either the class or metaclass structure.
998 if (IsClassMessage) {
999 if (!MetaClassPtrAlias) {
1000 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1001 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1002 Class->getNameAsString(), NULL, &TheModule);
1003 }
1004 ReceiverClass = MetaClassPtrAlias;
1005 } else {
1006 if (!ClassPtrAlias) {
1007 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1008 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1009 Class->getNameAsString(), NULL, &TheModule);
1010 }
1011 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001012 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001013 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001014 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001015 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001016 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +00001017 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001018 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001019 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001020 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001021 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001022 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +00001023 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
1024 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001025 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001026
David Chisnallea529a42010-05-01 12:37:16 +00001027 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1028 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001029
David Chisnall76803412011-03-23 22:52:06 +00001030 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1031 const llvm::FunctionType *impType =
1032 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1033
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001034 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001035 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1036 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001037
David Chisnall9eecafa2010-05-01 11:15:56 +00001038 llvm::Value *impMD[] = {
1039 llvm::MDString::get(VMContext, Sel.getAsString()),
1040 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1041 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1042 };
Jay Foadea324f12011-04-21 19:59:12 +00001043 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001044
David Chisnallff5f88c2010-05-02 13:41:58 +00001045 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001046 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001047 0, &call);
1048 call->setMetadata(msgSendMDKind, node);
1049 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001050}
1051
Mike Stump11289f42009-09-09 15:08:12 +00001052/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001053RValue
1054CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001055 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001056 QualType ResultType,
1057 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001058 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001059 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001060 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001061 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +00001062 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +00001063 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1064 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1065 return RValue::get(Receiver);
1066 }
1067 if (Sel == ReleaseSel) {
1068 return RValue::get(0);
1069 }
1070 }
David Chisnall75afda62010-04-27 15:08:48 +00001071
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001072 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +00001073
1074 // If the return type is something that goes in an integer register, the
1075 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1076 // ourselves.
1077 //
1078 // The language spec says the result of this kind of message send is
1079 // undefined, but lots of people seem to have forgotten to read that
1080 // paragraph and insist on sending messages to nil that have structure
1081 // returns. With GCC, this generates a random return value (whatever happens
1082 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001083 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1084 // the stack.
1085 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1086 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001087
1088 llvm::BasicBlock *startBB = 0;
1089 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001090 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001091
1092 if (!isPointerSizedReturn) {
1093 startBB = Builder.GetInsertBlock();
1094 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001095 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001096
1097 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1098 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001099 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001100 CGF.EmitBlock(messageBB);
1101 }
1102
David Chisnall9f57c292009-08-17 16:35:33 +00001103 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001104 llvm::Value *cmd;
1105 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001106 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001107 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001108 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001109 cmd = EnforceType(Builder, cmd, SelectorTy);
1110 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001111
David Chisnall76803412011-03-23 22:52:06 +00001112 llvm::Value *impMD[] = {
1113 llvm::MDString::get(VMContext, Sel.getAsString()),
1114 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1115 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1116 };
Jay Foadea324f12011-04-21 19:59:12 +00001117 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001118
1119 // Get the IMP to call
1120 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1121
1122 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001123 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1124 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001125 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1126
1127 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001128 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001129 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001130 const llvm::FunctionType *impType =
1131 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001132 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001133
1134
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001135 // For sender-aware dispatch, we pass the sender as the third argument to a
1136 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001137 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001138 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001139 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001140 0, &call);
1141 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001142
David Chisnall29cefd12010-05-20 13:45:48 +00001143
David Chisnall75afda62010-04-27 15:08:48 +00001144 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001145 messageBB = CGF.Builder.GetInsertBlock();
1146 CGF.Builder.CreateBr(continueBB);
1147 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001148 if (msgRet.isScalar()) {
1149 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001150 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001151 phi->addIncoming(v, messageBB);
1152 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1153 msgRet = RValue::get(phi);
1154 } else if (msgRet.isAggregate()) {
1155 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001156 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001157 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001158 llvm::AllocaInst *NullVal =
1159 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001160 CGF.InitTempAlloca(NullVal,
1161 llvm::Constant::getNullValue(RetTy->getElementType()));
1162 phi->addIncoming(v, messageBB);
1163 phi->addIncoming(NullVal, startBB);
1164 msgRet = RValue::getAggregate(phi);
1165 } else /* isComplex() */ {
1166 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001167 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001168 phi->addIncoming(v.first, messageBB);
1169 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1170 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001171 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001172 phi2->addIncoming(v.second, messageBB);
1173 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1174 startBB);
1175 msgRet = RValue::getComplex(phi, phi2);
1176 }
1177 }
1178 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001179}
1180
Mike Stump11289f42009-09-09 15:08:12 +00001181/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001182/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +00001183llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1184 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +00001185 const llvm::SmallVectorImpl<Selector> &MethodSels,
1186 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001187 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001188 if (MethodSels.empty())
1189 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001190 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001191 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001192 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1193 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001194 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001195 NULL);
1196 std::vector<llvm::Constant*> Methods;
1197 std::vector<llvm::Constant*> Elements;
1198 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1199 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001200 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001201 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001202 MethodSels[i],
1203 isClassMethodList));
1204 assert(Method && "Can't generate metadata for method that doesn't exist");
1205 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1206 Elements.push_back(C);
1207 Elements.push_back(MethodTypes[i]);
1208 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001209 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001210 Elements.push_back(Method);
1211 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001212 }
1213
1214 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001215 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001216 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001217 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001218 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001219
1220 // Structure containing list pointer, array and array count
1221 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001222 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001223 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001224 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001225 NextPtrTy,
1226 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001227 ObjCMethodArrayTy,
1228 NULL);
1229 // Refine next pointer type to concrete type
1230 llvm::cast<llvm::OpaqueType>(
1231 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1232 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1233
1234 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001235 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001236 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001237 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001238 MethodTypes.size()));
1239 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001241 // Create an instance of the structure
1242 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1243}
1244
1245/// Generates an IvarList. Used in construction of a objc_class.
1246llvm::Constant *CGObjCGNU::GenerateIvarList(
1247 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1248 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1249 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001250 if (IvarNames.size() == 0)
1251 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001252 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001253 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001254 PtrToInt8Ty,
1255 PtrToInt8Ty,
1256 IntTy,
1257 NULL);
1258 std::vector<llvm::Constant*> Ivars;
1259 std::vector<llvm::Constant*> Elements;
1260 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1261 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001262 Elements.push_back(IvarNames[i]);
1263 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001264 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001265 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001266 }
1267
1268 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001269 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001270 IvarNames.size());
1271
Mike Stump11289f42009-09-09 15:08:12 +00001272
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001273 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001274 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001275 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001276 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001277 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001278 ObjCIvarArrayTy,
1279 NULL);
1280
1281 // Create an instance of the structure
1282 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1283}
1284
1285/// Generate a class structure
1286llvm::Constant *CGObjCGNU::GenerateClassStructure(
1287 llvm::Constant *MetaClass,
1288 llvm::Constant *SuperClass,
1289 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001290 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001291 llvm::Constant *Version,
1292 llvm::Constant *InstanceSize,
1293 llvm::Constant *IVars,
1294 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001295 llvm::Constant *Protocols,
1296 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001297 llvm::Constant *Properties,
1298 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001299 // Set up the class structure
1300 // Note: Several of these are char*s when they should be ids. This is
1301 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001302 //
1303 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1304 // anyway; the classes will still work with the GNU runtime, they will just
1305 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001306 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001307 PtrToInt8Ty, // class_pointer
1308 PtrToInt8Ty, // super_class
1309 PtrToInt8Ty, // name
1310 LongTy, // version
1311 LongTy, // info
1312 LongTy, // instance_size
1313 IVars->getType(), // ivars
1314 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001315 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001316 PtrTy, // dtable
1317 PtrTy, // subclass_list
1318 PtrTy, // sibling_class
1319 PtrTy, // protocols
1320 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001321 // New ABI:
1322 LongTy, // abi_version
1323 IvarOffsets->getType(), // ivar_offsets
1324 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001325 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001326 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001327 // Fill in the structure
1328 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001329 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001330 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001331 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001332 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001333 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001334 if (isMeta) {
1335 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001336 Elements.push_back(
1337 llvm::ConstantInt::get(LongTy,
1338 td.getTypeSizeInBits(ClassTy) /
1339 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001340 } else
1341 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001342 Elements.push_back(IVars);
1343 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001344 Elements.push_back(NULLPtr);
1345 Elements.push_back(NULLPtr);
1346 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001347 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001348 Elements.push_back(NULLPtr);
1349 Elements.push_back(Zero);
1350 Elements.push_back(IvarOffsets);
1351 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001352 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001353 // This is now an externally visible symbol, so that we can speed up class
1354 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001355 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1356 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001357}
1358
1359llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1360 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1361 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001362 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001363 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001364 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1365 PtrToInt8Ty,
1366 NULL);
1367 std::vector<llvm::Constant*> Methods;
1368 std::vector<llvm::Constant*> Elements;
1369 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1370 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001371 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001372 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001373 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001374 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001375 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001376 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001377 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001378 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001379 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001380 IntTy, ObjCMethodArrayTy, NULL);
1381 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001382 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001383 Methods.push_back(Array);
1384 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1385}
Mike Stumpdd93a192009-07-31 21:31:32 +00001386
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001387// Create the protocol list structure used in classes, categories and so on
1388llvm::Constant *CGObjCGNU::GenerateProtocolList(
1389 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001390 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001391 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001392 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001393 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001394 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001395 ProtocolArrayTy,
1396 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001397 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001398 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1399 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001400 llvm::Constant *protocol = 0;
1401 llvm::StringMap<llvm::Constant*>::iterator value =
1402 ExistingProtocols.find(*iter);
1403 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001404 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001405 } else {
1406 protocol = value->getValue();
1407 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001408 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001409 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001410 Elements.push_back(Ptr);
1411 }
Owen Anderson47034e12009-07-28 18:33:04 +00001412 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001413 Elements);
1414 Elements.clear();
1415 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001416 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001417 Elements.push_back(ProtocolArray);
1418 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1419}
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001422 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001423 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001424 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001425 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001426 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001427}
1428
1429llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1430 const std::string &ProtocolName) {
1431 llvm::SmallVector<std::string, 0> EmptyStringVector;
1432 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1433
1434 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001435 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001436 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1437 // Protocols are objects containing lists of the methods implemented and
1438 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001439 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001440 PtrToInt8Ty,
1441 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001442 MethodList->getType(),
1443 MethodList->getType(),
1444 MethodList->getType(),
1445 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001446 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001447 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001448 // The isa pointer must be set to a magic number so the runtime knows it's
1449 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001450 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001451 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1452 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001453 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1454 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001455 Elements.push_back(MethodList);
1456 Elements.push_back(MethodList);
1457 Elements.push_back(MethodList);
1458 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001459 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001460}
1461
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001462void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1463 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001464 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001465 llvm::SmallVector<std::string, 16> Protocols;
1466 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1467 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001468 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001469 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1470 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001471 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1472 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001473 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1474 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001475 std::string TypeStr;
1476 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001477 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1478 InstanceMethodNames.push_back(
1479 MakeConstantString((*iter)->getSelector().getAsString()));
1480 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1481 } else {
1482 OptionalInstanceMethodNames.push_back(
1483 MakeConstantString((*iter)->getSelector().getAsString()));
1484 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1485 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001486 }
1487 // Collect information about class methods:
1488 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1489 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001490 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1491 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001492 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001493 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1494 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001495 std::string TypeStr;
1496 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001497 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1498 ClassMethodNames.push_back(
1499 MakeConstantString((*iter)->getSelector().getAsString()));
1500 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1501 } else {
1502 OptionalClassMethodNames.push_back(
1503 MakeConstantString((*iter)->getSelector().getAsString()));
1504 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1505 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001506 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001507
1508 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1509 llvm::Constant *InstanceMethodList =
1510 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1511 llvm::Constant *ClassMethodList =
1512 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001513 llvm::Constant *OptionalInstanceMethodList =
1514 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1515 OptionalInstanceMethodTypes);
1516 llvm::Constant *OptionalClassMethodList =
1517 GenerateProtocolMethodList(OptionalClassMethodNames,
1518 OptionalClassMethodTypes);
1519
1520 // Property metadata: name, attributes, isSynthesized, setter name, setter
1521 // types, getter name, getter types.
1522 // The isSynthesized value is always set to 0 in a protocol. It exists to
1523 // simplify the runtime library by allowing it to use the same data
1524 // structures for protocol metadata everywhere.
1525 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1526 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1527 PtrToInt8Ty, NULL);
1528 std::vector<llvm::Constant*> Properties;
1529 std::vector<llvm::Constant*> OptionalProperties;
1530
1531 // Add all of the property methods need adding to the method list and to the
1532 // property metadata list.
1533 for (ObjCContainerDecl::prop_iterator
1534 iter = PD->prop_begin(), endIter = PD->prop_end();
1535 iter != endIter ; iter++) {
1536 std::vector<llvm::Constant*> Fields;
1537 ObjCPropertyDecl *property = (*iter);
1538
1539 Fields.push_back(MakeConstantString(property->getNameAsString()));
1540 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1541 property->getPropertyAttributes()));
1542 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1543 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1544 std::string TypeStr;
1545 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1546 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1547 InstanceMethodTypes.push_back(TypeEncoding);
1548 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1549 Fields.push_back(TypeEncoding);
1550 } else {
1551 Fields.push_back(NULLPtr);
1552 Fields.push_back(NULLPtr);
1553 }
1554 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1555 std::string TypeStr;
1556 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1557 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1558 InstanceMethodTypes.push_back(TypeEncoding);
1559 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1560 Fields.push_back(TypeEncoding);
1561 } else {
1562 Fields.push_back(NULLPtr);
1563 Fields.push_back(NULLPtr);
1564 }
1565 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1566 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1567 } else {
1568 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1569 }
1570 }
1571 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1572 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1573 llvm::Constant* PropertyListInitFields[] =
1574 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1575
1576 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001577 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001578 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1579 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1580 PropertyListInit, ".objc_property_list");
1581
1582 llvm::Constant *OptionalPropertyArray =
1583 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1584 OptionalProperties.size()) , OptionalProperties);
1585 llvm::Constant* OptionalPropertyListInitFields[] = {
1586 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1587 OptionalPropertyArray };
1588
1589 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001590 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001591 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1592 OptionalPropertyListInit->getType(), false,
1593 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1594 ".objc_property_list");
1595
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001596 // Protocols are objects containing lists of the methods implemented and
1597 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001598 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001599 PtrToInt8Ty,
1600 ProtocolList->getType(),
1601 InstanceMethodList->getType(),
1602 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001603 OptionalInstanceMethodList->getType(),
1604 OptionalClassMethodList->getType(),
1605 PropertyList->getType(),
1606 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001607 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001608 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001609 // The isa pointer must be set to a magic number so the runtime knows it's
1610 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001611 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001612 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1613 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001614 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1615 Elements.push_back(ProtocolList);
1616 Elements.push_back(InstanceMethodList);
1617 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001618 Elements.push_back(OptionalInstanceMethodList);
1619 Elements.push_back(OptionalClassMethodList);
1620 Elements.push_back(PropertyList);
1621 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001622 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001623 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001624 ".objc_protocol"), IdTy);
1625}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001626void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1627 // Collect information about instance methods
1628 llvm::SmallVector<Selector, 1> MethodSels;
1629 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1630
1631 std::vector<llvm::Constant*> Elements;
1632 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1633 const std::string CategoryName = "AnotherHack";
1634 Elements.push_back(MakeConstantString(CategoryName));
1635 Elements.push_back(MakeConstantString(ClassName));
1636 // Instance method list
1637 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1638 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1639 // Class method list
1640 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1641 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1642 // Protocol list
1643 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1644 ExistingProtocols.size());
1645 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1646 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001647 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001648 ProtocolArrayTy,
1649 NULL);
1650 std::vector<llvm::Constant*> ProtocolElements;
1651 for (llvm::StringMapIterator<llvm::Constant*> iter =
1652 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1653 iter != endIter ; iter++) {
1654 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1655 PtrTy);
1656 ProtocolElements.push_back(Ptr);
1657 }
1658 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1659 ProtocolElements);
1660 ProtocolElements.clear();
1661 ProtocolElements.push_back(NULLPtr);
1662 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1663 ExistingProtocols.size()));
1664 ProtocolElements.push_back(ProtocolArray);
1665 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1666 ProtocolElements, ".objc_protocol_list"), PtrTy));
1667 Categories.push_back(llvm::ConstantExpr::getBitCast(
1668 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1669 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1670}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001671
Daniel Dunbar92992502008-08-15 22:20:32 +00001672void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001673 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1674 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001675 // Collect information about instance methods
1676 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1677 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001678 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001679 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001680 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001681 InstanceMethodSels.push_back((*iter)->getSelector());
1682 std::string TypeStr;
1683 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001684 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001685 }
1686
1687 // Collect information about class methods
1688 llvm::SmallVector<Selector, 16> ClassMethodSels;
1689 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001690 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001691 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001692 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001693 ClassMethodSels.push_back((*iter)->getSelector());
1694 std::string TypeStr;
1695 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001696 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001697 }
1698
1699 // Collect the names of referenced protocols
1700 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001701 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1702 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001703 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1704 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001705 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001706
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001707 std::vector<llvm::Constant*> Elements;
1708 Elements.push_back(MakeConstantString(CategoryName));
1709 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001710 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001711 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001712 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001713 false), PtrTy));
1714 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001715 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001716 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001717 PtrTy));
1718 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001719 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001720 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001721 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001722 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001723 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001724}
Daniel Dunbar92992502008-08-15 22:20:32 +00001725
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001726llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1727 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1728 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1729 ASTContext &Context = CGM.getContext();
1730 //
1731 // Property metadata: name, attributes, isSynthesized, setter name, setter
1732 // types, getter name, getter types.
1733 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1734 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1735 PtrToInt8Ty, NULL);
1736 std::vector<llvm::Constant*> Properties;
1737
1738
1739 // Add all of the property methods need adding to the method list and to the
1740 // property metadata list.
1741 for (ObjCImplDecl::propimpl_iterator
1742 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1743 iter != endIter ; iter++) {
1744 std::vector<llvm::Constant*> Fields;
1745 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001746 ObjCPropertyImplDecl *propertyImpl = *iter;
1747 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1748 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001749
1750 Fields.push_back(MakeConstantString(property->getNameAsString()));
1751 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1752 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001753 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001754 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001755 std::string TypeStr;
1756 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1757 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001758 if (isSynthesized) {
1759 InstanceMethodTypes.push_back(TypeEncoding);
1760 InstanceMethodSels.push_back(getter->getSelector());
1761 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001762 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1763 Fields.push_back(TypeEncoding);
1764 } else {
1765 Fields.push_back(NULLPtr);
1766 Fields.push_back(NULLPtr);
1767 }
1768 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001769 std::string TypeStr;
1770 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1771 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001772 if (isSynthesized) {
1773 InstanceMethodTypes.push_back(TypeEncoding);
1774 InstanceMethodSels.push_back(setter->getSelector());
1775 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001776 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1777 Fields.push_back(TypeEncoding);
1778 } else {
1779 Fields.push_back(NULLPtr);
1780 Fields.push_back(NULLPtr);
1781 }
1782 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1783 }
1784 llvm::ArrayType *PropertyArrayTy =
1785 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1786 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1787 Properties);
1788 llvm::Constant* PropertyListInitFields[] =
1789 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1790
1791 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001792 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001793 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1794 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1795 ".objc_property_list");
1796}
1797
Daniel Dunbar92992502008-08-15 22:20:32 +00001798void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1799 ASTContext &Context = CGM.getContext();
1800
1801 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001802 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001803 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001804 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001805 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001806 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001807 EmitClassRef(SuperClassName);
1808 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001809
1810 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001811 ObjCInterfaceDecl *ClassDecl =
1812 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001813 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001814 // Emit the symbol that is used to generate linker errors if this class is
1815 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001816 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001817 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001818 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001819 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001820 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001821 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001822 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001823 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Daniel Dunbar12119b92009-05-03 10:46:44 +00001826 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001827 int instanceSize =
1828 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001829
1830 // Collect information about instance variables.
1831 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1832 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1833 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001834
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001835 std::vector<llvm::Constant*> IvarOffsetValues;
1836
Mike Stump11289f42009-09-09 15:08:12 +00001837 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001838 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001839 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1840 // class}. The runtime will then set this to the correct value on load.
1841 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1842 instanceSize = 0 - (instanceSize - superInstanceSize);
1843 }
David Chisnall18cf7372010-04-19 00:45:34 +00001844
1845 // Collect declared and synthesized ivars.
1846 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1847 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1848
1849 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1850 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001851 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001852 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001853 // Get the type encoding for this ivar
1854 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001855 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001856 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001857 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001858 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001859 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001860 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001861 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001862 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001863 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001864 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001865 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1866 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00001867 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001868 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001869 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001870 }
David Chisnalld7972f52011-03-23 16:36:54 +00001871 llvm::GlobalVariable *IvarOffsetArray =
1872 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1873
Daniel Dunbar92992502008-08-15 22:20:32 +00001874
1875 // Collect information about instance methods
1876 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1877 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001878 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001879 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001880 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001881 InstanceMethodSels.push_back((*iter)->getSelector());
1882 std::string TypeStr;
1883 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001884 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001885 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001886
1887 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1888 InstanceMethodTypes);
1889
Daniel Dunbar92992502008-08-15 22:20:32 +00001890
1891 // Collect information about class methods
1892 llvm::SmallVector<Selector, 16> ClassMethodSels;
1893 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001894 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001895 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001896 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001897 ClassMethodSels.push_back((*iter)->getSelector());
1898 std::string TypeStr;
1899 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001900 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001901 }
1902 // Collect the names of referenced protocols
1903 llvm::SmallVector<std::string, 16> Protocols;
1904 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1905 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1906 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001907 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001908
1909
1910
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001911 // Get the superclass pointer.
1912 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001913 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001914 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1915 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001916 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001917 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001918 // Empty vector used to construct empty method lists
1919 llvm::SmallVector<llvm::Constant*, 1> empty;
1920 // Generate the method and instance variable lists
1921 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001922 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001923 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001924 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001925 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1926 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001927 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001928 // we emit a symbol containing the offset for each ivar in the class. This
1929 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1930 // for the legacy ABI, without causing problems. The converse is also
1931 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001932
David Chisnall5778fce2009-08-31 16:41:57 +00001933 // Offset pointer for getting at the correct field in the ivar list when
1934 // setting up the alias. These are: The base address for the global, the
1935 // ivar array (second field), the ivar in this list (set for each ivar), and
1936 // the offset (third field in ivar structure)
1937 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1938 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001939 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001940 llvm::ConstantInt::get(IndexTy, 2) };
1941
David Chisnalle8431a72010-11-03 16:12:44 +00001942
1943 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1944 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00001945 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001946 + IVD->getNameAsString();
1947 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00001948 // Get the correct ivar field
1949 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1950 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00001951 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001952 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1953 if (offset) {
1954 offset->setInitializer(offsetValue);
1955 // If this is the real definition, change its linkage type so that
1956 // different modules will use this one, rather than their private
1957 // copy.
1958 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1959 } else {
1960 // Add a new alias if there isn't one already.
1961 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1962 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1963 }
1964 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001965 //Generate metaclass for class methods
1966 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001967 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001968 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001969
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001970 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001971 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001972 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001973 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001974 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001975 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1976 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001977
1978 // Resolve the class aliases, if they exist.
1979 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001980 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001981 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001982 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001983 ClassPtrAlias = 0;
1984 }
1985 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001986 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001987 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001988 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001989 MetaClassPtrAlias = 0;
1990 }
1991
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001992 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001993 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001994 Classes.push_back(ClassStruct);
1995}
1996
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001997
Mike Stump11289f42009-09-09 15:08:12 +00001998llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001999 // Only emit an ObjC load function if no Objective-C stuff has been called
2000 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002001 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002002 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002003
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002004 // Add all referenced protocols to a category.
2005 GenerateProtocolHolderCategory();
2006
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002007 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2008 SelectorTy->getElementType());
2009 const llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002010 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00002011 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
2012 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002013 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002014 }
2015
Eli Friedman412c6682008-06-01 16:00:02 +00002016 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002017 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00002018 TheModule.addTypeName(".objc_id", IdTy);
2019 TheModule.addTypeName(".objc_imp", IMPTy);
2020
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002021 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002022 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002023 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002024 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002025 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002026 ConstantStrings.size() + 1);
2027 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002028
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002029 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002030
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002031 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002032
David Chisnall5778fce2009-08-31 16:41:57 +00002033 Elements.push_back(MakeConstantString(StringClass,
2034 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002035 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002036 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002037 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00002038 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002039 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002040 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002041 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002042 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002043 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002044 Elements.clear();
2045 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002046 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002047 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002048 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002049 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002050 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002051 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002052 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00002053 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00002054 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002055 llvm::Type::getInt16Ty(VMContext),
2056 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002057 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002058
2059 Elements.clear();
2060 // Pointer to an array of selectors used in this module.
2061 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002062 std::vector<llvm::GlobalAlias*> SelectorAliases;
2063 for (SelectorMap::iterator iter = SelectorTable.begin(),
2064 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2065
2066 std::string SelNameStr = iter->first.getAsString();
2067 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2068
2069 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2070 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2071 e = Types.end() ; i!=e ; i++) {
2072
2073 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2074 if (!i->first.empty())
2075 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2076
2077 Elements.push_back(SelName);
2078 Elements.push_back(SelectorTypeEncoding);
2079 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2080 Elements.clear();
2081
2082 // Store the selector alias for later replacement
2083 SelectorAliases.push_back(i->second);
2084 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002085 }
David Chisnalld7972f52011-03-23 16:36:54 +00002086 unsigned SelectorCount = Selectors.size();
2087 // NULL-terminate the selector list. This should not actually be required,
2088 // because the selector list has a length field. Unfortunately, the GCC
2089 // runtime decides to ignore the length field and expects a NULL terminator,
2090 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002091 Elements.push_back(NULLPtr);
2092 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002093 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002094 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002095
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002096 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002097 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2098 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002099 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002100 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002101 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002102
2103 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002104 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2105
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002106 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00002107 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2108 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002109 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2110 Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002111 // If selectors are defined as an opaque type, cast the pointer to this
2112 // type.
David Chisnall76803412011-03-23 22:52:06 +00002113 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002114 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2115 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002116 }
David Chisnalld7972f52011-03-23 16:36:54 +00002117
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002118 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002119 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002120 Classes.size()));
2121 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002122 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002123 Categories.size()));
2124 // Create an array of classes, then categories, then static object instances
2125 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2126 // NULL-terminated list of static object instances (mainly constant strings)
2127 Classes.push_back(Statics);
2128 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002129 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002130 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002131 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002132 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2133
2134 // The symbol table is contained in a module which has some version-checking
2135 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00002136 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002137 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2138 (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) ? NULL : IntTy,
2139 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002140 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002141 // Runtime version, used for ABI compatibility checking.
2142 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002143 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002144 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002145 Elements.push_back(
2146 llvm::ConstantInt::get(LongTy,
2147 td.getTypeSizeInBits(ModuleTy) /
2148 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002149
2150 // The path to the source file where this module was declared
2151 SourceManager &SM = CGM.getContext().getSourceManager();
2152 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2153 std::string path =
2154 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2155 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002156 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002157
2158 switch (CGM.getLangOptions().getGCMode()) {
2159 case LangOptions::GCOnly:
2160 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2161 case LangOptions::NonGC:
2162 break;
2163 case LangOptions::HybridGC:
2164 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2165 }
2166
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002167 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2168
2169 // Create the load function calling the runtime entry point with the module
2170 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002171 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002172 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002173 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2174 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002175 llvm::BasicBlock *EntryBB =
2176 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002177 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002178 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002179
2180 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002181 llvm::PointerType::getUnqual(ModuleTy));
2182 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00002183 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002184 Builder.CreateCall(Register, Module);
2185 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002186
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002187 return LoadFunction;
2188}
Daniel Dunbar92992502008-08-15 22:20:32 +00002189
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002190llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002191 const ObjCContainerDecl *CD) {
2192 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002193 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00002194 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2195 llvm::StringRef ClassName = CD->getName();
2196 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002197 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002198
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002199 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00002200 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002201 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002202 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2203 MethodName, isClassMethod);
2204
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002205 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002206 = llvm::Function::Create(MethodTy,
2207 llvm::GlobalValue::InternalLinkage,
2208 FunctionName,
2209 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002210 return Method;
2211}
2212
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002213llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002214 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002215}
2216
2217llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002218 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002219}
2220
David Chisnall168b80f2010-12-26 22:13:16 +00002221llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002222 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002223}
2224llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002225 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002226}
2227
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002228llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002229 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002230}
2231
David Chisnalld7972f52011-03-23 16:36:54 +00002232void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002233 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002234 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002235}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002236
David Chisnall3a509cd2009-12-24 02:26:34 +00002237
David Chisnalld7972f52011-03-23 16:36:54 +00002238void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002239 const ObjCAtTryStmt &S) {
2240 // Unlike the Apple non-fragile runtimes, which also uses
2241 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2242 // EH support isn't a veneer over C++ EH. Instead, exception
2243 // objects are created by __objc_exception_throw and destroyed by
2244 // the personality function; this avoids the need for bracketing
2245 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2246 // (or even _Unwind_DeleteException), but probably doesn't
2247 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002248 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002249 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002250 // exception handler.
2251 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2252 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002253}
2254
David Chisnalld7972f52011-03-23 16:36:54 +00002255void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002256 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002257 llvm::Value *ExceptionAsObject;
2258
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002259 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2260 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002261 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002262 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002263 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002264 "Unexpected rethrow outside @catch block.");
2265 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2266 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002267 ExceptionAsObject =
2268 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002270 // Note: This may have to be an invoke, if we want to support constructs like:
2271 // @try {
2272 // @throw(obj);
2273 // }
2274 // @catch(id) ...
2275 //
2276 // This is effectively turning @throw into an incredibly-expensive goto, but
2277 // it may happen as a result of inlining followed by missed optimizations, or
2278 // as a result of stupidity.
2279 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2280 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002281 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002282 CGF.Builder.CreateUnreachable();
2283 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002284 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002285 &ExceptionAsObject+1);
2286 }
2287 // Clear the insertion point to indicate we are in unreachable code.
2288 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002289}
2290
David Chisnalld7972f52011-03-23 16:36:54 +00002291llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002292 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002293 CGBuilderTy B = CGF.Builder;
2294 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2295 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002296}
2297
David Chisnalld7972f52011-03-23 16:36:54 +00002298void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002299 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002300 CGBuilderTy B = CGF.Builder;
2301 src = EnforceType(B, src, IdTy);
2302 dst = EnforceType(B, dst, PtrToIdTy);
2303 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002304}
2305
David Chisnalld7972f52011-03-23 16:36:54 +00002306void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002307 llvm::Value *src, llvm::Value *dst,
2308 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002309 CGBuilderTy B = CGF.Builder;
2310 src = EnforceType(B, src, IdTy);
2311 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002312 if (!threadlocal)
2313 B.CreateCall2(GlobalAssignFn, src, dst);
2314 else
2315 // FIXME. Add threadloca assign API
2316 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002317}
2318
David Chisnalld7972f52011-03-23 16:36:54 +00002319void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002320 llvm::Value *src, llvm::Value *dst,
2321 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002322 CGBuilderTy B = CGF.Builder;
2323 src = EnforceType(B, src, IdTy);
2324 dst = EnforceType(B, dst, PtrToIdTy);
2325 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002326}
2327
David Chisnalld7972f52011-03-23 16:36:54 +00002328void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002329 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002330 CGBuilderTy B = CGF.Builder;
2331 src = EnforceType(B, src, IdTy);
2332 dst = EnforceType(B, dst, PtrToIdTy);
2333 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002334}
2335
David Chisnalld7972f52011-03-23 16:36:54 +00002336void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002337 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002338 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002339 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002340 CGBuilderTy B = CGF.Builder;
2341 DestPtr = EnforceType(B, DestPtr, IdTy);
2342 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2343
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002344 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002345}
2346
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002347llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2348 const ObjCInterfaceDecl *ID,
2349 const ObjCIvarDecl *Ivar) {
2350 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2351 + '.' + Ivar->getNameAsString();
2352 // Emit the variable and initialize it with what we think the correct value
2353 // is. This allows code compiled with non-fragile ivars to work correctly
2354 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002355 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2356 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002357 // This will cause a run-time crash if we accidentally use it. A value of
2358 // 0 would seem more sensible, but will silently overwrite the isa pointer
2359 // causing a great deal of confusion.
2360 uint64_t Offset = -1;
2361 // We can't call ComputeIvarBaseOffset() here if we have the
2362 // implementation, because it will create an invalid ASTRecordLayout object
2363 // that we are then stuck with forever, so we only initialize the ivar
2364 // offset variable with a guess if we only have the interface. The
2365 // initializer will be reset later anyway, when we are generating the class
2366 // description.
2367 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002368 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002369 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2370
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002371 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002372 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002373 // Don't emit the guess in non-PIC code because the linker will not be able
2374 // to replace it with the real version for a library. In non-PIC code you
2375 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002376 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002377 if (CGM.getLangOptions().PICLevel) {
2378 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2379 llvm::Type::getInt32Ty(VMContext), false,
2380 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2381 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2382 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2383 IvarOffsetGV, Name);
2384 } else {
2385 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002386 llvm::Type::getInt32PtrTy(VMContext), false,
2387 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002388 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002389 }
David Chisnall5778fce2009-08-31 16:41:57 +00002390 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002391}
2392
David Chisnalld7972f52011-03-23 16:36:54 +00002393LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002394 QualType ObjectTy,
2395 llvm::Value *BaseValue,
2396 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002397 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002398 const ObjCInterfaceDecl *ID =
2399 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002400 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2401 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002402}
Mike Stumpdd93a192009-07-31 21:31:32 +00002403
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002404static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2405 const ObjCInterfaceDecl *OID,
2406 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002407 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002408 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002409 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2410 if (OIVD == Ivars[k])
2411 return OID;
2412 }
Mike Stump11289f42009-09-09 15:08:12 +00002413
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002414 // Otherwise check in the super class.
2415 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2416 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002417
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002418 return 0;
2419}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002420
David Chisnalld7972f52011-03-23 16:36:54 +00002421llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002422 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002423 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002424 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002425 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002426 return CGF.Builder.CreateZExtOrBitCast(
2427 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2428 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2429 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002430 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002431 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002432 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002433}
2434
David Chisnalld7972f52011-03-23 16:36:54 +00002435CGObjCRuntime *
2436clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2437 if (CGM.getLangOptions().ObjCNonFragileABI)
2438 return new CGObjCGNUstep(CGM);
2439 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002440}