blob: ae8a8dd58f5c6c277a29eda5b6e37833f45a2609 [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCall36f893c2011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000021
Chris Lattnerdce14062008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnall80558d22011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000038
Chris Lattner5f9e2722011-07-23 10:55:15 +000039#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000040
41
Chris Lattnerdce14062008-06-26 04:19:03 +000042using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000043using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000044
Chris Lattner0f984262008-03-01 08:50:34 +000045
Chris Lattner0f984262008-03-01 08:50:34 +000046namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000047/// Class that lazily initialises the runtime function. Avoids inserting the
48/// types and the function declaration into a module if they're not used, and
49/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000050class LazyRuntimeFunction {
51 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000052 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000053 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000054 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000055 public:
David Chisnall81a65f52011-03-26 11:48:37 +000056 /// Constructor leaves this class uninitialized, because it is intended to
57 /// be used as a field in another class and not all of the types that are
58 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000059 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60
David Chisnall81a65f52011-03-26 11:48:37 +000061 /// Initialises the lazy function with the name, return type, and the types
62 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000063 END_WITH_NULL
64 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000065 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000066 CGM =Mod;
67 FunctionName = name;
68 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000069 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000070 va_list Args;
71 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000072 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000073 ArgTys.push_back(ArgTy);
74 va_end(Args);
75 // Push the return type on at the end so we can pop it off easily
76 ArgTys.push_back(RetTy);
77 }
David Chisnall81a65f52011-03-26 11:48:37 +000078 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000080 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000081 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000082 if (0 == FunctionName) return 0;
83 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000084 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000085 ArgTys.pop_back();
86 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000088 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000089 // We won't need to use the types again, so we may as well clean up the
90 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000091 ArgTys.resize(0);
92 }
93 return Function;
94 }
David Chisnall789ecde2011-05-23 22:33:28 +000095 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000096 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000097 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000098
David Chisnall9f6614e2011-03-23 16:36:54 +000099};
100
101
David Chisnall81a65f52011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
103/// Objective-C support that are specific to the GNU family of runtimes (GCC and
104/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000106protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000107 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000108 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000109 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000110 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000111 /// strut objc_super. Used for sending messages to super. This structure
112 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000113 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000114 /// struct objc_super*. The type of the argument to the superclass message
115 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000116 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000117 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
118 /// SEL is included in a header somewhere, in which case it will be whatever
119 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000120 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000121 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
122 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000123 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000124 /// Pointer to i8 - LLVM type of char*, for all of the places where the
125 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000126 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000127 /// Instance Method Pointer type. This is a pointer to a function that takes,
128 /// at a minimum, an object and a selector, and is the generic type for
129 /// Objective-C methods. Due to differences between variadic / non-variadic
130 /// calling conventions, it must always be cast to the correct type before
131 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000132 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000133 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
134 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
135 /// but if the runtime header declaring it is included then it may be a
136 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000137 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000138 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
139 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000140 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// The clang type of id. Used when using the clang CGCall infrastructure to
142 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000143 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000144 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000145 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000146 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
147 /// used in the code to document the difference between i8* meaning a pointer
148 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000149 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000150 /// LLVM type for C long type. The runtime uses this in a lot of places where
151 /// it should be using intptr_t, but we can't fix this without breaking
152 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000153 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000154 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000155 llvm::IntegerType *SizeTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000156 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000157 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000158 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
159 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000160 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000161 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000162 llvm::Type *BoolTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000163 /// Metadata kind used to tie method lookups to message sends. The GNUstep
164 /// runtime provides some LLVM passes that can use this to do things like
165 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000166 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000167 /// Helper function that generates a constant string and returns a pointer to
168 /// the start of the string. The result of this function can be used anywhere
169 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000170 llvm::Constant *MakeConstantString(const std::string &Str,
171 const std::string &Name="") {
172 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000173 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000174 }
David Chisnall81a65f52011-03-26 11:48:37 +0000175 /// Emits a linkonce_odr string, whose name is the prefix followed by the
176 /// string value. This allows the linker to combine the strings between
177 /// different modules. Used for EH typeinfo names, selector strings, and a
178 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000179 llvm::Constant *ExportUniqueString(const std::string &Str,
180 const std::string prefix) {
181 std::string name = prefix + Str;
182 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
183 if (!ConstStr) {
184 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
185 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
186 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
187 }
Jay Foada5c04342011-07-21 14:31:17 +0000188 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000189 }
David Chisnall81a65f52011-03-26 11:48:37 +0000190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
192 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000193 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000194 std::vector<llvm::Constant*> &V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000195 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000196 llvm::GlobalValue::LinkageTypes linkage
197 =llvm::GlobalValue::InternalLinkage) {
198 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
199 return new llvm::GlobalVariable(TheModule, Ty, false,
200 linkage, C, Name);
201 }
David Chisnall81a65f52011-03-26 11:48:37 +0000202 /// Generates a global array. The vector must contain the same number of
203 /// elements that the array type declares, of the type specified as the array
204 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000205 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000206 std::vector<llvm::Constant*> &V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000207 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000208 llvm::GlobalValue::LinkageTypes linkage
209 =llvm::GlobalValue::InternalLinkage) {
210 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
211 return new llvm::GlobalVariable(TheModule, Ty, false,
212 linkage, C, Name);
213 }
David Chisnall81a65f52011-03-26 11:48:37 +0000214 /// Generates a global array, inferring the array type from the specified
215 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000216 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000217 std::vector<llvm::Constant*> &V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000218 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000219 llvm::GlobalValue::LinkageTypes linkage
220 =llvm::GlobalValue::InternalLinkage) {
221 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
222 return MakeGlobal(ArrayTy, V, Name, linkage);
223 }
David Chisnall81a65f52011-03-26 11:48:37 +0000224 /// Ensures that the value has the required type, by inserting a bitcast if
225 /// required. This function lets us avoid inserting bitcasts that are
226 /// redundant.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000227 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnallc7ef4622011-03-23 22:52:06 +0000228 if (V->getType() == Ty) return V;
229 return B.CreateBitCast(V, Ty);
230 }
231 // Some zeros used for GEPs in lots of places.
232 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000233 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000234 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000235 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000236 llvm::LLVMContext &VMContext;
237private:
David Chisnall81a65f52011-03-26 11:48:37 +0000238 /// Placeholder for the class. Lots of things refer to the class before we've
239 /// actually emitted it. We use this alias as a placeholder, and then replace
240 /// it with a pointer to the class structure before finally emitting the
241 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000242 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000243 /// Placeholder for the metaclass. Lots of things refer to the class before
244 /// we've / actually emitted it. We use this alias as a placeholder, and then
245 /// replace / it with a pointer to the metaclass structure before finally
246 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000247 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000248 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000249 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000250 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000251 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000252 /// All of the Objective-C constant strings that have been generated for this
253 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000254 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000255 /// Map from string values to Objective-C constant strings in the output.
256 /// Used to prevent emitting Objective-C strings more than once. This should
257 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000258 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000259 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000260 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000261 /// For each variant of a selector, we store the type encoding and a
262 /// placeholder value. For an untyped selector, the type will be the empty
263 /// string. Selector references are all done via the module's selector table,
264 /// so we create an alias as a placeholder and then replace it with the real
265 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000266 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000267 /// Type of the selector map. This is roughly equivalent to the structure
268 /// used in the GNUstep runtime, which maintains a list of all of the valid
269 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000270 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000271 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000272 /// A map from selectors to selector types. This allows us to emit all
273 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000274 SelectorMap SelectorTable;
275
David Chisnall81a65f52011-03-26 11:48:37 +0000276 /// Selectors related to memory management. When compiling in GC mode, we
277 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000278 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000279 /// Runtime functions used for memory management in GC mode. Note that clang
280 /// supports code generation for calling these functions, but neither GNU
281 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000282 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
283 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000284
David Chisnall9735ca62011-03-25 11:57:33 +0000285protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000286 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000287 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000288 /// Function used for rethrowing exceptions, used at the end of @finally or
289 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000290 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000291 /// Function called when entering a catch function. This is required for
292 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000293 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000294 /// Function called when exiting from a catch block. Used to do exception
295 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000296 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000298 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000299 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000300 LazyRuntimeFunction SyncExitFn;
301
David Chisnall9735ca62011-03-25 11:57:33 +0000302private:
303
David Chisnall81a65f52011-03-26 11:48:37 +0000304 /// Function called if fast enumeration detects that the collection is
305 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000306 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000307 /// Function for implementing synthesized property getters that return an
308 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000309 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// Function for implementing synthesized property setters that return an
311 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000312 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000313 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000314 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000315 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000316 LazyRuntimeFunction SetStructPropertyFn;
317
David Chisnall81a65f52011-03-26 11:48:37 +0000318 /// The version of the runtime that this class targets. Must match the
319 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000320 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000321 /// The version of the protocol class. Used to differentiate between ObjC1
322 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
323 /// components and can not contain declared properties. We always emit
324 /// Objective-C 2 property structures, but we have to pretend that they're
325 /// Objective-C 1 property structures when targeting the GCC runtime or it
326 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000327 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000328private:
David Chisnall81a65f52011-03-26 11:48:37 +0000329 /// Generates an instance variable list structure. This is a structure
330 /// containing a size and an array of structures containing instance variable
331 /// metadata. This is used purely for introspection in the fragile ABI. In
332 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000333 llvm::Constant *GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334 const SmallVectorImpl<llvm::Constant *> &IvarNames,
335 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
336 const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000337 /// Generates a method list structure. This is a structure containing a size
338 /// and an array of structures containing method metadata.
339 ///
340 /// This structure is used by both classes and categories, and contains a next
341 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000342 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
343 const StringRef &CategoryName,
344 const SmallVectorImpl<Selector> &MethodSels,
345 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000346 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000347 /// Emits an empty protocol. This is used for @protocol() where no protocol
348 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
349 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000350 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000351 /// Generates a list of property metadata structures. This follows the same
352 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000353 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000354 SmallVectorImpl<Selector> &InstanceMethodSels,
355 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000356 /// Generates a list of referenced protocols. Classes, categories, and
357 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000358 llvm::Constant *GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000359 const SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000360 /// To ensure that all protocols are seen by the runtime, we add a category on
361 /// a class defined in the runtime, declaring no methods, but adopting the
362 /// protocols. This is a horribly ugly hack, but it allows us to collect all
363 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000364 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000365 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000366 llvm::Constant *GenerateClassStructure(
367 llvm::Constant *MetaClass,
368 llvm::Constant *SuperClass,
369 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000370 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000371 llvm::Constant *Version,
372 llvm::Constant *InstanceSize,
373 llvm::Constant *IVars,
374 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000375 llvm::Constant *Protocols,
376 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000377 llvm::Constant *Properties,
378 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000379 /// Generates a method list. This is used by protocols to define the required
380 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000381 llvm::Constant *GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000382 const SmallVectorImpl<llvm::Constant *> &MethodNames,
383 const SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000384 /// Returns a selector with the specified type encoding. An empty string is
385 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000386 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
387 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000388 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000389 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
390 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000391 /// Emits a reference to a class. This allows the linker to object if there
392 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000393 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000394 /// Emits a pointer to the named class
David Chisnalld3fc7292011-06-30 10:14:37 +0000395 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
396 bool isWeak);
David Chisnallc7ef4622011-03-23 22:52:06 +0000397protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000398 /// Looks up the method for sending a message to the specified object. This
399 /// mechanism differs between the GCC and GNU runtimes, so this method must be
400 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000401 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
402 llvm::Value *&Receiver,
403 llvm::Value *cmd,
404 llvm::MDNode *node) = 0;
David Chisnall81a65f52011-03-26 11:48:37 +0000405 /// Looks up the method for sending a message to a superclass. This mechanism
406 /// differs between the GCC and GNU runtimes, so this method must be
407 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000408 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
409 llvm::Value *ObjCSuper,
410 llvm::Value *cmd) = 0;
Chris Lattner0f984262008-03-01 08:50:34 +0000411public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000412 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
413 unsigned protocolClassVersion);
414
David Chisnall0d13f6f2010-01-23 02:40:42 +0000415 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000416
417 virtual RValue
418 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000419 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000420 QualType ResultType,
421 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000422 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000423 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000424 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000425 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000426 virtual RValue
427 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000428 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000429 QualType ResultType,
430 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000431 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000432 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000433 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000434 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000435 const CallArgList &CallArgs,
436 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000437 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000438 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000439 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
440 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000441 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
442 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000443 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
445 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000446 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000447 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
448 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000449 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000450 const ObjCProtocolDecl *PD);
451 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000452 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000453 virtual llvm::Constant *GetPropertyGetFunction();
454 virtual llvm::Constant *GetPropertySetFunction();
455 virtual llvm::Constant *GetSetStructFunction();
456 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000457 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000458
David Chisnall9f6614e2011-03-23 16:36:54 +0000459 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000460 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000461 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000462 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000463 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000464 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000465 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000466 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000467 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000468 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000469 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000470 llvm::Value *src, llvm::Value *dest,
471 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000472 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000473 llvm::Value *src, llvm::Value *dest,
474 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000475 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000476 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000477 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000478 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000479 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000480 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000481 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000482 QualType ObjectTy,
483 llvm::Value *BaseValue,
484 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000485 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000486 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000487 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000488 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000489 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000490 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000491 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000492 return NULLPtr;
493 }
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000494
495 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
496 return 0;
497 }
Chris Lattner0f984262008-03-01 08:50:34 +0000498};
David Chisnall81a65f52011-03-26 11:48:37 +0000499/// Class representing the legacy GCC Objective-C ABI. This is the default when
500/// -fobjc-nonfragile-abi is not specified.
501///
502/// The GCC ABI target actually generates code that is approximately compatible
503/// with the new GNUstep runtime ABI, but refrains from using any features that
504/// would not work with the GCC runtime. For example, clang always generates
505/// the extended form of the class structure, and the extra fields are simply
506/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000507class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000508 /// The GCC ABI message lookup function. Returns an IMP pointing to the
509 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000510 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000511 /// The GCC ABI superclass message lookup function. Takes a pointer to a
512 /// structure describing the receiver and the class, and a selector as
513 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000514 LazyRuntimeFunction MsgLookupSuperFn;
515protected:
516 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
517 llvm::Value *&Receiver,
518 llvm::Value *cmd,
519 llvm::MDNode *node) {
520 CGBuilderTy &Builder = CGF.Builder;
521 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
522 EnforceType(Builder, Receiver, IdTy),
523 EnforceType(Builder, cmd, SelectorTy));
524 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
525 return imp;
526 }
527 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
528 llvm::Value *ObjCSuper,
529 llvm::Value *cmd) {
530 CGBuilderTy &Builder = CGF.Builder;
531 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
532 PtrToObjCSuperTy), cmd};
Jay Foad4c7d9f12011-07-15 08:37:34 +0000533 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000534 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000535 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000536 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
537 // IMP objc_msg_lookup(id, SEL);
538 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
539 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
540 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
541 PtrToObjCSuperTy, SelectorTy, NULL);
542 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000543};
David Chisnall81a65f52011-03-26 11:48:37 +0000544/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000545class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000546 /// The slot lookup function. Returns a pointer to a cacheable structure
547 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000548 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000549 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
550 /// a structure describing the receiver and the class, and a selector as
551 /// arguments. Returns the slot for the corresponding method. Superclass
552 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000553 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000554 /// Type of an slot structure pointer. This is returned by the various
555 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000556 llvm::Type *SlotTy;
557 protected:
558 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
559 llvm::Value *&Receiver,
560 llvm::Value *cmd,
561 llvm::MDNode *node) {
562 CGBuilderTy &Builder = CGF.Builder;
563 llvm::Function *LookupFn = SlotLookupFn;
564
565 // Store the receiver on the stack so that we can reload it later
566 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
567 Builder.CreateStore(Receiver, ReceiverPtr);
568
569 llvm::Value *self;
570
571 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
572 self = CGF.LoadObjCSelf();
573 } else {
574 self = llvm::ConstantPointerNull::get(IdTy);
575 }
576
577 // The lookup function is guaranteed not to capture the receiver pointer.
578 LookupFn->setDoesNotCapture(1);
579
580 llvm::CallInst *slot =
581 Builder.CreateCall3(LookupFn,
582 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
583 EnforceType(Builder, cmd, SelectorTy),
584 EnforceType(Builder, self, IdTy));
585 slot->setOnlyReadsMemory();
586 slot->setMetadata(msgSendMDKind, node);
587
588 // Load the imp from the slot
589 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
590
591 // The lookup function may have changed the receiver, so make sure we use
592 // the new one.
593 Receiver = Builder.CreateLoad(ReceiverPtr, true);
594 return imp;
595 }
596 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
597 llvm::Value *ObjCSuper,
598 llvm::Value *cmd) {
599 CGBuilderTy &Builder = CGF.Builder;
600 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
601
Jay Foad4c7d9f12011-07-15 08:37:34 +0000602 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000603 slot->setOnlyReadsMemory();
604
605 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
606 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000607 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000608 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner7650d952011-06-18 22:49:11 +0000609 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000610 PtrTy, PtrTy, IntTy, IMPTy, NULL);
611 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
612 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
613 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
614 SelectorTy, IdTy, NULL);
615 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
616 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
617 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000618 // If we're in ObjC++ mode, then we want to make
619 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000620 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000621 // void *__cxa_begin_catch(void *e)
622 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
623 // void __cxa_end_catch(void)
624 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
625 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000626 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000627 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000628 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000629};
630
Chris Lattner0f984262008-03-01 08:50:34 +0000631} // end anonymous namespace
632
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000633
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000634/// Emits a reference to a dummy variable which is emitted with each class.
635/// This ensures that a linker error will be generated when trying to link
636/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000637void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000638 std::string symbolRef = "__objc_class_ref_" + className;
639 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000640 if (TheModule.getGlobalVariable(symbolRef))
641 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000642 std::string symbolName = "__objc_class_name_" + className;
643 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
644 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000645 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
646 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000647 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000648 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000649 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000650}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000651
Chris Lattner5f9e2722011-07-23 10:55:15 +0000652static std::string SymbolNameForMethod(const StringRef &ClassName,
653 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000654 bool isClassMethod) {
655 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000656 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
657 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000658 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000659 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000660}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000661
David Chisnall9f6614e2011-03-23 16:36:54 +0000662CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
663 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000664 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
665 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
666 ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000667
668 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
669
David Chisnall9f6614e2011-03-23 16:36:54 +0000670 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000671 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000672 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000673 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000674 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000675 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000676 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000677 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000678 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000679 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000681 Int8Ty = llvm::Type::getInt8Ty(VMContext);
682 // C string type. Used in lots of places.
683 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
684
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000685 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000686 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000687 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000688 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000689 QualType selTy = CGM.getContext().getObjCSelType();
690 if (QualType() == selTy) {
691 SelectorTy = PtrToInt8Ty;
692 } else {
693 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
694 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000695
Owen Anderson96e0fc72009-07-29 22:16:19 +0000696 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000697 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattner391d77a2008-03-30 23:03:07 +0000699 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000700 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
701 ASTIdTy = CanQualType();
702 if (UnqualIdTy != QualType()) {
703 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000704 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000705 } else {
706 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000707 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000708 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner7650d952011-06-18 22:49:11 +0000710 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000711 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
712
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000713 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000714
715 // void objc_exception_throw(id);
716 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000717 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000718 // int objc_sync_enter(id);
719 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
720 // int objc_sync_exit(id);
721 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
722
723 // void objc_enumerationMutation (id)
724 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
725 IdTy, NULL);
726
727 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
728 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
729 PtrDiffTy, BoolTy, NULL);
730 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
731 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
732 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
733 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
734 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
735 PtrDiffTy, BoolTy, BoolTy, NULL);
736 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
737 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
738 PtrDiffTy, BoolTy, BoolTy, NULL);
739
Chris Lattner391d77a2008-03-30 23:03:07 +0000740 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000741 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000742 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
743 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000744
David Chisnallf0748852011-07-07 11:22:31 +0000745 const LangOptions &Opts = CGM.getLangOptions();
746 if ((Opts.getGCMode() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
747 RuntimeVersion = 10;
748
David Chisnall9735ca62011-03-25 11:57:33 +0000749 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnallf0748852011-07-07 11:22:31 +0000750 if (Opts.getGCMode() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000751 // This is a bit of an hack. We should sort this out by having a proper
752 // CGObjCGNUstep subclass for GC, but we may want to really support the old
753 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000754 // Get selectors needed in GC mode
755 RetainSel = GetNullarySelector("retain", CGM.getContext());
756 ReleaseSel = GetNullarySelector("release", CGM.getContext());
757 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
758
759 // Get functions needed in GC mode
760
761 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000762 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
763 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000764 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000765 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
766 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000767 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000768 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
769 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000770 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000771 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000772 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000773 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000774 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000775 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
776 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000777 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000778}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000779
David Chisnallc7aed3b2011-06-29 13:16:41 +0000780llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +0000781 const std::string &Name,
782 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +0000783 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +0000784 // With the incompatible ABI, this will need to be replaced with a direct
785 // reference to the class symbol. For the compatible nonfragile ABI we are
786 // still performing this lookup at run time but emitting the symbol for the
787 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +0000788 //
789 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
790 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +0000791 if (!isWeak)
792 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000793 ClassName = Builder.CreateStructGEP(ClassName, 0);
794
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000795 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +0000796 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000797 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000798 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000799}
800
David Chisnallc7aed3b2011-06-29 13:16:41 +0000801// This has to perform the lookup every time, since posing and related
802// techniques can modify the name -> class mapping.
803llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
804 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000805 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +0000806}
807llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000808 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000809}
810
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000811llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000812 const std::string &TypeEncoding, bool lval) {
813
Chris Lattner5f9e2722011-07-23 10:55:15 +0000814 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +0000815 llvm::GlobalAlias *SelValue = 0;
816
817
Chris Lattner5f9e2722011-07-23 10:55:15 +0000818 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +0000819 e = Types.end() ; i!=e ; i++) {
820 if (i->first == TypeEncoding) {
821 SelValue = i->second;
822 break;
823 }
824 }
825 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000826 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000827 llvm::GlobalValue::PrivateLinkage,
828 ".objc_selector_"+Sel.getAsString(), NULL,
829 &TheModule);
830 Types.push_back(TypedSelector(TypeEncoding, SelValue));
831 }
832
David Chisnallc7ef4622011-03-23 22:52:06 +0000833 if (lval) {
834 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
835 Builder.CreateStore(SelValue, tmp);
836 return tmp;
837 }
838 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000839}
840
841llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
842 bool lval) {
843 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000844}
845
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000846llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000847 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000848 std::string SelTypes;
849 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000850 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000851}
852
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000853llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000854 if (!CGM.getLangOptions().CPlusPlus) {
855 if (T->isObjCIdType()
856 || T->isObjCQualifiedIdType()) {
857 // With the old ABI, there was only one kind of catchall, which broke
858 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
859 // a pointer indicating object catchalls, and NULL to indicate real
860 // catchalls
861 if (CGM.getLangOptions().ObjCNonFragileABI) {
862 return MakeConstantString("@id");
863 } else {
864 return 0;
865 }
866 }
867
868 // All other types should be Objective-C interface pointer types.
869 const ObjCObjectPointerType *OPT =
870 T->getAs<ObjCObjectPointerType>();
871 assert(OPT && "Invalid @catch type.");
872 const ObjCInterfaceDecl *IDecl =
873 OPT->getObjectType()->getInterface();
874 assert(IDecl && "Invalid @catch type.");
875 return MakeConstantString(IDecl->getIdentifier()->getName());
876 }
David Chisnall80558d22011-03-20 21:35:39 +0000877 // For Objective-C++, we want to provide the ability to catch both C++ and
878 // Objective-C objects in the same function.
879
880 // There's a particular fixed type info for 'id'.
881 if (T->isObjCIdType() ||
882 T->isObjCQualifiedIdType()) {
883 llvm::Constant *IDEHType =
884 CGM.getModule().getGlobalVariable("__objc_id_type_info");
885 if (!IDEHType)
886 IDEHType =
887 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
888 false,
889 llvm::GlobalValue::ExternalLinkage,
890 0, "__objc_id_type_info");
891 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
892 }
893
894 const ObjCObjectPointerType *PT =
895 T->getAs<ObjCObjectPointerType>();
896 assert(PT && "Invalid @catch type.");
897 const ObjCInterfaceType *IT = PT->getInterfaceType();
898 assert(IT && "Invalid @catch type.");
899 std::string className = IT->getDecl()->getIdentifier()->getName();
900
901 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
902
903 // Return the existing typeinfo if it exists
904 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
905 if (typeinfo) return typeinfo;
906
907 // Otherwise create it.
908
909 // vtable for gnustep::libobjc::__objc_class_type_info
910 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
911 // platform's name mangling.
912 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
913 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
914 if (!Vtable) {
915 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
916 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
917 }
918 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +0000919 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +0000920 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
921
922 llvm::Constant *typeName =
923 ExportUniqueString(className, "__objc_eh_typename_");
924
925 std::vector<llvm::Constant*> fields;
926 fields.push_back(Vtable);
927 fields.push_back(typeName);
928 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +0000929 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +0000930 NULL), fields, "__objc_eh_typeinfo_" + className,
931 llvm::GlobalValue::LinkOnceODRLinkage);
932 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000933}
934
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000935/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000936llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000937
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000938 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000939
David Chisnall48272a02010-01-27 12:49:23 +0000940 // Look for an existing one
941 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
942 if (old != ObjCStrings.end())
943 return old->getValue();
944
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 std::vector<llvm::Constant*> Ivars;
946 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000947 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000948 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000949 llvm::Constant *ObjCStr = MakeGlobal(
Chris Lattner7650d952011-06-18 22:49:11 +0000950 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000951 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000952 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
953 ObjCStrings[Str] = ObjCStr;
954 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000955 return ObjCStr;
956}
957
958///Generates a message send where the super is the receiver. This is a message
959///send to self with special delivery semantics indicating which class's method
960///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +0000961RValue
962CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000963 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000964 QualType ResultType,
965 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000966 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000967 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000968 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000969 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000970 const CallArgList &CallArgs,
971 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +0000972 CGBuilderTy &Builder = CGF.Builder;
David Chisnalle6a11a62011-05-23 23:13:25 +0000973 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000974 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +0000975 return RValue::get(EnforceType(Builder, Receiver,
976 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +0000977 }
978 if (Sel == ReleaseSel) {
979 return RValue::get(0);
980 }
981 }
David Chisnalldb831942010-05-01 12:37:16 +0000982
David Chisnalldb831942010-05-01 12:37:16 +0000983 llvm::Value *cmd = GetSelector(Builder, Sel);
984
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000985
986 CallArgList ActualArgs;
987
Eli Friedman04c9a492011-05-02 17:57:46 +0000988 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
989 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +0000990 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000991
992 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000993 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000994 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000995
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000996 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000997 if (isCategoryImpl) {
998 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000999 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001000 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001001 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001002 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001003 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001004 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001005 }
David Chisnalldb831942010-05-01 12:37:16 +00001006 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001007 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001008 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001009 // Set up global aliases for the metaclass or class pointer if they do not
1010 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001011 // pointers to the class and metaclass structure created for the runtime
1012 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001013 // super_class pointer from either the class or metaclass structure.
1014 if (IsClassMessage) {
1015 if (!MetaClassPtrAlias) {
1016 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1017 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1018 Class->getNameAsString(), NULL, &TheModule);
1019 }
1020 ReceiverClass = MetaClassPtrAlias;
1021 } else {
1022 if (!ClassPtrAlias) {
1023 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1024 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1025 Class->getNameAsString(), NULL, &TheModule);
1026 }
1027 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001028 }
Chris Lattner71238f62009-04-25 23:19:45 +00001029 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001030 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001031 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001032 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001033 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001034 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001035 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001036 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001037 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001038 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001039 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001040 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001041 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001042
David Chisnalldb831942010-05-01 12:37:16 +00001043 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1044 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001045
David Chisnallc7ef4622011-03-23 22:52:06 +00001046 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001047 llvm::FunctionType *impType =
David Chisnallc7ef4622011-03-23 22:52:06 +00001048 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1049
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001050 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001051 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1052 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001053
David Chisnalldd5c98f2010-05-01 11:15:56 +00001054 llvm::Value *impMD[] = {
1055 llvm::MDString::get(VMContext, Sel.getAsString()),
1056 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1057 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1058 };
Jay Foad6f141652011-04-21 19:59:12 +00001059 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001060
David Chisnall4b02afc2010-05-02 13:41:58 +00001061 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001062 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001063 0, &call);
1064 call->setMetadata(msgSendMDKind, node);
1065 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001066}
1067
Mike Stump1eb44332009-09-09 15:08:12 +00001068/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001069RValue
1070CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001071 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001072 QualType ResultType,
1073 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001074 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001075 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001076 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001077 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001078 CGBuilderTy &Builder = CGF.Builder;
1079
David Chisnall664b7c72010-04-27 15:08:48 +00001080 // Strip out message sends to retain / release in GC mode
David Chisnalle6a11a62011-05-23 23:13:25 +00001081 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001082 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001083 return RValue::get(EnforceType(Builder, Receiver,
1084 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001085 }
1086 if (Sel == ReleaseSel) {
1087 return RValue::get(0);
1088 }
1089 }
David Chisnall664b7c72010-04-27 15:08:48 +00001090
David Chisnall664b7c72010-04-27 15:08:48 +00001091 // If the return type is something that goes in an integer register, the
1092 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1093 // ourselves.
1094 //
1095 // The language spec says the result of this kind of message send is
1096 // undefined, but lots of people seem to have forgotten to read that
1097 // paragraph and insist on sending messages to nil that have structure
1098 // returns. With GCC, this generates a random return value (whatever happens
1099 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001100 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1101 // the stack.
1102 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1103 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001104
1105 llvm::BasicBlock *startBB = 0;
1106 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001107 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001108
1109 if (!isPointerSizedReturn) {
1110 startBB = Builder.GetInsertBlock();
1111 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001112 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001113
1114 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1115 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001116 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001117 CGF.EmitBlock(messageBB);
1118 }
1119
David Chisnall0f436562009-08-17 16:35:33 +00001120 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001121 llvm::Value *cmd;
1122 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001123 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001124 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001125 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001126 cmd = EnforceType(Builder, cmd, SelectorTy);
1127 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001128
David Chisnallc7ef4622011-03-23 22:52:06 +00001129 llvm::Value *impMD[] = {
1130 llvm::MDString::get(VMContext, Sel.getAsString()),
1131 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1132 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1133 };
Jay Foad6f141652011-04-21 19:59:12 +00001134 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001135
1136 // Get the IMP to call
1137 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1138
1139 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001140 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1141 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001142 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001143
1144 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001145 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001146 FunctionType::ExtInfo());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001147 llvm::FunctionType *impType =
Daniel Dunbar67939662009-09-17 04:01:40 +00001148 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001149 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001150
1151
Fariborz Jahanian34e65772009-05-22 20:17:16 +00001152 // For sender-aware dispatch, we pass the sender as the third argument to a
1153 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001154 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnall4b02afc2010-05-02 13:41:58 +00001155 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001156 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001157 0, &call);
1158 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001159
David Chisnalla54da052010-05-20 13:45:48 +00001160
David Chisnall664b7c72010-04-27 15:08:48 +00001161 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001162 messageBB = CGF.Builder.GetInsertBlock();
1163 CGF.Builder.CreateBr(continueBB);
1164 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001165 if (msgRet.isScalar()) {
1166 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001167 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001168 phi->addIncoming(v, messageBB);
1169 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1170 msgRet = RValue::get(phi);
1171 } else if (msgRet.isAggregate()) {
1172 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001173 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001174 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001175 llvm::AllocaInst *NullVal =
1176 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001177 CGF.InitTempAlloca(NullVal,
1178 llvm::Constant::getNullValue(RetTy->getElementType()));
1179 phi->addIncoming(v, messageBB);
1180 phi->addIncoming(NullVal, startBB);
1181 msgRet = RValue::getAggregate(phi);
1182 } else /* isComplex() */ {
1183 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001184 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001185 phi->addIncoming(v.first, messageBB);
1186 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1187 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001188 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001189 phi2->addIncoming(v.second, messageBB);
1190 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1191 startBB);
1192 msgRet = RValue::getComplex(phi, phi2);
1193 }
1194 }
1195 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001196}
1197
Mike Stump1eb44332009-09-09 15:08:12 +00001198/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001199/// objc_category structures.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001200llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1201 const StringRef &CategoryName,
1202 const SmallVectorImpl<Selector> &MethodSels,
1203 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001204 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001205 if (MethodSels.empty())
1206 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001207 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001208 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001209 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1210 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001211 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001212 NULL);
1213 std::vector<llvm::Constant*> Methods;
1214 std::vector<llvm::Constant*> Elements;
1215 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1216 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001217 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001218 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001219 MethodSels[i],
1220 isClassMethodList));
1221 assert(Method && "Can't generate metadata for method that doesn't exist");
1222 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1223 Elements.push_back(C);
1224 Elements.push_back(MethodTypes[i]);
1225 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001226 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001227 Elements.push_back(Method);
1228 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001229 }
1230
1231 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001232 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001233 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001234 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001235 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001236
1237 // Structure containing list pointer, array and array count
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001238 llvm::StructType *ObjCMethodListTy =
1239 llvm::StructType::createNamed(VMContext, "");
1240 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1241 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001242 NextPtrTy,
1243 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001244 ObjCMethodArrayTy,
1245 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001246
1247 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001248 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001249 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +00001250 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001251 MethodTypes.size()));
1252 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001254 // Create an instance of the structure
1255 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1256}
1257
1258/// Generates an IvarList. Used in construction of a objc_class.
1259llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001260 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1261 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1262 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001263 if (IvarNames.size() == 0)
1264 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001265 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001266 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001267 PtrToInt8Ty,
1268 PtrToInt8Ty,
1269 IntTy,
1270 NULL);
1271 std::vector<llvm::Constant*> Ivars;
1272 std::vector<llvm::Constant*> Elements;
1273 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1274 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001275 Elements.push_back(IvarNames[i]);
1276 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001277 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001278 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001279 }
1280
1281 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001282 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001283 IvarNames.size());
1284
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001286 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001287 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001288 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001289 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001290 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001291 ObjCIvarArrayTy,
1292 NULL);
1293
1294 // Create an instance of the structure
1295 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1296}
1297
1298/// Generate a class structure
1299llvm::Constant *CGObjCGNU::GenerateClassStructure(
1300 llvm::Constant *MetaClass,
1301 llvm::Constant *SuperClass,
1302 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001303 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001304 llvm::Constant *Version,
1305 llvm::Constant *InstanceSize,
1306 llvm::Constant *IVars,
1307 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001308 llvm::Constant *Protocols,
1309 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001310 llvm::Constant *Properties,
1311 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001312 // Set up the class structure
1313 // Note: Several of these are char*s when they should be ids. This is
1314 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001315 //
1316 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1317 // anyway; the classes will still work with the GNU runtime, they will just
1318 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001319 llvm::StructType *ClassTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001320 PtrToInt8Ty, // class_pointer
1321 PtrToInt8Ty, // super_class
1322 PtrToInt8Ty, // name
1323 LongTy, // version
1324 LongTy, // info
1325 LongTy, // instance_size
1326 IVars->getType(), // ivars
1327 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001328 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001329 PtrTy, // dtable
1330 PtrTy, // subclass_list
1331 PtrTy, // sibling_class
1332 PtrTy, // protocols
1333 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001334 // New ABI:
1335 LongTy, // abi_version
1336 IvarOffsets->getType(), // ivar_offsets
1337 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001338 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001339 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001340 // Fill in the structure
1341 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001342 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001343 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001344 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001345 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001346 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001347 if (isMeta) {
1348 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001349 Elements.push_back(
1350 llvm::ConstantInt::get(LongTy,
1351 td.getTypeSizeInBits(ClassTy) /
1352 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001353 } else
1354 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001355 Elements.push_back(IVars);
1356 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001357 Elements.push_back(NULLPtr);
1358 Elements.push_back(NULLPtr);
1359 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001360 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001361 Elements.push_back(NULLPtr);
1362 Elements.push_back(Zero);
1363 Elements.push_back(IvarOffsets);
1364 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001365 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001366 // This is now an externally visible symbol, so that we can speed up class
1367 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +00001368 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1369 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001370}
1371
1372llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001373 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1374 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001376 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001377 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1378 PtrToInt8Ty,
1379 NULL);
1380 std::vector<llvm::Constant*> Methods;
1381 std::vector<llvm::Constant*> Elements;
1382 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1383 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001384 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001385 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001386 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001387 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001388 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001389 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001390 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001391 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001392 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001393 IntTy, ObjCMethodArrayTy, NULL);
1394 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001395 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001396 Methods.push_back(Array);
1397 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1398}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001399
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001400// Create the protocol list structure used in classes, categories and so on
1401llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001402 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001403 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001404 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001405 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001406 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001407 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001408 ProtocolArrayTy,
1409 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001410 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001411 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1412 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001413 llvm::Constant *protocol = 0;
1414 llvm::StringMap<llvm::Constant*>::iterator value =
1415 ExistingProtocols.find(*iter);
1416 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001417 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001418 } else {
1419 protocol = value->getValue();
1420 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001421 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001422 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001423 Elements.push_back(Ptr);
1424 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001425 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001426 Elements);
1427 Elements.clear();
1428 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001429 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001430 Elements.push_back(ProtocolArray);
1431 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1432}
1433
Mike Stump1eb44332009-09-09 15:08:12 +00001434llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001435 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001436 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001437 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001438 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001439 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001440}
1441
1442llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1443 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001444 SmallVector<std::string, 0> EmptyStringVector;
1445 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001446
1447 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001448 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001449 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1450 // Protocols are objects containing lists of the methods implemented and
1451 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001452 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001453 PtrToInt8Ty,
1454 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001455 MethodList->getType(),
1456 MethodList->getType(),
1457 MethodList->getType(),
1458 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001459 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001460 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001461 // The isa pointer must be set to a magic number so the runtime knows it's
1462 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001463 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001464 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1465 ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001466 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1467 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001468 Elements.push_back(MethodList);
1469 Elements.push_back(MethodList);
1470 Elements.push_back(MethodList);
1471 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001472 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001473}
1474
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001475void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1476 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001477 std::string ProtocolName = PD->getNameAsString();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001478 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001479 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1480 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001481 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001482 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1483 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1484 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1485 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001486 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1487 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001488 std::string TypeStr;
1489 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001490 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1491 InstanceMethodNames.push_back(
1492 MakeConstantString((*iter)->getSelector().getAsString()));
1493 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1494 } else {
1495 OptionalInstanceMethodNames.push_back(
1496 MakeConstantString((*iter)->getSelector().getAsString()));
1497 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1498 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001499 }
1500 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001501 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1502 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1503 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1504 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001505 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001506 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1507 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001508 std::string TypeStr;
1509 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001510 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1511 ClassMethodNames.push_back(
1512 MakeConstantString((*iter)->getSelector().getAsString()));
1513 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1514 } else {
1515 OptionalClassMethodNames.push_back(
1516 MakeConstantString((*iter)->getSelector().getAsString()));
1517 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1518 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001519 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001520
1521 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1522 llvm::Constant *InstanceMethodList =
1523 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1524 llvm::Constant *ClassMethodList =
1525 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001526 llvm::Constant *OptionalInstanceMethodList =
1527 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1528 OptionalInstanceMethodTypes);
1529 llvm::Constant *OptionalClassMethodList =
1530 GenerateProtocolMethodList(OptionalClassMethodNames,
1531 OptionalClassMethodTypes);
1532
1533 // Property metadata: name, attributes, isSynthesized, setter name, setter
1534 // types, getter name, getter types.
1535 // The isSynthesized value is always set to 0 in a protocol. It exists to
1536 // simplify the runtime library by allowing it to use the same data
1537 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001538 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001539 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1540 PtrToInt8Ty, NULL);
1541 std::vector<llvm::Constant*> Properties;
1542 std::vector<llvm::Constant*> OptionalProperties;
1543
1544 // Add all of the property methods need adding to the method list and to the
1545 // property metadata list.
1546 for (ObjCContainerDecl::prop_iterator
1547 iter = PD->prop_begin(), endIter = PD->prop_end();
1548 iter != endIter ; iter++) {
1549 std::vector<llvm::Constant*> Fields;
1550 ObjCPropertyDecl *property = (*iter);
1551
1552 Fields.push_back(MakeConstantString(property->getNameAsString()));
1553 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1554 property->getPropertyAttributes()));
1555 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1556 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1557 std::string TypeStr;
1558 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1559 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1560 InstanceMethodTypes.push_back(TypeEncoding);
1561 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1562 Fields.push_back(TypeEncoding);
1563 } else {
1564 Fields.push_back(NULLPtr);
1565 Fields.push_back(NULLPtr);
1566 }
1567 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1568 std::string TypeStr;
1569 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1570 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1571 InstanceMethodTypes.push_back(TypeEncoding);
1572 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1573 Fields.push_back(TypeEncoding);
1574 } else {
1575 Fields.push_back(NULLPtr);
1576 Fields.push_back(NULLPtr);
1577 }
1578 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1579 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1580 } else {
1581 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1582 }
1583 }
1584 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1585 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1586 llvm::Constant* PropertyListInitFields[] =
1587 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1588
1589 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001590 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001591 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1592 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1593 PropertyListInit, ".objc_property_list");
1594
1595 llvm::Constant *OptionalPropertyArray =
1596 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1597 OptionalProperties.size()) , OptionalProperties);
1598 llvm::Constant* OptionalPropertyListInitFields[] = {
1599 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1600 OptionalPropertyArray };
1601
1602 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001603 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001604 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1605 OptionalPropertyListInit->getType(), false,
1606 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1607 ".objc_property_list");
1608
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001609 // Protocols are objects containing lists of the methods implemented and
1610 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001611 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001612 PtrToInt8Ty,
1613 ProtocolList->getType(),
1614 InstanceMethodList->getType(),
1615 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001616 OptionalInstanceMethodList->getType(),
1617 OptionalClassMethodList->getType(),
1618 PropertyList->getType(),
1619 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001620 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001621 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001622 // The isa pointer must be set to a magic number so the runtime knows it's
1623 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001624 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001625 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1626 ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001627 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1628 Elements.push_back(ProtocolList);
1629 Elements.push_back(InstanceMethodList);
1630 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001631 Elements.push_back(OptionalInstanceMethodList);
1632 Elements.push_back(OptionalClassMethodList);
1633 Elements.push_back(PropertyList);
1634 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001635 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001636 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001637 ".objc_protocol"), IdTy);
1638}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001639void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1640 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001641 SmallVector<Selector, 1> MethodSels;
1642 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001643
1644 std::vector<llvm::Constant*> Elements;
1645 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1646 const std::string CategoryName = "AnotherHack";
1647 Elements.push_back(MakeConstantString(CategoryName));
1648 Elements.push_back(MakeConstantString(ClassName));
1649 // Instance method list
1650 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1651 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1652 // Class method list
1653 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1654 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1655 // Protocol list
1656 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1657 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001658 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001659 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001660 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001661 ProtocolArrayTy,
1662 NULL);
1663 std::vector<llvm::Constant*> ProtocolElements;
1664 for (llvm::StringMapIterator<llvm::Constant*> iter =
1665 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1666 iter != endIter ; iter++) {
1667 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1668 PtrTy);
1669 ProtocolElements.push_back(Ptr);
1670 }
1671 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1672 ProtocolElements);
1673 ProtocolElements.clear();
1674 ProtocolElements.push_back(NULLPtr);
1675 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1676 ExistingProtocols.size()));
1677 ProtocolElements.push_back(ProtocolArray);
1678 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1679 ProtocolElements, ".objc_protocol_list"), PtrTy));
1680 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001681 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001682 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1683}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001684
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001685void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001686 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1687 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001688 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001689 SmallVector<Selector, 16> InstanceMethodSels;
1690 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001691 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001692 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001693 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001694 InstanceMethodSels.push_back((*iter)->getSelector());
1695 std::string TypeStr;
1696 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001697 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001698 }
1699
1700 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001701 SmallVector<Selector, 16> ClassMethodSels;
1702 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001703 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001704 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001705 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001706 ClassMethodSels.push_back((*iter)->getSelector());
1707 std::string TypeStr;
1708 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001709 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001710 }
1711
1712 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001713 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001714 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1715 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001716 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1717 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001718 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001719
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001720 std::vector<llvm::Constant*> Elements;
1721 Elements.push_back(MakeConstantString(CategoryName));
1722 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001724 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001725 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001726 false), PtrTy));
1727 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001728 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001729 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001730 PtrTy));
1731 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001732 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001733 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001734 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001735 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001736 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001737}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001738
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001739llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001740 SmallVectorImpl<Selector> &InstanceMethodSels,
1741 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001742 ASTContext &Context = CGM.getContext();
1743 //
1744 // Property metadata: name, attributes, isSynthesized, setter name, setter
1745 // types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00001746 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001747 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1748 PtrToInt8Ty, NULL);
1749 std::vector<llvm::Constant*> Properties;
1750
1751
1752 // Add all of the property methods need adding to the method list and to the
1753 // property metadata list.
1754 for (ObjCImplDecl::propimpl_iterator
1755 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1756 iter != endIter ; iter++) {
1757 std::vector<llvm::Constant*> Fields;
1758 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001759 ObjCPropertyImplDecl *propertyImpl = *iter;
1760 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1761 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001762
1763 Fields.push_back(MakeConstantString(property->getNameAsString()));
1764 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1765 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001766 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001767 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001768 std::string TypeStr;
1769 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1770 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001771 if (isSynthesized) {
1772 InstanceMethodTypes.push_back(TypeEncoding);
1773 InstanceMethodSels.push_back(getter->getSelector());
1774 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001775 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1776 Fields.push_back(TypeEncoding);
1777 } else {
1778 Fields.push_back(NULLPtr);
1779 Fields.push_back(NULLPtr);
1780 }
1781 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001782 std::string TypeStr;
1783 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1784 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001785 if (isSynthesized) {
1786 InstanceMethodTypes.push_back(TypeEncoding);
1787 InstanceMethodSels.push_back(setter->getSelector());
1788 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001789 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1790 Fields.push_back(TypeEncoding);
1791 } else {
1792 Fields.push_back(NULLPtr);
1793 Fields.push_back(NULLPtr);
1794 }
1795 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1796 }
1797 llvm::ArrayType *PropertyArrayTy =
1798 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1799 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1800 Properties);
1801 llvm::Constant* PropertyListInitFields[] =
1802 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1803
1804 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001805 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001806 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1807 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1808 ".objc_property_list");
1809}
1810
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001811void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1812 ASTContext &Context = CGM.getContext();
1813
1814 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001815 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001816 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001817 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001818 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001819 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001820 EmitClassRef(SuperClassName);
1821 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001822
1823 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001824 ObjCInterfaceDecl *ClassDecl =
1825 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001826 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001827 // Emit the symbol that is used to generate linker errors if this class is
1828 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001829 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001830 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001831 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001832 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001833 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001834 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001835 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001836 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001837 }
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001839 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001840 int instanceSize =
1841 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001842
1843 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001844 SmallVector<llvm::Constant*, 16> IvarNames;
1845 SmallVector<llvm::Constant*, 16> IvarTypes;
1846 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001848 std::vector<llvm::Constant*> IvarOffsetValues;
1849
Mike Stump1eb44332009-09-09 15:08:12 +00001850 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001851 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001852 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1853 // class}. The runtime will then set this to the correct value on load.
1854 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1855 instanceSize = 0 - (instanceSize - superInstanceSize);
1856 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001857
Jordy Rosedb8264e2011-07-22 02:08:32 +00001858 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1859 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001860 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001861 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001862 // Get the type encoding for this ivar
1863 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001864 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001865 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001866 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001867 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001868 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001869 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001870 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001871 }
David Chisnall63ff7032011-07-07 12:34:51 +00001872 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1873 // Create the direct offset value
1874 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1875 IVD->getNameAsString();
1876 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1877 if (OffsetVar) {
1878 OffsetVar->setInitializer(OffsetValue);
1879 // If this is the real definition, change its linkage type so that
1880 // different modules will use this one, rather than their private
1881 // copy.
1882 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1883 } else
1884 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001885 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00001886 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001887 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00001888 IVD->getNameAsString());
1889 IvarOffsets.push_back(OffsetValue);
1890 IvarOffsetValues.push_back(OffsetVar);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001891 }
David Chisnall9f6614e2011-03-23 16:36:54 +00001892 llvm::GlobalVariable *IvarOffsetArray =
1893 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1894
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001895
1896 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001897 SmallVector<Selector, 16> InstanceMethodSels;
1898 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001899 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001900 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001901 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001902 InstanceMethodSels.push_back((*iter)->getSelector());
1903 std::string TypeStr;
1904 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001905 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001906 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001907
1908 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1909 InstanceMethodTypes);
1910
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001911
1912 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001913 SmallVector<Selector, 16> ClassMethodSels;
1914 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001915 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001916 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001917 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001918 ClassMethodSels.push_back((*iter)->getSelector());
1919 std::string TypeStr;
1920 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001921 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001922 }
1923 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001924 SmallVector<std::string, 16> Protocols;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001925 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1926 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1927 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001928 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001929
1930
1931
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001932 // Get the superclass pointer.
1933 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001934 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001935 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1936 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001937 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001938 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001939 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00001940 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001941 // Generate the method and instance variable lists
1942 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001943 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001944 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001945 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001946 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1947 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001948 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001949 // we emit a symbol containing the offset for each ivar in the class. This
1950 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1951 // for the legacy ABI, without causing problems. The converse is also
1952 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001953
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001954 // Offset pointer for getting at the correct field in the ivar list when
1955 // setting up the alias. These are: The base address for the global, the
1956 // ivar array (second field), the ivar in this list (set for each ivar), and
1957 // the offset (third field in ivar structure)
Chris Lattner2acc6e32011-07-18 04:24:23 +00001958 llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001959 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001960 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001961 llvm::ConstantInt::get(IndexTy, 2) };
1962
Jordy Rosedb8264e2011-07-22 02:08:32 +00001963 unsigned ivarIndex = 0;
1964 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1965 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001966 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001967 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00001968 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001969 // Get the correct ivar field
1970 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00001971 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00001972 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001973 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1974 if (offset) {
1975 offset->setInitializer(offsetValue);
1976 // If this is the real definition, change its linkage type so that
1977 // different modules will use this one, rather than their private
1978 // copy.
1979 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1980 } else {
1981 // Add a new alias if there isn't one already.
1982 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1983 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1984 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00001985 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001986 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001987 //Generate metaclass for class methods
1988 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001989 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001990 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001991
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001992 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001993 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001994 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001995 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001996 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001997 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1998 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001999
2000 // Resolve the class aliases, if they exist.
2001 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002002 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002003 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002004 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002005 ClassPtrAlias = 0;
2006 }
2007 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002008 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002009 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002010 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002011 MetaClassPtrAlias = 0;
2012 }
2013
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002014 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002015 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002016 Classes.push_back(ClassStruct);
2017}
2018
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002019
Mike Stump1eb44332009-09-09 15:08:12 +00002020llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002021 // Only emit an ObjC load function if no Objective-C stuff has been called
2022 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002023 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002024 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002025
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002026 // Add all referenced protocols to a category.
2027 GenerateProtocolHolderCategory();
2028
Chris Lattner2acc6e32011-07-18 04:24:23 +00002029 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002030 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002031 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002032 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002033 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002034 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002035 }
2036
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002037 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002038 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002039 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002040 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002041 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002042 ConstantStrings.size() + 1);
2043 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002044
Chris Lattner5f9e2722011-07-23 10:55:15 +00002045 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002046
Daniel Dunbar1b096952009-11-29 02:38:47 +00002047 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002048
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002049 Elements.push_back(MakeConstantString(StringClass,
2050 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002051 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002052 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002053 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002054 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002055 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002056 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002057 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002058 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002059 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002060 Elements.clear();
2061 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002062 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002063 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002064 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002065 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002066 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002067 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002068 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002069 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002070 llvm::Type::getInt16Ty(VMContext),
2071 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002072 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002073
2074 Elements.clear();
2075 // Pointer to an array of selectors used in this module.
2076 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002077 std::vector<llvm::GlobalAlias*> SelectorAliases;
2078 for (SelectorMap::iterator iter = SelectorTable.begin(),
2079 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2080
2081 std::string SelNameStr = iter->first.getAsString();
2082 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2083
Chris Lattner5f9e2722011-07-23 10:55:15 +00002084 SmallVectorImpl<TypedSelector> &Types = iter->second;
2085 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002086 e = Types.end() ; i!=e ; i++) {
2087
2088 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2089 if (!i->first.empty())
2090 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2091
2092 Elements.push_back(SelName);
2093 Elements.push_back(SelectorTypeEncoding);
2094 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2095 Elements.clear();
2096
2097 // Store the selector alias for later replacement
2098 SelectorAliases.push_back(i->second);
2099 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002100 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002101 unsigned SelectorCount = Selectors.size();
2102 // NULL-terminate the selector list. This should not actually be required,
2103 // because the selector list has a length field. Unfortunately, the GCC
2104 // runtime decides to ignore the length field and expects a NULL terminator,
2105 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002106 Elements.push_back(NULLPtr);
2107 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002108 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002109 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002110
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002111 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002112 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2113 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002114 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002115 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002116 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002117
2118 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002119 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2120
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002121 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall9f6614e2011-03-23 16:36:54 +00002122 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2123 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002124 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002125 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002126 // If selectors are defined as an opaque type, cast the pointer to this
2127 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002128 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002129 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2130 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002131 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002132
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002133 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002134 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002135 Classes.size()));
2136 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002137 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002138 Categories.size()));
2139 // Create an array of classes, then categories, then static object instances
2140 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2141 // NULL-terminated list of static object instances (mainly constant strings)
2142 Classes.push_back(Statics);
2143 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002144 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002145 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002146 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002147 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2148
2149 // The symbol table is contained in a module which has some version-checking
2150 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002151 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002152 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002153 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002154 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002155 // Runtime version, used for ABI compatibility checking.
2156 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002157 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002158 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002159 Elements.push_back(
2160 llvm::ConstantInt::get(LongTy,
2161 td.getTypeSizeInBits(ModuleTy) /
2162 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002163
2164 // The path to the source file where this module was declared
2165 SourceManager &SM = CGM.getContext().getSourceManager();
2166 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2167 std::string path =
2168 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2169 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002170 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002171
David Chisnallf0748852011-07-07 11:22:31 +00002172 if (RuntimeVersion >= 10)
2173 switch (CGM.getLangOptions().getGCMode()) {
2174 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002175 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002176 break;
David Chisnallf0748852011-07-07 11:22:31 +00002177 case LangOptions::NonGC:
2178 if (CGM.getLangOptions().ObjCAutoRefCount)
2179 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2180 else
2181 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2182 break;
2183 case LangOptions::HybridGC:
2184 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2185 break;
2186 }
David Chisnalla2120032011-05-22 22:37:08 +00002187
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002188 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2189
2190 // Create the load function calling the runtime entry point with the module
2191 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002192 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002193 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002194 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2195 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002196 llvm::BasicBlock *EntryBB =
2197 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002198 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002199 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002200
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002201 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002202 llvm::FunctionType::get(Builder.getVoidTy(),
2203 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002204 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002205 Builder.CreateCall(Register, Module);
2206 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002207
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002208 return LoadFunction;
2209}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002210
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002211llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002212 const ObjCContainerDecl *CD) {
2213 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002214 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002215 StringRef CategoryName = OCD ? OCD->getName() : "";
2216 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002217 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002218 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002219
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002220 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002221 llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002222 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002223 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2224 MethodName, isClassMethod);
2225
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002226 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002227 = llvm::Function::Create(MethodTy,
2228 llvm::GlobalValue::InternalLinkage,
2229 FunctionName,
2230 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002231 return Method;
2232}
2233
David Chisnall789ecde2011-05-23 22:33:28 +00002234llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002235 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002236}
2237
David Chisnall789ecde2011-05-23 22:33:28 +00002238llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002239 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002240}
2241
David Chisnall789ecde2011-05-23 22:33:28 +00002242llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002243 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002244}
David Chisnall789ecde2011-05-23 22:33:28 +00002245llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002246 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002247}
2248
Daniel Dunbar309a4362009-07-24 07:40:24 +00002249llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002250 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002251}
2252
David Chisnall9f6614e2011-03-23 16:36:54 +00002253void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002254 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002255 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002256}
Chris Lattner5dc08672009-05-08 00:11:50 +00002257
David Chisnall0faa5162009-12-24 02:26:34 +00002258
David Chisnall9f6614e2011-03-23 16:36:54 +00002259void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002260 const ObjCAtTryStmt &S) {
2261 // Unlike the Apple non-fragile runtimes, which also uses
2262 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2263 // EH support isn't a veneer over C++ EH. Instead, exception
2264 // objects are created by __objc_exception_throw and destroyed by
2265 // the personality function; this avoids the need for bracketing
2266 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2267 // (or even _Unwind_DeleteException), but probably doesn't
2268 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002269 //
David Chisnall80558d22011-03-20 21:35:39 +00002270 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002271 // exception handler.
2272 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2273 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002274}
2275
David Chisnall9f6614e2011-03-23 16:36:54 +00002276void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002277 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002278 llvm::Value *ExceptionAsObject;
2279
Chris Lattner5dc08672009-05-08 00:11:50 +00002280 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2281 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002282 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002283 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002284 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002285 "Unexpected rethrow outside @catch block.");
2286 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2287 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002288 ExceptionAsObject =
2289 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Chris Lattner5dc08672009-05-08 00:11:50 +00002291 // Note: This may have to be an invoke, if we want to support constructs like:
2292 // @try {
2293 // @throw(obj);
2294 // }
2295 // @catch(id) ...
2296 //
2297 // This is effectively turning @throw into an incredibly-expensive goto, but
2298 // it may happen as a result of inlining followed by missed optimizations, or
2299 // as a result of stupidity.
2300 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2301 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002302 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002303 CGF.Builder.CreateUnreachable();
2304 } else {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002305 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2306 ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002307 }
2308 // Clear the insertion point to indicate we are in unreachable code.
2309 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002310}
2311
David Chisnall9f6614e2011-03-23 16:36:54 +00002312llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002313 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002314 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002315 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002316 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002317}
2318
David Chisnall9f6614e2011-03-23 16:36:54 +00002319void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002320 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002321 CGBuilderTy B = CGF.Builder;
2322 src = EnforceType(B, src, IdTy);
2323 dst = EnforceType(B, dst, PtrToIdTy);
2324 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002325}
2326
David Chisnall9f6614e2011-03-23 16:36:54 +00002327void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002328 llvm::Value *src, llvm::Value *dst,
2329 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002330 CGBuilderTy B = CGF.Builder;
2331 src = EnforceType(B, src, IdTy);
2332 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002333 if (!threadlocal)
2334 B.CreateCall2(GlobalAssignFn, src, dst);
2335 else
2336 // FIXME. Add threadloca assign API
2337 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002338}
2339
David Chisnall9f6614e2011-03-23 16:36:54 +00002340void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002341 llvm::Value *src, llvm::Value *dst,
2342 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002343 CGBuilderTy B = CGF.Builder;
2344 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002345 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002346 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002347}
2348
David Chisnall9f6614e2011-03-23 16:36:54 +00002349void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002350 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002351 CGBuilderTy B = CGF.Builder;
2352 src = EnforceType(B, src, IdTy);
2353 dst = EnforceType(B, dst, PtrToIdTy);
2354 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002355}
2356
David Chisnall9f6614e2011-03-23 16:36:54 +00002357void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002358 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002359 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002360 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002361 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002362 DestPtr = EnforceType(B, DestPtr, PtrTy);
2363 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002364
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002365 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002366}
2367
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002368llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2369 const ObjCInterfaceDecl *ID,
2370 const ObjCIvarDecl *Ivar) {
2371 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2372 + '.' + Ivar->getNameAsString();
2373 // Emit the variable and initialize it with what we think the correct value
2374 // is. This allows code compiled with non-fragile ivars to work correctly
2375 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002376 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2377 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002378 // This will cause a run-time crash if we accidentally use it. A value of
2379 // 0 would seem more sensible, but will silently overwrite the isa pointer
2380 // causing a great deal of confusion.
2381 uint64_t Offset = -1;
2382 // We can't call ComputeIvarBaseOffset() here if we have the
2383 // implementation, because it will create an invalid ASTRecordLayout object
2384 // that we are then stuck with forever, so we only initialize the ivar
2385 // offset variable with a guess if we only have the interface. The
2386 // initializer will be reset later anyway, when we are generating the class
2387 // description.
2388 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002389 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002390 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2391
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002392 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002393 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002394 // Don't emit the guess in non-PIC code because the linker will not be able
2395 // to replace it with the real version for a library. In non-PIC code you
2396 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002397 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002398 if (CGM.getLangOptions().PICLevel) {
2399 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2400 llvm::Type::getInt32Ty(VMContext), false,
2401 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2402 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2403 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2404 IvarOffsetGV, Name);
2405 } else {
2406 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002407 llvm::Type::getInt32PtrTy(VMContext), false,
2408 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002409 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002410 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002411 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002412}
2413
David Chisnall9f6614e2011-03-23 16:36:54 +00002414LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002415 QualType ObjectTy,
2416 llvm::Value *BaseValue,
2417 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002418 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002419 const ObjCInterfaceDecl *ID =
2420 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002421 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2422 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002423}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002424
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002425static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2426 const ObjCInterfaceDecl *OID,
2427 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002428 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2429 next = next->getNextIvar()) {
2430 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002431 return OID;
2432 }
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002434 // Otherwise check in the super class.
2435 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2436 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002438 return 0;
2439}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002440
David Chisnall9f6614e2011-03-23 16:36:54 +00002441llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002442 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002443 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002444 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002445 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002446 if (RuntimeVersion < 10)
2447 return CGF.Builder.CreateZExtOrBitCast(
2448 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2449 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2450 PtrDiffTy);
2451 std::string name = "__objc_ivar_offset_value_" +
2452 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2453 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2454 if (!Offset)
2455 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002456 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2457 llvm::Constant::getNullValue(IntTy), name);
David Chisnall63ff7032011-07-07 12:34:51 +00002458 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002459 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002460 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002461 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002462}
2463
David Chisnall9f6614e2011-03-23 16:36:54 +00002464CGObjCRuntime *
2465clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2466 if (CGM.getLangOptions().ObjCNonFragileABI)
2467 return new CGObjCGNUstep(CGM);
2468 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002469}