blob: 9ef2b98f9b77d4cbb8436cd1e8f5b6a8de1a4aaf [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
David Chisnall9f6614e2011-03-23 16:36:54 +000039#include <stdarg.h>
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 +000044using llvm::dyn_cast;
45
Chris Lattner0f984262008-03-01 08:50:34 +000046
Chris Lattner0f984262008-03-01 08:50:34 +000047namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000048/// Class that lazily initialises the runtime function. Avoids inserting the
49/// types and the function declaration into a module if they're not used, and
50/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000051class LazyRuntimeFunction {
52 CodeGenModule *CGM;
53 std::vector<const llvm::Type*> ArgTys;
54 const char *FunctionName;
55 llvm::Function *Function;
56 public:
David Chisnall81a65f52011-03-26 11:48:37 +000057 /// Constructor leaves this class uninitialized, because it is intended to
58 /// be used as a field in another class and not all of the types that are
59 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000060 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
61
David Chisnall81a65f52011-03-26 11:48:37 +000062 /// Initialises the lazy function with the name, return type, and the types
63 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000064 END_WITH_NULL
65 void init(CodeGenModule *Mod, const char *name,
66 const llvm::Type *RetTy, ...) {
67 CGM =Mod;
68 FunctionName = name;
69 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000070 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000071 va_list Args;
72 va_start(Args, RetTy);
73 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
74 ArgTys.push_back(ArgTy);
75 va_end(Args);
76 // Push the return type on at the end so we can pop it off easily
77 ArgTys.push_back(RetTy);
78 }
David Chisnall81a65f52011-03-26 11:48:37 +000079 /// Overloaded cast operator, allows the class to be implicitly cast to an
80 /// LLVM constant.
David Chisnall9f6614e2011-03-23 16:36:54 +000081 operator llvm::Function*() {
82 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000083 if (0 == FunctionName) return 0;
84 // We put the return type on the end of the vector, so pop it back off
David Chisnall9f6614e2011-03-23 16:36:54 +000085 const llvm::Type *RetTy = ArgTys.back();
86 ArgTys.pop_back();
87 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
88 Function =
89 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000090 // We won't need to use the types again, so we may as well clean up the
91 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000092 ArgTys.resize(0);
93 }
94 return Function;
95 }
96};
97
98
David Chisnall81a65f52011-03-26 11:48:37 +000099/// GNU Objective-C runtime code generation. This class implements the parts of
100/// Objective-C support that are specific to the GNU family of runtimes (GCC and
101/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000102class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000103protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000104 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000105 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000106 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000107 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000108 /// strut objc_super. Used for sending messages to super. This structure
109 /// contains the receiver (object) and the expected class.
David Chisnallc7ef4622011-03-23 22:52:06 +0000110 const llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000111 /// struct objc_super*. The type of the argument to the superclass message
112 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000113 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000114 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
115 /// SEL is included in a header somewhere, in which case it will be whatever
116 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000117 const llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000118 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
119 /// places where it's used
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000120 const llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000121 /// Pointer to i8 - LLVM type of char*, for all of the places where the
122 /// runtime needs to deal with C strings.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000123 const llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000124 /// Instance Method Pointer type. This is a pointer to a function that takes,
125 /// at a minimum, an object and a selector, and is the generic type for
126 /// Objective-C methods. Due to differences between variadic / non-variadic
127 /// calling conventions, it must always be cast to the correct type before
128 /// actually being used.
David Chisnallc7ef4622011-03-23 22:52:06 +0000129 const llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000130 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
131 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
132 /// but if the runtime header declaring it is included then it may be a
133 /// pointer to a structure.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000134 const llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000135 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
136 /// message lookup function and some GC-related functions.
David Chisnallef6e0f32010-02-03 15:59:02 +0000137 const llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000138 /// The clang type of id. Used when using the clang CGCall infrastructure to
139 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000140 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// LLVM type for C int type.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000142 const llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000143 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
144 /// used in the code to document the difference between i8* meaning a pointer
145 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000146 const llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000147 /// LLVM type for C long type. The runtime uses this in a lot of places where
148 /// it should be using intptr_t, but we can't fix this without breaking
149 /// compatibility with GCC...
Chris Lattnere160c9b2009-01-27 05:06:01 +0000150 const llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000151 /// LLVM type for C size_t. Used in various runtime data structures.
David Chisnall8fac25d2010-12-26 22:13:16 +0000152 const llvm::IntegerType *SizeTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
David Chisnall8fac25d2010-12-26 22:13:16 +0000154 const llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 /// variables.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000157 const llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000158 /// LLVM type for Objective-C BOOL type.
David Chisnall8fac25d2010-12-26 22:13:16 +0000159 const llvm::Type *BoolTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000160 /// Metadata kind used to tie method lookups to message sends. The GNUstep
161 /// runtime provides some LLVM passes that can use this to do things like
162 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000163 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000167 llvm::Constant *MakeConstantString(const std::string &Str,
168 const std::string &Name="") {
169 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
170 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
171 }
David Chisnall81a65f52011-03-26 11:48:37 +0000172 /// Emits a linkonce_odr string, whose name is the prefix followed by the
173 /// string value. This allows the linker to combine the strings between
174 /// different modules. Used for EH typeinfo names, selector strings, and a
175 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000176 llvm::Constant *ExportUniqueString(const std::string &Str,
177 const std::string prefix) {
178 std::string name = prefix + Str;
179 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
180 if (!ConstStr) {
181 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
182 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
183 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
184 }
185 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
186 }
David Chisnall81a65f52011-03-26 11:48:37 +0000187 /// Generates a global structure, initialized by the elements in the vector.
188 /// The element types must match the types of the structure elements in the
189 /// first argument.
David Chisnallc7ef4622011-03-23 22:52:06 +0000190 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000191 std::vector<llvm::Constant*> &V,
192 llvm::StringRef Name="",
193 llvm::GlobalValue::LinkageTypes linkage
194 =llvm::GlobalValue::InternalLinkage) {
195 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
196 return new llvm::GlobalVariable(TheModule, Ty, false,
197 linkage, C, Name);
198 }
David Chisnall81a65f52011-03-26 11:48:37 +0000199 /// Generates a global array. The vector must contain the same number of
200 /// elements that the array type declares, of the type specified as the array
201 /// element type.
David Chisnallc7ef4622011-03-23 22:52:06 +0000202 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000203 std::vector<llvm::Constant*> &V,
204 llvm::StringRef Name="",
205 llvm::GlobalValue::LinkageTypes linkage
206 =llvm::GlobalValue::InternalLinkage) {
207 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
208 return new llvm::GlobalVariable(TheModule, Ty, false,
209 linkage, C, Name);
210 }
David Chisnall81a65f52011-03-26 11:48:37 +0000211 /// Generates a global array, inferring the array type from the specified
212 /// element type and the size of the initialiser.
David Chisnallc7ef4622011-03-23 22:52:06 +0000213 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000214 std::vector<llvm::Constant*> &V,
215 llvm::StringRef Name="",
216 llvm::GlobalValue::LinkageTypes linkage
217 =llvm::GlobalValue::InternalLinkage) {
218 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
219 return MakeGlobal(ArrayTy, V, Name, linkage);
220 }
David Chisnall81a65f52011-03-26 11:48:37 +0000221 /// Ensures that the value has the required type, by inserting a bitcast if
222 /// required. This function lets us avoid inserting bitcasts that are
223 /// redundant.
David Chisnallc7ef4622011-03-23 22:52:06 +0000224 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
225 if (V->getType() == Ty) return V;
226 return B.CreateBitCast(V, Ty);
227 }
228 // Some zeros used for GEPs in lots of places.
229 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000230 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000231 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000232 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000233 llvm::LLVMContext &VMContext;
234private:
David Chisnall81a65f52011-03-26 11:48:37 +0000235 /// Placeholder for the class. Lots of things refer to the class before we've
236 /// actually emitted it. We use this alias as a placeholder, and then replace
237 /// it with a pointer to the class structure before finally emitting the
238 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000239 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000240 /// Placeholder for the metaclass. Lots of things refer to the class before
241 /// we've / actually emitted it. We use this alias as a placeholder, and then
242 /// replace / it with a pointer to the metaclass structure before finally
243 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000244 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000245 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000246 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000247 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000248 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000249 /// All of the Objective-C constant strings that have been generated for this
250 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000251 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000252 /// Map from string values to Objective-C constant strings in the output.
253 /// Used to prevent emitting Objective-C strings more than once. This should
254 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000255 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000256 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000257 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000258 /// For each variant of a selector, we store the type encoding and a
259 /// placeholder value. For an untyped selector, the type will be the empty
260 /// string. Selector references are all done via the module's selector table,
261 /// so we create an alias as a placeholder and then replace it with the real
262 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000263 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000264 /// Type of the selector map. This is roughly equivalent to the structure
265 /// used in the GNUstep runtime, which maintains a list of all of the valid
266 /// types for a selector in a table.
David Chisnall9f6614e2011-03-23 16:36:54 +0000267 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
268 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000269 /// A map from selectors to selector types. This allows us to emit all
270 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000271 SelectorMap SelectorTable;
272
David Chisnall81a65f52011-03-26 11:48:37 +0000273 /// Selectors related to memory management. When compiling in GC mode, we
274 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000275 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000276 /// Runtime functions used for memory management in GC mode. Note that clang
277 /// supports code generation for calling these functions, but neither GNU
278 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000279 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
280 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000281
David Chisnall9735ca62011-03-25 11:57:33 +0000282protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000283 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000284 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000285 /// Function used for rethrowing exceptions, used at the end of @finally or
286 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000287 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000288 /// Function called when entering a catch function. This is required for
289 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000290 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000291 /// Function called when exiting from a catch block. Used to do exception
292 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000293 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000294 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000295 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000296 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000297 LazyRuntimeFunction SyncExitFn;
298
David Chisnall9735ca62011-03-25 11:57:33 +0000299private:
300
David Chisnall81a65f52011-03-26 11:48:37 +0000301 /// Function called if fast enumeration detects that the collection is
302 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000303 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000304 /// Function for implementing synthesized property getters that return an
305 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000306 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000307 /// Function for implementing synthesized property setters that return an
308 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000309 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000311 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000312 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000313 LazyRuntimeFunction SetStructPropertyFn;
314
David Chisnall81a65f52011-03-26 11:48:37 +0000315 /// The version of the runtime that this class targets. Must match the
316 /// version in the runtime.
David Chisnall9f6614e2011-03-23 16:36:54 +0000317 const int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000318 /// The version of the protocol class. Used to differentiate between ObjC1
319 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
320 /// components and can not contain declared properties. We always emit
321 /// Objective-C 2 property structures, but we have to pretend that they're
322 /// Objective-C 1 property structures when targeting the GCC runtime or it
323 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000324 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000325private:
David Chisnall81a65f52011-03-26 11:48:37 +0000326 /// Generates an instance variable list structure. This is a structure
327 /// containing a size and an array of structures containing instance variable
328 /// metadata. This is used purely for introspection in the fragile ABI. In
329 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000330 llvm::Constant *GenerateIvarList(
331 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
332 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
333 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000334 /// Generates a method list structure. This is a structure containing a size
335 /// and an array of structures containing method metadata.
336 ///
337 /// This structure is used by both classes and categories, and contains a next
338 /// pointer allowing them to be chained together in a linked list.
David Chisnall9f6614e2011-03-23 16:36:54 +0000339 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
340 const llvm::StringRef &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +0000341 const llvm::SmallVectorImpl<Selector> &MethodSels,
342 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000343 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000344 /// Emits an empty protocol. This is used for @protocol() where no protocol
345 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
346 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000347 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000348 /// Generates a list of property metadata structures. This follows the same
349 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000350 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
351 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
352 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000353 /// Generates a list of referenced protocols. Classes, categories, and
354 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000355 llvm::Constant *GenerateProtocolList(
356 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000357 /// To ensure that all protocols are seen by the runtime, we add a category on
358 /// a class defined in the runtime, declaring no methods, but adopting the
359 /// protocols. This is a horribly ugly hack, but it allows us to collect all
360 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000361 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000362 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000363 llvm::Constant *GenerateClassStructure(
364 llvm::Constant *MetaClass,
365 llvm::Constant *SuperClass,
366 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000367 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000368 llvm::Constant *Version,
369 llvm::Constant *InstanceSize,
370 llvm::Constant *IVars,
371 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000372 llvm::Constant *Protocols,
373 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000374 llvm::Constant *Properties,
375 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000376 /// Generates a method list. This is used by protocols to define the required
377 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000378 llvm::Constant *GenerateProtocolMethodList(
379 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
380 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000381 /// Returns a selector with the specified type encoding. An empty string is
382 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000383 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
384 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000385 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000386 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
387 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000388 /// Emits a reference to a class. This allows the linker to object if there
389 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000390 void EmitClassRef(const std::string &className);
David Chisnallc7ef4622011-03-23 22:52:06 +0000391protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000392 /// Looks up the method for sending a message to the specified object. This
393 /// mechanism differs between the GCC and GNU runtimes, so this method must be
394 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000395 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
396 llvm::Value *&Receiver,
397 llvm::Value *cmd,
398 llvm::MDNode *node) = 0;
David Chisnall81a65f52011-03-26 11:48:37 +0000399 /// Looks up the method for sending a message to a superclass. This mechanism
400 /// differs between the GCC and GNU runtimes, so this method must be
401 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000402 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
403 llvm::Value *ObjCSuper,
404 llvm::Value *cmd) = 0;
Chris Lattner0f984262008-03-01 08:50:34 +0000405public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000406 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
407 unsigned protocolClassVersion);
408
David Chisnall0d13f6f2010-01-23 02:40:42 +0000409 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000410
411 virtual RValue
412 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000413 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000414 QualType ResultType,
415 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000416 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000417 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000418 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000419 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000420 virtual RValue
421 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000422 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000423 QualType ResultType,
424 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000425 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000426 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000427 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000428 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000429 const CallArgList &CallArgs,
430 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000431 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000432 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000433 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
434 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000435 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
436 *Method);
John McCall5a180392010-07-24 00:37:23 +0000437 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000438
439 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000440 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000441 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
442 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000443 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000444 const ObjCProtocolDecl *PD);
445 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000446 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000447 virtual llvm::Function *GetPropertyGetFunction();
448 virtual llvm::Function *GetPropertySetFunction();
David Chisnall8fac25d2010-12-26 22:13:16 +0000449 virtual llvm::Function *GetSetStructFunction();
450 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000451 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000452
David Chisnall9f6614e2011-03-23 16:36:54 +0000453 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000454 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000455 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000456 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000457 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000458 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000459 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000460 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000461 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000462 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000463 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000464 llvm::Value *src, llvm::Value *dest,
465 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000466 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000467 llvm::Value *src, llvm::Value *dest,
468 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000469 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000470 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000471 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000472 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000473 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000474 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000475 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000476 QualType ObjectTy,
477 llvm::Value *BaseValue,
478 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000479 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000480 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000481 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000482 const ObjCIvarDecl *Ivar);
David Chisnall9f6614e2011-03-23 16:36:54 +0000483 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000484 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000485 return NULLPtr;
486 }
Chris Lattner0f984262008-03-01 08:50:34 +0000487};
David Chisnall81a65f52011-03-26 11:48:37 +0000488/// Class representing the legacy GCC Objective-C ABI. This is the default when
489/// -fobjc-nonfragile-abi is not specified.
490///
491/// The GCC ABI target actually generates code that is approximately compatible
492/// with the new GNUstep runtime ABI, but refrains from using any features that
493/// would not work with the GCC runtime. For example, clang always generates
494/// the extended form of the class structure, and the extra fields are simply
495/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000496class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000497 /// The GCC ABI message lookup function. Returns an IMP pointing to the
498 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000499 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000500 /// The GCC ABI superclass message lookup function. Takes a pointer to a
501 /// structure describing the receiver and the class, and a selector as
502 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000503 LazyRuntimeFunction MsgLookupSuperFn;
504protected:
505 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
506 llvm::Value *&Receiver,
507 llvm::Value *cmd,
508 llvm::MDNode *node) {
509 CGBuilderTy &Builder = CGF.Builder;
510 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
511 EnforceType(Builder, Receiver, IdTy),
512 EnforceType(Builder, cmd, SelectorTy));
513 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
514 return imp;
515 }
516 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
517 llvm::Value *ObjCSuper,
518 llvm::Value *cmd) {
519 CGBuilderTy &Builder = CGF.Builder;
520 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
521 PtrToObjCSuperTy), cmd};
522 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
523 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000524 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000525 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
526 // IMP objc_msg_lookup(id, SEL);
527 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
528 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
529 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
530 PtrToObjCSuperTy, SelectorTy, NULL);
531 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000532};
David Chisnall81a65f52011-03-26 11:48:37 +0000533/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000534class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000535 /// The slot lookup function. Returns a pointer to a cacheable structure
536 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000537 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000538 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
539 /// a structure describing the receiver and the class, and a selector as
540 /// arguments. Returns the slot for the corresponding method. Superclass
541 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000542 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000543 /// Type of an slot structure pointer. This is returned by the various
544 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000545 llvm::Type *SlotTy;
546 protected:
547 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
548 llvm::Value *&Receiver,
549 llvm::Value *cmd,
550 llvm::MDNode *node) {
551 CGBuilderTy &Builder = CGF.Builder;
552 llvm::Function *LookupFn = SlotLookupFn;
553
554 // Store the receiver on the stack so that we can reload it later
555 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
556 Builder.CreateStore(Receiver, ReceiverPtr);
557
558 llvm::Value *self;
559
560 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
561 self = CGF.LoadObjCSelf();
562 } else {
563 self = llvm::ConstantPointerNull::get(IdTy);
564 }
565
566 // The lookup function is guaranteed not to capture the receiver pointer.
567 LookupFn->setDoesNotCapture(1);
568
569 llvm::CallInst *slot =
570 Builder.CreateCall3(LookupFn,
571 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
572 EnforceType(Builder, cmd, SelectorTy),
573 EnforceType(Builder, self, IdTy));
574 slot->setOnlyReadsMemory();
575 slot->setMetadata(msgSendMDKind, node);
576
577 // Load the imp from the slot
578 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
579
580 // The lookup function may have changed the receiver, so make sure we use
581 // the new one.
582 Receiver = Builder.CreateLoad(ReceiverPtr, true);
583 return imp;
584 }
585 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
586 llvm::Value *ObjCSuper,
587 llvm::Value *cmd) {
588 CGBuilderTy &Builder = CGF.Builder;
589 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
590
591 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
592 lookupArgs+2);
593 slot->setOnlyReadsMemory();
594
595 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
596 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000597 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000598 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
599 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
600 PtrTy, PtrTy, IntTy, IMPTy, NULL);
601 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
602 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
603 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
604 SelectorTy, IdTy, NULL);
605 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
606 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
607 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000608 // If we're in ObjC++ mode, then we want to make
609 if (CGM.getLangOptions().CPlusPlus) {
610 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
611 // void *__cxa_begin_catch(void *e)
612 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
613 // void __cxa_end_catch(void)
614 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
615 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000616 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000617 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000618 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000619};
620
Chris Lattner0f984262008-03-01 08:50:34 +0000621} // end anonymous namespace
622
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000623
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000624/// Emits a reference to a dummy variable which is emitted with each class.
625/// This ensures that a linker error will be generated when trying to link
626/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000627void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000628 std::string symbolRef = "__objc_class_ref_" + className;
629 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000630 if (TheModule.getGlobalVariable(symbolRef))
631 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000632 std::string symbolName = "__objc_class_name_" + className;
633 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
634 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000635 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
636 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000637 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000638 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000639 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000640}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000641
David Chisnall9f6614e2011-03-23 16:36:54 +0000642static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
643 const llvm::StringRef &CategoryName, const Selector MethodName,
644 bool isClassMethod) {
645 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000646 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
647 ':', '_');
David Chisnall9f6614e2011-03-23 16:36:54 +0000648 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
649 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000650}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000651
David Chisnall9f6614e2011-03-23 16:36:54 +0000652CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
653 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000654 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
655 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
656 ProtocolVersion(protocolClassVersion) {
David Chisnall9f6614e2011-03-23 16:36:54 +0000657
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000658
659 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
660
David Chisnall9f6614e2011-03-23 16:36:54 +0000661 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000662 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000663 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000664 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000665 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000666 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000667 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000668 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000669 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000670 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000672 Int8Ty = llvm::Type::getInt8Ty(VMContext);
673 // C string type. Used in lots of places.
674 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
675
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000676 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000677 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000678 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000679 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000680 QualType selTy = CGM.getContext().getObjCSelType();
681 if (QualType() == selTy) {
682 SelectorTy = PtrToInt8Ty;
683 } else {
684 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
685 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000686
Owen Anderson96e0fc72009-07-29 22:16:19 +0000687 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000688 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattner391d77a2008-03-30 23:03:07 +0000690 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000691 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
692 ASTIdTy = CanQualType();
693 if (UnqualIdTy != QualType()) {
694 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000695 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000696 } else {
697 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000698 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000699 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
David Chisnallc7ef4622011-03-23 22:52:06 +0000701 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
702 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
703
David Chisnall9f6614e2011-03-23 16:36:54 +0000704 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
705
706 // void objc_exception_throw(id);
707 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000708 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000709 // int objc_sync_enter(id);
710 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
711 // int objc_sync_exit(id);
712 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
713
714 // void objc_enumerationMutation (id)
715 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
716 IdTy, NULL);
717
718 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
719 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
720 PtrDiffTy, BoolTy, NULL);
721 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
722 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
723 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
724 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
725 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
726 PtrDiffTy, BoolTy, BoolTy, NULL);
727 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
728 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
729 PtrDiffTy, BoolTy, BoolTy, NULL);
730
Chris Lattner391d77a2008-03-30 23:03:07 +0000731 // IMP type
732 std::vector<const llvm::Type*> IMPArgs;
733 IMPArgs.push_back(IdTy);
734 IMPArgs.push_back(SelectorTy);
David Chisnallc7ef4622011-03-23 22:52:06 +0000735 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
736 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000737
David Chisnall9735ca62011-03-25 11:57:33 +0000738 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +0000739 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
740 // Get selectors needed in GC mode
741 RetainSel = GetNullarySelector("retain", CGM.getContext());
742 ReleaseSel = GetNullarySelector("release", CGM.getContext());
743 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
744
745 // Get functions needed in GC mode
746
747 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000748 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
749 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000750 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000751 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
752 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000753 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000754 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
755 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000756 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000757 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000758 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000759 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000760 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000761 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
762 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000763 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000764}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000765
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000766// This has to perform the lookup every time, since posing and related
767// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000768llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000769 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000770 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnall41d63ed2010-01-08 00:14:31 +0000771 // With the incompatible ABI, this will need to be replaced with a direct
772 // reference to the class symbol. For the compatible nonfragile ABI we are
773 // still performing this lookup at run time but emitting the symbol for the
774 // class externally so that we can make the switch later.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000775 EmitClassRef(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000776 ClassName = Builder.CreateStructGEP(ClassName, 0);
777
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000778 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000779 llvm::Constant *ClassLookupFn =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000780 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000781 Params,
782 true),
783 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000784 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000785}
786
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000787llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000788 const std::string &TypeEncoding, bool lval) {
789
790 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
791 llvm::GlobalAlias *SelValue = 0;
792
793
794 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
795 e = Types.end() ; i!=e ; i++) {
796 if (i->first == TypeEncoding) {
797 SelValue = i->second;
798 break;
799 }
800 }
801 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000802 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000803 llvm::GlobalValue::PrivateLinkage,
804 ".objc_selector_"+Sel.getAsString(), NULL,
805 &TheModule);
806 Types.push_back(TypedSelector(TypeEncoding, SelValue));
807 }
808
David Chisnallc7ef4622011-03-23 22:52:06 +0000809 if (lval) {
810 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
811 Builder.CreateStore(SelValue, tmp);
812 return tmp;
813 }
814 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000815}
816
817llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
818 bool lval) {
819 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000820}
821
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000822llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000823 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000824 std::string SelTypes;
825 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000826 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000827}
828
John McCall5a180392010-07-24 00:37:23 +0000829llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000830 if (!CGM.getLangOptions().CPlusPlus) {
831 if (T->isObjCIdType()
832 || T->isObjCQualifiedIdType()) {
833 // With the old ABI, there was only one kind of catchall, which broke
834 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
835 // a pointer indicating object catchalls, and NULL to indicate real
836 // catchalls
837 if (CGM.getLangOptions().ObjCNonFragileABI) {
838 return MakeConstantString("@id");
839 } else {
840 return 0;
841 }
842 }
843
844 // All other types should be Objective-C interface pointer types.
845 const ObjCObjectPointerType *OPT =
846 T->getAs<ObjCObjectPointerType>();
847 assert(OPT && "Invalid @catch type.");
848 const ObjCInterfaceDecl *IDecl =
849 OPT->getObjectType()->getInterface();
850 assert(IDecl && "Invalid @catch type.");
851 return MakeConstantString(IDecl->getIdentifier()->getName());
852 }
David Chisnall80558d22011-03-20 21:35:39 +0000853 // For Objective-C++, we want to provide the ability to catch both C++ and
854 // Objective-C objects in the same function.
855
856 // There's a particular fixed type info for 'id'.
857 if (T->isObjCIdType() ||
858 T->isObjCQualifiedIdType()) {
859 llvm::Constant *IDEHType =
860 CGM.getModule().getGlobalVariable("__objc_id_type_info");
861 if (!IDEHType)
862 IDEHType =
863 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
864 false,
865 llvm::GlobalValue::ExternalLinkage,
866 0, "__objc_id_type_info");
867 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
868 }
869
870 const ObjCObjectPointerType *PT =
871 T->getAs<ObjCObjectPointerType>();
872 assert(PT && "Invalid @catch type.");
873 const ObjCInterfaceType *IT = PT->getInterfaceType();
874 assert(IT && "Invalid @catch type.");
875 std::string className = IT->getDecl()->getIdentifier()->getName();
876
877 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
878
879 // Return the existing typeinfo if it exists
880 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
881 if (typeinfo) return typeinfo;
882
883 // Otherwise create it.
884
885 // vtable for gnustep::libobjc::__objc_class_type_info
886 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
887 // platform's name mangling.
888 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
889 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
890 if (!Vtable) {
891 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
892 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
893 }
894 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
895 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
896 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
897
898 llvm::Constant *typeName =
899 ExportUniqueString(className, "__objc_eh_typename_");
900
901 std::vector<llvm::Constant*> fields;
902 fields.push_back(Vtable);
903 fields.push_back(typeName);
904 llvm::Constant *TI =
905 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
906 NULL), fields, "__objc_eh_typeinfo_" + className,
907 llvm::GlobalValue::LinkOnceODRLinkage);
908 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000909}
910
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000911/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000912llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000913
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000914 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000915
David Chisnall48272a02010-01-27 12:49:23 +0000916 // Look for an existing one
917 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
918 if (old != ObjCStrings.end())
919 return old->getValue();
920
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000921 std::vector<llvm::Constant*> Ivars;
922 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000923 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000924 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000925 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson47a434f2009-08-05 23:18:46 +0000926 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000927 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000928 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
929 ObjCStrings[Str] = ObjCStr;
930 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000931 return ObjCStr;
932}
933
934///Generates a message send where the super is the receiver. This is a message
935///send to self with special delivery semantics indicating which class's method
936///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +0000937RValue
938CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000939 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000940 QualType ResultType,
941 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000942 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000943 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000944 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000945 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000946 const CallArgList &CallArgs,
947 const ObjCMethodDecl *Method) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000948 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
949 if (Sel == RetainSel || Sel == AutoreleaseSel) {
950 return RValue::get(Receiver);
951 }
952 if (Sel == ReleaseSel) {
953 return RValue::get(0);
954 }
955 }
David Chisnalldb831942010-05-01 12:37:16 +0000956
957 CGBuilderTy &Builder = CGF.Builder;
958 llvm::Value *cmd = GetSelector(Builder, Sel);
959
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000960
961 CallArgList ActualArgs;
962
963 ActualArgs.push_back(
David Chisnallc7ef4622011-03-23 22:52:06 +0000964 std::make_pair(RValue::get(EnforceType(Builder, Receiver, IdTy)),
David Chisnall0f436562009-08-17 16:35:33 +0000965 ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000966 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
967 CGF.getContext().getObjCSelType()));
968 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
969
970 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000971 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000972 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000973
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000974 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000975 if (isCategoryImpl) {
976 llvm::Constant *classLookupFunction = 0;
977 std::vector<const llvm::Type*> Params;
978 Params.push_back(PtrTy);
979 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000980 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000981 IdTy, Params, true), "objc_get_meta_class");
982 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000983 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000984 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000985 }
David Chisnalldb831942010-05-01 12:37:16 +0000986 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000987 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000988 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000989 // Set up global aliases for the metaclass or class pointer if they do not
990 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +0000991 // pointers to the class and metaclass structure created for the runtime
992 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000993 // super_class pointer from either the class or metaclass structure.
994 if (IsClassMessage) {
995 if (!MetaClassPtrAlias) {
996 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
997 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
998 Class->getNameAsString(), NULL, &TheModule);
999 }
1000 ReceiverClass = MetaClassPtrAlias;
1001 } else {
1002 if (!ClassPtrAlias) {
1003 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1004 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1005 Class->getNameAsString(), NULL, &TheModule);
1006 }
1007 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001008 }
Chris Lattner71238f62009-04-25 23:19:45 +00001009 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001010 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001011 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001012 llvm::PointerType::getUnqual(
Owen Anderson47a434f2009-08-05 23:18:46 +00001013 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001014 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001015 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001016 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001017 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001018 // Construct the structure used to look up the IMP
Owen Anderson47a434f2009-08-05 23:18:46 +00001019 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
1020 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001021 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001022
David Chisnalldb831942010-05-01 12:37:16 +00001023 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1024 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001025
David Chisnallc7ef4622011-03-23 22:52:06 +00001026 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1027 const llvm::FunctionType *impType =
1028 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1029
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001030 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001031 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1032 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001033
David Chisnalldd5c98f2010-05-01 11:15:56 +00001034 llvm::Value *impMD[] = {
1035 llvm::MDString::get(VMContext, Sel.getAsString()),
1036 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1037 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1038 };
Jay Foad6f141652011-04-21 19:59:12 +00001039 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001040
David Chisnall4b02afc2010-05-02 13:41:58 +00001041 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001042 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001043 0, &call);
1044 call->setMetadata(msgSendMDKind, node);
1045 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001046}
1047
Mike Stump1eb44332009-09-09 15:08:12 +00001048/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001049RValue
1050CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001051 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001052 QualType ResultType,
1053 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001054 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001055 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001056 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001057 const ObjCMethodDecl *Method) {
David Chisnall664b7c72010-04-27 15:08:48 +00001058 // Strip out message sends to retain / release in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +00001059 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1060 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1061 return RValue::get(Receiver);
1062 }
1063 if (Sel == ReleaseSel) {
1064 return RValue::get(0);
1065 }
1066 }
David Chisnall664b7c72010-04-27 15:08:48 +00001067
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001068 CGBuilderTy &Builder = CGF.Builder;
David Chisnall664b7c72010-04-27 15:08:48 +00001069
1070 // If the return type is something that goes in an integer register, the
1071 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1072 // ourselves.
1073 //
1074 // The language spec says the result of this kind of message send is
1075 // undefined, but lots of people seem to have forgotten to read that
1076 // paragraph and insist on sending messages to nil that have structure
1077 // returns. With GCC, this generates a random return value (whatever happens
1078 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001079 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1080 // the stack.
1081 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1082 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001083
1084 llvm::BasicBlock *startBB = 0;
1085 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001086 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001087
1088 if (!isPointerSizedReturn) {
1089 startBB = Builder.GetInsertBlock();
1090 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001091 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001092
1093 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1094 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001095 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001096 CGF.EmitBlock(messageBB);
1097 }
1098
David Chisnall0f436562009-08-17 16:35:33 +00001099 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001100 llvm::Value *cmd;
1101 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001102 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001103 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001104 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001105 cmd = EnforceType(Builder, cmd, SelectorTy);
1106 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001107
David Chisnallc7ef4622011-03-23 22:52:06 +00001108 llvm::Value *impMD[] = {
1109 llvm::MDString::get(VMContext, Sel.getAsString()),
1110 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1111 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1112 };
Jay Foad6f141652011-04-21 19:59:12 +00001113 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001114
1115 // Get the IMP to call
1116 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1117
1118 CallArgList ActualArgs;
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001119 ActualArgs.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001120 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001121 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
1122 CGF.getContext().getObjCSelType()));
1123 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1124
1125 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001126 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001127 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +00001128 const llvm::FunctionType *impType =
1129 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001130 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001131
1132
Fariborz Jahanian34e65772009-05-22 20:17:16 +00001133 // For sender-aware dispatch, we pass the sender as the third argument to a
1134 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001135 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnall4b02afc2010-05-02 13:41:58 +00001136 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001137 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001138 0, &call);
1139 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001140
David Chisnalla54da052010-05-20 13:45:48 +00001141
David Chisnall664b7c72010-04-27 15:08:48 +00001142 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001143 messageBB = CGF.Builder.GetInsertBlock();
1144 CGF.Builder.CreateBr(continueBB);
1145 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001146 if (msgRet.isScalar()) {
1147 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001148 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001149 phi->addIncoming(v, messageBB);
1150 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1151 msgRet = RValue::get(phi);
1152 } else if (msgRet.isAggregate()) {
1153 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001154 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001155 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001156 llvm::AllocaInst *NullVal =
1157 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001158 CGF.InitTempAlloca(NullVal,
1159 llvm::Constant::getNullValue(RetTy->getElementType()));
1160 phi->addIncoming(v, messageBB);
1161 phi->addIncoming(NullVal, startBB);
1162 msgRet = RValue::getAggregate(phi);
1163 } else /* isComplex() */ {
1164 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001165 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001166 phi->addIncoming(v.first, messageBB);
1167 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1168 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001169 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001170 phi2->addIncoming(v.second, messageBB);
1171 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1172 startBB);
1173 msgRet = RValue::getComplex(phi, phi2);
1174 }
1175 }
1176 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001177}
1178
Mike Stump1eb44332009-09-09 15:08:12 +00001179/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001180/// objc_category structures.
David Chisnall9f6614e2011-03-23 16:36:54 +00001181llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1182 const llvm::StringRef &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +00001183 const llvm::SmallVectorImpl<Selector> &MethodSels,
1184 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001185 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001186 if (MethodSels.empty())
1187 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001188 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +00001189 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001190 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1191 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001192 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001193 NULL);
1194 std::vector<llvm::Constant*> Methods;
1195 std::vector<llvm::Constant*> Elements;
1196 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1197 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001198 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001199 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001200 MethodSels[i],
1201 isClassMethodList));
1202 assert(Method && "Can't generate metadata for method that doesn't exist");
1203 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1204 Elements.push_back(C);
1205 Elements.push_back(MethodTypes[i]);
1206 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001207 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001208 Elements.push_back(Method);
1209 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001210 }
1211
1212 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001213 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001214 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001215 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001216 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001217
1218 // Structure containing list pointer, array and array count
1219 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Anderson8c8f69e2009-08-13 23:27:53 +00001220 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001221 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson47a434f2009-08-05 23:18:46 +00001222 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump1eb44332009-09-09 15:08:12 +00001223 NextPtrTy,
1224 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001225 ObjCMethodArrayTy,
1226 NULL);
1227 // Refine next pointer type to concrete type
1228 llvm::cast<llvm::OpaqueType>(
1229 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1230 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1231
1232 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001233 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001234 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +00001235 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001236 MethodTypes.size()));
1237 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001239 // Create an instance of the structure
1240 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1241}
1242
1243/// Generates an IvarList. Used in construction of a objc_class.
1244llvm::Constant *CGObjCGNU::GenerateIvarList(
1245 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1246 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1247 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001248 if (IvarNames.size() == 0)
1249 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001250 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +00001251 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001252 PtrToInt8Ty,
1253 PtrToInt8Ty,
1254 IntTy,
1255 NULL);
1256 std::vector<llvm::Constant*> Ivars;
1257 std::vector<llvm::Constant*> Elements;
1258 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1259 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001260 Elements.push_back(IvarNames[i]);
1261 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001262 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001263 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001264 }
1265
1266 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001267 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001268 IvarNames.size());
1269
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001271 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001272 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001273 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001274 // Structure containing array and array count
Owen Anderson47a434f2009-08-05 23:18:46 +00001275 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001276 ObjCIvarArrayTy,
1277 NULL);
1278
1279 // Create an instance of the structure
1280 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1281}
1282
1283/// Generate a class structure
1284llvm::Constant *CGObjCGNU::GenerateClassStructure(
1285 llvm::Constant *MetaClass,
1286 llvm::Constant *SuperClass,
1287 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001288 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001289 llvm::Constant *Version,
1290 llvm::Constant *InstanceSize,
1291 llvm::Constant *IVars,
1292 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001293 llvm::Constant *Protocols,
1294 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001295 llvm::Constant *Properties,
1296 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001297 // Set up the class structure
1298 // Note: Several of these are char*s when they should be ids. This is
1299 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001300 //
1301 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1302 // anyway; the classes will still work with the GNU runtime, they will just
1303 // be ignored.
Owen Anderson47a434f2009-08-05 23:18:46 +00001304 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001305 PtrToInt8Ty, // class_pointer
1306 PtrToInt8Ty, // super_class
1307 PtrToInt8Ty, // name
1308 LongTy, // version
1309 LongTy, // info
1310 LongTy, // instance_size
1311 IVars->getType(), // ivars
1312 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001313 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001314 PtrTy, // dtable
1315 PtrTy, // subclass_list
1316 PtrTy, // sibling_class
1317 PtrTy, // protocols
1318 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001319 // New ABI:
1320 LongTy, // abi_version
1321 IvarOffsets->getType(), // ivar_offsets
1322 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001323 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001324 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001325 // Fill in the structure
1326 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001327 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001328 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001329 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001330 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001331 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001332 if (isMeta) {
1333 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001334 Elements.push_back(
1335 llvm::ConstantInt::get(LongTy,
1336 td.getTypeSizeInBits(ClassTy) /
1337 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001338 } else
1339 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001340 Elements.push_back(IVars);
1341 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001342 Elements.push_back(NULLPtr);
1343 Elements.push_back(NULLPtr);
1344 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001345 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001346 Elements.push_back(NULLPtr);
1347 Elements.push_back(Zero);
1348 Elements.push_back(IvarOffsets);
1349 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001350 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001351 // This is now an externally visible symbol, so that we can speed up class
1352 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +00001353 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1354 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001355}
1356
1357llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1358 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1359 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001360 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +00001361 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001362 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1363 PtrToInt8Ty,
1364 NULL);
1365 std::vector<llvm::Constant*> Methods;
1366 std::vector<llvm::Constant*> Elements;
1367 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1368 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001369 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001370 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001371 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001372 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001373 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001374 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001375 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001376 Methods);
Owen Anderson47a434f2009-08-05 23:18:46 +00001377 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001378 IntTy, ObjCMethodArrayTy, NULL);
1379 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001380 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001381 Methods.push_back(Array);
1382 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1383}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001384
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001385// Create the protocol list structure used in classes, categories and so on
1386llvm::Constant *CGObjCGNU::GenerateProtocolList(
1387 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001388 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001389 Protocols.size());
Owen Anderson47a434f2009-08-05 23:18:46 +00001390 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001391 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001392 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001393 ProtocolArrayTy,
1394 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001395 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001396 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1397 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001398 llvm::Constant *protocol = 0;
1399 llvm::StringMap<llvm::Constant*>::iterator value =
1400 ExistingProtocols.find(*iter);
1401 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001402 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001403 } else {
1404 protocol = value->getValue();
1405 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001406 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001407 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001408 Elements.push_back(Ptr);
1409 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001410 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001411 Elements);
1412 Elements.clear();
1413 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001414 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001415 Elements.push_back(ProtocolArray);
1416 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1417}
1418
Mike Stump1eb44332009-09-09 15:08:12 +00001419llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001420 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001421 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001422 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001423 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001424 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001425}
1426
1427llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1428 const std::string &ProtocolName) {
1429 llvm::SmallVector<std::string, 0> EmptyStringVector;
1430 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1431
1432 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001433 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001434 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1435 // Protocols are objects containing lists of the methods implemented and
1436 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001437 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001438 PtrToInt8Ty,
1439 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001440 MethodList->getType(),
1441 MethodList->getType(),
1442 MethodList->getType(),
1443 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001444 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001445 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001446 // The isa pointer must be set to a magic number so the runtime knows it's
1447 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001448 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001449 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1450 ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001451 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1452 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001453 Elements.push_back(MethodList);
1454 Elements.push_back(MethodList);
1455 Elements.push_back(MethodList);
1456 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001457 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001458}
1459
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001460void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1461 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001462 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001463 llvm::SmallVector<std::string, 16> Protocols;
1464 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1465 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001466 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001467 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1468 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001469 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1470 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001471 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1472 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001473 std::string TypeStr;
1474 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001475 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1476 InstanceMethodNames.push_back(
1477 MakeConstantString((*iter)->getSelector().getAsString()));
1478 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1479 } else {
1480 OptionalInstanceMethodNames.push_back(
1481 MakeConstantString((*iter)->getSelector().getAsString()));
1482 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1483 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001484 }
1485 // Collect information about class methods:
1486 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1487 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001488 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1489 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001490 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001491 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1492 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001493 std::string TypeStr;
1494 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001495 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1496 ClassMethodNames.push_back(
1497 MakeConstantString((*iter)->getSelector().getAsString()));
1498 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1499 } else {
1500 OptionalClassMethodNames.push_back(
1501 MakeConstantString((*iter)->getSelector().getAsString()));
1502 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1503 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001504 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001505
1506 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1507 llvm::Constant *InstanceMethodList =
1508 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1509 llvm::Constant *ClassMethodList =
1510 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001511 llvm::Constant *OptionalInstanceMethodList =
1512 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1513 OptionalInstanceMethodTypes);
1514 llvm::Constant *OptionalClassMethodList =
1515 GenerateProtocolMethodList(OptionalClassMethodNames,
1516 OptionalClassMethodTypes);
1517
1518 // Property metadata: name, attributes, isSynthesized, setter name, setter
1519 // types, getter name, getter types.
1520 // The isSynthesized value is always set to 0 in a protocol. It exists to
1521 // simplify the runtime library by allowing it to use the same data
1522 // structures for protocol metadata everywhere.
1523 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1524 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1525 PtrToInt8Ty, NULL);
1526 std::vector<llvm::Constant*> Properties;
1527 std::vector<llvm::Constant*> OptionalProperties;
1528
1529 // Add all of the property methods need adding to the method list and to the
1530 // property metadata list.
1531 for (ObjCContainerDecl::prop_iterator
1532 iter = PD->prop_begin(), endIter = PD->prop_end();
1533 iter != endIter ; iter++) {
1534 std::vector<llvm::Constant*> Fields;
1535 ObjCPropertyDecl *property = (*iter);
1536
1537 Fields.push_back(MakeConstantString(property->getNameAsString()));
1538 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1539 property->getPropertyAttributes()));
1540 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1541 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1542 std::string TypeStr;
1543 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1544 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1545 InstanceMethodTypes.push_back(TypeEncoding);
1546 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1547 Fields.push_back(TypeEncoding);
1548 } else {
1549 Fields.push_back(NULLPtr);
1550 Fields.push_back(NULLPtr);
1551 }
1552 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1553 std::string TypeStr;
1554 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1555 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1556 InstanceMethodTypes.push_back(TypeEncoding);
1557 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1558 Fields.push_back(TypeEncoding);
1559 } else {
1560 Fields.push_back(NULLPtr);
1561 Fields.push_back(NULLPtr);
1562 }
1563 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1564 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1565 } else {
1566 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1567 }
1568 }
1569 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1570 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1571 llvm::Constant* PropertyListInitFields[] =
1572 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1573
1574 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001575 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001576 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1577 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1578 PropertyListInit, ".objc_property_list");
1579
1580 llvm::Constant *OptionalPropertyArray =
1581 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1582 OptionalProperties.size()) , OptionalProperties);
1583 llvm::Constant* OptionalPropertyListInitFields[] = {
1584 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1585 OptionalPropertyArray };
1586
1587 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001588 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001589 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1590 OptionalPropertyListInit->getType(), false,
1591 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1592 ".objc_property_list");
1593
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001594 // Protocols are objects containing lists of the methods implemented and
1595 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001596 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001597 PtrToInt8Ty,
1598 ProtocolList->getType(),
1599 InstanceMethodList->getType(),
1600 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001601 OptionalInstanceMethodList->getType(),
1602 OptionalClassMethodList->getType(),
1603 PropertyList->getType(),
1604 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001605 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001606 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001607 // The isa pointer must be set to a magic number so the runtime knows it's
1608 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001609 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001610 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1611 ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001612 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1613 Elements.push_back(ProtocolList);
1614 Elements.push_back(InstanceMethodList);
1615 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001616 Elements.push_back(OptionalInstanceMethodList);
1617 Elements.push_back(OptionalClassMethodList);
1618 Elements.push_back(PropertyList);
1619 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001620 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001621 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001622 ".objc_protocol"), IdTy);
1623}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001624void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1625 // Collect information about instance methods
1626 llvm::SmallVector<Selector, 1> MethodSels;
1627 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1628
1629 std::vector<llvm::Constant*> Elements;
1630 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1631 const std::string CategoryName = "AnotherHack";
1632 Elements.push_back(MakeConstantString(CategoryName));
1633 Elements.push_back(MakeConstantString(ClassName));
1634 // Instance method list
1635 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1636 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1637 // Class method list
1638 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1639 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1640 // Protocol list
1641 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1642 ExistingProtocols.size());
1643 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1644 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001645 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001646 ProtocolArrayTy,
1647 NULL);
1648 std::vector<llvm::Constant*> ProtocolElements;
1649 for (llvm::StringMapIterator<llvm::Constant*> iter =
1650 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1651 iter != endIter ; iter++) {
1652 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1653 PtrTy);
1654 ProtocolElements.push_back(Ptr);
1655 }
1656 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1657 ProtocolElements);
1658 ProtocolElements.clear();
1659 ProtocolElements.push_back(NULLPtr);
1660 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1661 ExistingProtocols.size()));
1662 ProtocolElements.push_back(ProtocolArray);
1663 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1664 ProtocolElements, ".objc_protocol_list"), PtrTy));
1665 Categories.push_back(llvm::ConstantExpr::getBitCast(
1666 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1667 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1668}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001669
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001670void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001671 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1672 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001673 // Collect information about instance methods
1674 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1675 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001676 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001677 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001678 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001679 InstanceMethodSels.push_back((*iter)->getSelector());
1680 std::string TypeStr;
1681 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001682 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001683 }
1684
1685 // Collect information about class methods
1686 llvm::SmallVector<Selector, 16> ClassMethodSels;
1687 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001688 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001689 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001690 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001691 ClassMethodSels.push_back((*iter)->getSelector());
1692 std::string TypeStr;
1693 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001694 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001695 }
1696
1697 // Collect the names of referenced protocols
1698 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001699 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1700 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001701 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1702 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001703 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001704
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001705 std::vector<llvm::Constant*> Elements;
1706 Elements.push_back(MakeConstantString(CategoryName));
1707 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001708 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001709 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001710 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001711 false), PtrTy));
1712 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001713 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001714 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001715 PtrTy));
1716 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001717 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001718 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001719 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump1eb44332009-09-09 15:08:12 +00001720 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001721 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001722}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001723
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001724llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1725 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1726 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1727 ASTContext &Context = CGM.getContext();
1728 //
1729 // Property metadata: name, attributes, isSynthesized, setter name, setter
1730 // types, getter name, getter types.
1731 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1732 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1733 PtrToInt8Ty, NULL);
1734 std::vector<llvm::Constant*> Properties;
1735
1736
1737 // Add all of the property methods need adding to the method list and to the
1738 // property metadata list.
1739 for (ObjCImplDecl::propimpl_iterator
1740 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1741 iter != endIter ; iter++) {
1742 std::vector<llvm::Constant*> Fields;
1743 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001744 ObjCPropertyImplDecl *propertyImpl = *iter;
1745 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1746 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001747
1748 Fields.push_back(MakeConstantString(property->getNameAsString()));
1749 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1750 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001751 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001752 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001753 std::string TypeStr;
1754 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1755 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001756 if (isSynthesized) {
1757 InstanceMethodTypes.push_back(TypeEncoding);
1758 InstanceMethodSels.push_back(getter->getSelector());
1759 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001760 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1761 Fields.push_back(TypeEncoding);
1762 } else {
1763 Fields.push_back(NULLPtr);
1764 Fields.push_back(NULLPtr);
1765 }
1766 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001767 std::string TypeStr;
1768 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1769 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001770 if (isSynthesized) {
1771 InstanceMethodTypes.push_back(TypeEncoding);
1772 InstanceMethodSels.push_back(setter->getSelector());
1773 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001774 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1775 Fields.push_back(TypeEncoding);
1776 } else {
1777 Fields.push_back(NULLPtr);
1778 Fields.push_back(NULLPtr);
1779 }
1780 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1781 }
1782 llvm::ArrayType *PropertyArrayTy =
1783 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1784 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1785 Properties);
1786 llvm::Constant* PropertyListInitFields[] =
1787 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1788
1789 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001790 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001791 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1792 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1793 ".objc_property_list");
1794}
1795
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001796void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1797 ASTContext &Context = CGM.getContext();
1798
1799 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001800 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001801 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001802 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001803 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001804 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001805 EmitClassRef(SuperClassName);
1806 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001807
1808 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001809 ObjCInterfaceDecl *ClassDecl =
1810 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001811 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001812 // Emit the symbol that is used to generate linker errors if this class is
1813 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001814 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001815 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001816 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001817 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001818 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001819 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001820 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001821 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001822 }
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001824 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001825 int instanceSize =
1826 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001827
1828 // Collect information about instance variables.
1829 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1830 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1831 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001833 std::vector<llvm::Constant*> IvarOffsetValues;
1834
Mike Stump1eb44332009-09-09 15:08:12 +00001835 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001836 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001837 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1838 // class}. The runtime will then set this to the correct value on load.
1839 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1840 instanceSize = 0 - (instanceSize - superInstanceSize);
1841 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001842
1843 // Collect declared and synthesized ivars.
1844 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1845 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1846
1847 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1848 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001849 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001850 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001851 // Get the type encoding for this ivar
1852 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001853 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001854 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001855 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001856 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001857 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001858 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001859 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001860 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001861 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001862 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001863 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1864 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle0d98762010-11-03 16:12:44 +00001865 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001866 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001867 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001868 }
David Chisnall9f6614e2011-03-23 16:36:54 +00001869 llvm::GlobalVariable *IvarOffsetArray =
1870 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1871
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001872
1873 // Collect information about instance methods
1874 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1875 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001876 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001877 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001878 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001879 InstanceMethodSels.push_back((*iter)->getSelector());
1880 std::string TypeStr;
1881 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001882 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001883 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001884
1885 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1886 InstanceMethodTypes);
1887
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001888
1889 // Collect information about class methods
1890 llvm::SmallVector<Selector, 16> ClassMethodSels;
1891 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001892 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001893 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001894 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001895 ClassMethodSels.push_back((*iter)->getSelector());
1896 std::string TypeStr;
1897 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001898 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001899 }
1900 // Collect the names of referenced protocols
1901 llvm::SmallVector<std::string, 16> Protocols;
1902 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1903 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1904 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001905 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001906
1907
1908
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001909 // Get the superclass pointer.
1910 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001911 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001912 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1913 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001914 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001915 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001916 // Empty vector used to construct empty method lists
1917 llvm::SmallVector<llvm::Constant*, 1> empty;
1918 // Generate the method and instance variable lists
1919 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001920 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001921 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001922 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001923 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1924 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001925 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001926 // we emit a symbol containing the offset for each ivar in the class. This
1927 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1928 // for the legacy ABI, without causing problems. The converse is also
1929 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001930
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001931 // Offset pointer for getting at the correct field in the ivar list when
1932 // setting up the alias. These are: The base address for the global, the
1933 // ivar array (second field), the ivar in this list (set for each ivar), and
1934 // the offset (third field in ivar structure)
1935 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1936 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001937 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001938 llvm::ConstantInt::get(IndexTy, 2) };
1939
David Chisnalle0d98762010-11-03 16:12:44 +00001940
1941 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1942 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001943 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001944 + IVD->getNameAsString();
1945 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001946 // Get the correct ivar field
1947 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1948 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001949 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001950 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1951 if (offset) {
1952 offset->setInitializer(offsetValue);
1953 // If this is the real definition, change its linkage type so that
1954 // different modules will use this one, rather than their private
1955 // copy.
1956 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1957 } else {
1958 // Add a new alias if there isn't one already.
1959 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1960 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1961 }
1962 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001963 //Generate metaclass for class methods
1964 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001965 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001966 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001967
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001968 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001969 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001970 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001971 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001972 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001973 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1974 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001975
1976 // Resolve the class aliases, if they exist.
1977 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001978 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001979 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001980 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001981 ClassPtrAlias = 0;
1982 }
1983 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001984 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001985 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001986 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001987 MetaClassPtrAlias = 0;
1988 }
1989
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001990 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001991 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001992 Classes.push_back(ClassStruct);
1993}
1994
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001995
Mike Stump1eb44332009-09-09 15:08:12 +00001996llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001997 // Only emit an ObjC load function if no Objective-C stuff has been called
1998 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00001999 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002000 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002001
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002002 // Add all referenced protocols to a category.
2003 GenerateProtocolHolderCategory();
2004
Chris Lattnere160c9b2009-01-27 05:06:01 +00002005 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2006 SelectorTy->getElementType());
2007 const llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002008 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00002009 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
2010 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002011 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002012 }
2013
Eli Friedman1b8956e2008-06-01 16:00:02 +00002014 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00002015 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00002016 TheModule.addTypeName(".objc_id", IdTy);
2017 TheModule.addTypeName(".objc_imp", IMPTy);
2018
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002019 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002020 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002021 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002022 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002023 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002024 ConstantStrings.size() + 1);
2025 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002026
Daniel Dunbar1b096952009-11-29 02:38:47 +00002027 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002028
Daniel Dunbar1b096952009-11-29 02:38:47 +00002029 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002030
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002031 Elements.push_back(MakeConstantString(StringClass,
2032 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002033 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002034 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002035 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00002036 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002037 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002038 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002039 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002040 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002041 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002042 Elements.clear();
2043 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002044 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002045 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002046 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002047 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002048 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002049 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002050 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00002051 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00002052 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002053 llvm::Type::getInt16Ty(VMContext),
2054 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002055 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002056
2057 Elements.clear();
2058 // Pointer to an array of selectors used in this module.
2059 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002060 std::vector<llvm::GlobalAlias*> SelectorAliases;
2061 for (SelectorMap::iterator iter = SelectorTable.begin(),
2062 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2063
2064 std::string SelNameStr = iter->first.getAsString();
2065 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2066
2067 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2068 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2069 e = Types.end() ; i!=e ; i++) {
2070
2071 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2072 if (!i->first.empty())
2073 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2074
2075 Elements.push_back(SelName);
2076 Elements.push_back(SelectorTypeEncoding);
2077 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2078 Elements.clear();
2079
2080 // Store the selector alias for later replacement
2081 SelectorAliases.push_back(i->second);
2082 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002083 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002084 unsigned SelectorCount = Selectors.size();
2085 // NULL-terminate the selector list. This should not actually be required,
2086 // because the selector list has a length field. Unfortunately, the GCC
2087 // runtime decides to ignore the length field and expects a NULL terminator,
2088 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002089 Elements.push_back(NULLPtr);
2090 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002091 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002092 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002093
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002094 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002095 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2096 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002097 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002098 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002099 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002100
2101 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002102 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2103
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002104 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall9f6614e2011-03-23 16:36:54 +00002105 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2106 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002107 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2108 Idxs, 2);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002109 // If selectors are defined as an opaque type, cast the pointer to this
2110 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002111 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002112 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2113 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002114 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002115
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002116 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002117 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002118 Classes.size()));
2119 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002120 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002121 Categories.size()));
2122 // Create an array of classes, then categories, then static object instances
2123 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2124 // NULL-terminated list of static object instances (mainly constant strings)
2125 Classes.push_back(Statics);
2126 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002127 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002128 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002129 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002130 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2131
2132 // The symbol table is contained in a module which has some version-checking
2133 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00002134 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002135 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002136 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002137 // Runtime version, used for ABI compatibility checking.
2138 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002139 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002140 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002141 Elements.push_back(
2142 llvm::ConstantInt::get(LongTy,
2143 td.getTypeSizeInBits(ModuleTy) /
2144 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002145
2146 // The path to the source file where this module was declared
2147 SourceManager &SM = CGM.getContext().getSourceManager();
2148 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2149 std::string path =
2150 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2151 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2152
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002153 Elements.push_back(SymTab);
2154 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2155
2156 // Create the load function calling the runtime entry point with the module
2157 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002158 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002159 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002160 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2161 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002162 llvm::BasicBlock *EntryBB =
2163 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002164 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002165 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002166
2167 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002168 llvm::PointerType::getUnqual(ModuleTy));
2169 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00002170 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002171 Builder.CreateCall(Register, Module);
2172 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002173
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002174 return LoadFunction;
2175}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002176
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002177llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002178 const ObjCContainerDecl *CD) {
2179 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002180 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnall9f6614e2011-03-23 16:36:54 +00002181 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2182 llvm::StringRef ClassName = CD->getName();
2183 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002184 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002185
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002186 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00002187 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002188 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002189 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2190 MethodName, isClassMethod);
2191
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002192 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002193 = llvm::Function::Create(MethodTy,
2194 llvm::GlobalValue::InternalLinkage,
2195 FunctionName,
2196 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002197 return Method;
2198}
2199
Daniel Dunbar49f66022008-09-24 03:38:44 +00002200llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002201 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002202}
2203
2204llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002205 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002206}
2207
David Chisnall8fac25d2010-12-26 22:13:16 +00002208llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002209 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002210}
2211llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002212 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002213}
2214
Daniel Dunbar309a4362009-07-24 07:40:24 +00002215llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002216 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002217}
2218
David Chisnall9f6614e2011-03-23 16:36:54 +00002219void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002220 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002221 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002222}
Chris Lattner5dc08672009-05-08 00:11:50 +00002223
David Chisnall0faa5162009-12-24 02:26:34 +00002224
David Chisnall9f6614e2011-03-23 16:36:54 +00002225void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002226 const ObjCAtTryStmt &S) {
2227 // Unlike the Apple non-fragile runtimes, which also uses
2228 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2229 // EH support isn't a veneer over C++ EH. Instead, exception
2230 // objects are created by __objc_exception_throw and destroyed by
2231 // the personality function; this avoids the need for bracketing
2232 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2233 // (or even _Unwind_DeleteException), but probably doesn't
2234 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002235 //
David Chisnall80558d22011-03-20 21:35:39 +00002236 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002237 // exception handler.
2238 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2239 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002240}
2241
David Chisnall9f6614e2011-03-23 16:36:54 +00002242void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002243 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002244 llvm::Value *ExceptionAsObject;
2245
Chris Lattner5dc08672009-05-08 00:11:50 +00002246 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2247 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002248 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002249 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002250 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002251 "Unexpected rethrow outside @catch block.");
2252 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2253 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002254 ExceptionAsObject =
2255 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Chris Lattner5dc08672009-05-08 00:11:50 +00002257 // Note: This may have to be an invoke, if we want to support constructs like:
2258 // @try {
2259 // @throw(obj);
2260 // }
2261 // @catch(id) ...
2262 //
2263 // This is effectively turning @throw into an incredibly-expensive goto, but
2264 // it may happen as a result of inlining followed by missed optimizations, or
2265 // as a result of stupidity.
2266 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2267 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002268 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002269 CGF.Builder.CreateUnreachable();
2270 } else {
David Chisnall9f6614e2011-03-23 16:36:54 +00002271 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattner5dc08672009-05-08 00:11:50 +00002272 &ExceptionAsObject+1);
2273 }
2274 // Clear the insertion point to indicate we are in unreachable code.
2275 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002276}
2277
David Chisnall9f6614e2011-03-23 16:36:54 +00002278llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002279 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002280 CGBuilderTy B = CGF.Builder;
2281 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2282 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002283}
2284
David Chisnall9f6614e2011-03-23 16:36:54 +00002285void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002286 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002287 CGBuilderTy B = CGF.Builder;
2288 src = EnforceType(B, src, IdTy);
2289 dst = EnforceType(B, dst, PtrToIdTy);
2290 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002291}
2292
David Chisnall9f6614e2011-03-23 16:36:54 +00002293void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002294 llvm::Value *src, llvm::Value *dst,
2295 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002296 CGBuilderTy B = CGF.Builder;
2297 src = EnforceType(B, src, IdTy);
2298 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002299 if (!threadlocal)
2300 B.CreateCall2(GlobalAssignFn, src, dst);
2301 else
2302 // FIXME. Add threadloca assign API
2303 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002304}
2305
David Chisnall9f6614e2011-03-23 16:36:54 +00002306void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002307 llvm::Value *src, llvm::Value *dst,
2308 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002309 CGBuilderTy B = CGF.Builder;
2310 src = EnforceType(B, src, IdTy);
2311 dst = EnforceType(B, dst, PtrToIdTy);
2312 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002313}
2314
David Chisnall9f6614e2011-03-23 16:36:54 +00002315void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002316 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002317 CGBuilderTy B = CGF.Builder;
2318 src = EnforceType(B, src, IdTy);
2319 dst = EnforceType(B, dst, PtrToIdTy);
2320 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002321}
2322
David Chisnall9f6614e2011-03-23 16:36:54 +00002323void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002324 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002325 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002326 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002327 CGBuilderTy B = CGF.Builder;
2328 DestPtr = EnforceType(B, DestPtr, IdTy);
2329 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2330
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002331 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002332}
2333
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002334llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2335 const ObjCInterfaceDecl *ID,
2336 const ObjCIvarDecl *Ivar) {
2337 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2338 + '.' + Ivar->getNameAsString();
2339 // Emit the variable and initialize it with what we think the correct value
2340 // is. This allows code compiled with non-fragile ivars to work correctly
2341 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002342 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2343 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002344 // This will cause a run-time crash if we accidentally use it. A value of
2345 // 0 would seem more sensible, but will silently overwrite the isa pointer
2346 // causing a great deal of confusion.
2347 uint64_t Offset = -1;
2348 // We can't call ComputeIvarBaseOffset() here if we have the
2349 // implementation, because it will create an invalid ASTRecordLayout object
2350 // that we are then stuck with forever, so we only initialize the ivar
2351 // offset variable with a guess if we only have the interface. The
2352 // initializer will be reset later anyway, when we are generating the class
2353 // description.
2354 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002355 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002356 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2357
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002358 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002359 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002360 // Don't emit the guess in non-PIC code because the linker will not be able
2361 // to replace it with the real version for a library. In non-PIC code you
2362 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002363 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002364 if (CGM.getLangOptions().PICLevel) {
2365 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2366 llvm::Type::getInt32Ty(VMContext), false,
2367 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2368 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2369 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2370 IvarOffsetGV, Name);
2371 } else {
2372 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002373 llvm::Type::getInt32PtrTy(VMContext), false,
2374 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002375 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002376 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002377 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002378}
2379
David Chisnall9f6614e2011-03-23 16:36:54 +00002380LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002381 QualType ObjectTy,
2382 llvm::Value *BaseValue,
2383 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002384 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002385 const ObjCInterfaceDecl *ID =
2386 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002387 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2388 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002389}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002390
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002391static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2392 const ObjCInterfaceDecl *OID,
2393 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002394 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002395 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002396 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2397 if (OIVD == Ivars[k])
2398 return OID;
2399 }
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002401 // Otherwise check in the super class.
2402 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2403 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002405 return 0;
2406}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002407
David Chisnall9f6614e2011-03-23 16:36:54 +00002408llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002409 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002410 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002411 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002412 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002413 return CGF.Builder.CreateZExtOrBitCast(
2414 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2415 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2416 PtrDiffTy);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002417 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002418 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002419 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002420}
2421
David Chisnall9f6614e2011-03-23 16:36:54 +00002422CGObjCRuntime *
2423clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2424 if (CGM.getLangOptions().ObjCNonFragileABI)
2425 return new CGObjCGNUstep(CGM);
2426 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002427}