blob: c7741ce86f34adb849507164c5b7935fc41394c2 [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
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000039#include <map>
David Chisnall9f6614e2011-03-23 16:36:54 +000040#include <stdarg.h>
Chris Lattnere160c9b2009-01-27 05:06:01 +000041
42
Chris Lattnerdce14062008-06-26 04:19:03 +000043using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000044using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000045using llvm::dyn_cast;
46
Chris Lattner0f984262008-03-01 08:50:34 +000047
Chris Lattner0f984262008-03-01 08:50:34 +000048namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000049/// Class that lazily initialises the runtime function. Avoids inserting the
50/// types and the function declaration into a module if they're not used, and
51/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000052class LazyRuntimeFunction {
53 CodeGenModule *CGM;
54 std::vector<const llvm::Type*> ArgTys;
55 const char *FunctionName;
56 llvm::Function *Function;
57 public:
David Chisnall81a65f52011-03-26 11:48:37 +000058 /// Constructor leaves this class uninitialized, because it is intended to
59 /// be used as a field in another class and not all of the types that are
60 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000061 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
62
David Chisnall81a65f52011-03-26 11:48:37 +000063 /// Initialises the lazy function with the name, return type, and the types
64 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000065 END_WITH_NULL
66 void init(CodeGenModule *Mod, const char *name,
67 const llvm::Type *RetTy, ...) {
68 CGM =Mod;
69 FunctionName = name;
70 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000071 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000072 va_list Args;
73 va_start(Args, RetTy);
74 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
75 ArgTys.push_back(ArgTy);
76 va_end(Args);
77 // Push the return type on at the end so we can pop it off easily
78 ArgTys.push_back(RetTy);
79 }
David Chisnall81a65f52011-03-26 11:48:37 +000080 /// Overloaded cast operator, allows the class to be implicitly cast to an
81 /// LLVM constant.
David Chisnall9f6614e2011-03-23 16:36:54 +000082 operator llvm::Function*() {
83 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000084 if (0 == FunctionName) return 0;
85 // We put the return type on the end of the vector, so pop it back off
David Chisnall9f6614e2011-03-23 16:36:54 +000086 const llvm::Type *RetTy = ArgTys.back();
87 ArgTys.pop_back();
88 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
89 Function =
90 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000091 // We won't need to use the types again, so we may as well clean up the
92 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000093 ArgTys.resize(0);
94 }
95 return Function;
96 }
97};
98
99
David Chisnall81a65f52011-03-26 11:48:37 +0000100/// GNU Objective-C runtime code generation. This class implements the parts of
101/// Objective-C support that are specific to the GNU family of runtimes (GCC and
102/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000103class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000104protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000105 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000106 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000107 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000108 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000109 /// strut objc_super. Used for sending messages to super. This structure
110 /// contains the receiver (object) and the expected class.
David Chisnallc7ef4622011-03-23 22:52:06 +0000111 const llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000112 /// struct objc_super*. The type of the argument to the superclass message
113 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000114 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000115 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
116 /// SEL is included in a header somewhere, in which case it will be whatever
117 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000118 const llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000119 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
120 /// places where it's used
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000121 const llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000122 /// Pointer to i8 - LLVM type of char*, for all of the places where the
123 /// runtime needs to deal with C strings.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000124 const llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000125 /// Instance Method Pointer type. This is a pointer to a function that takes,
126 /// at a minimum, an object and a selector, and is the generic type for
127 /// Objective-C methods. Due to differences between variadic / non-variadic
128 /// calling conventions, it must always be cast to the correct type before
129 /// actually being used.
David Chisnallc7ef4622011-03-23 22:52:06 +0000130 const llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000131 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
132 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
133 /// but if the runtime header declaring it is included then it may be a
134 /// pointer to a structure.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000135 const llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000136 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
137 /// message lookup function and some GC-related functions.
David Chisnallef6e0f32010-02-03 15:59:02 +0000138 const llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000139 /// The clang type of id. Used when using the clang CGCall infrastructure to
140 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000141 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000142 /// LLVM type for C int type.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000143 const llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000144 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
145 /// used in the code to document the difference between i8* meaning a pointer
146 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000147 const llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000148 /// LLVM type for C long type. The runtime uses this in a lot of places where
149 /// it should be using intptr_t, but we can't fix this without breaking
150 /// compatibility with GCC...
Chris Lattnere160c9b2009-01-27 05:06:01 +0000151 const llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000152 /// LLVM type for C size_t. Used in various runtime data structures.
David Chisnall8fac25d2010-12-26 22:13:16 +0000153 const llvm::IntegerType *SizeTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000154 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
David Chisnall8fac25d2010-12-26 22:13:16 +0000155 const llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000156 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
157 /// variables.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000158 const llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000159 /// LLVM type for Objective-C BOOL type.
David Chisnall8fac25d2010-12-26 22:13:16 +0000160 const llvm::Type *BoolTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000161 /// Metadata kind used to tie method lookups to message sends. The GNUstep
162 /// runtime provides some LLVM passes that can use this to do things like
163 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000164 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000165 /// Helper function that generates a constant string and returns a pointer to
166 /// the start of the string. The result of this function can be used anywhere
167 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000168 llvm::Constant *MakeConstantString(const std::string &Str,
169 const std::string &Name="") {
170 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
171 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
172 }
David Chisnall81a65f52011-03-26 11:48:37 +0000173 /// Emits a linkonce_odr string, whose name is the prefix followed by the
174 /// string value. This allows the linker to combine the strings between
175 /// different modules. Used for EH typeinfo names, selector strings, and a
176 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000177 llvm::Constant *ExportUniqueString(const std::string &Str,
178 const std::string prefix) {
179 std::string name = prefix + Str;
180 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
181 if (!ConstStr) {
182 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
183 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
184 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
185 }
186 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
187 }
David Chisnall81a65f52011-03-26 11:48:37 +0000188 /// Generates a global structure, initialized by the elements in the vector.
189 /// The element types must match the types of the structure elements in the
190 /// first argument.
David Chisnallc7ef4622011-03-23 22:52:06 +0000191 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000192 std::vector<llvm::Constant*> &V,
193 llvm::StringRef Name="",
194 llvm::GlobalValue::LinkageTypes linkage
195 =llvm::GlobalValue::InternalLinkage) {
196 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
197 return new llvm::GlobalVariable(TheModule, Ty, false,
198 linkage, C, Name);
199 }
David Chisnall81a65f52011-03-26 11:48:37 +0000200 /// Generates a global array. The vector must contain the same number of
201 /// elements that the array type declares, of the type specified as the array
202 /// element type.
David Chisnallc7ef4622011-03-23 22:52:06 +0000203 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000204 std::vector<llvm::Constant*> &V,
205 llvm::StringRef Name="",
206 llvm::GlobalValue::LinkageTypes linkage
207 =llvm::GlobalValue::InternalLinkage) {
208 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
209 return new llvm::GlobalVariable(TheModule, Ty, false,
210 linkage, C, Name);
211 }
David Chisnall81a65f52011-03-26 11:48:37 +0000212 /// Generates a global array, inferring the array type from the specified
213 /// element type and the size of the initialiser.
David Chisnallc7ef4622011-03-23 22:52:06 +0000214 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000215 std::vector<llvm::Constant*> &V,
216 llvm::StringRef Name="",
217 llvm::GlobalValue::LinkageTypes linkage
218 =llvm::GlobalValue::InternalLinkage) {
219 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
220 return MakeGlobal(ArrayTy, V, Name, linkage);
221 }
David Chisnall81a65f52011-03-26 11:48:37 +0000222 /// Ensures that the value has the required type, by inserting a bitcast if
223 /// required. This function lets us avoid inserting bitcasts that are
224 /// redundant.
David Chisnallc7ef4622011-03-23 22:52:06 +0000225 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
226 if (V->getType() == Ty) return V;
227 return B.CreateBitCast(V, Ty);
228 }
229 // Some zeros used for GEPs in lots of places.
230 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000231 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000232 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000233 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000234 llvm::LLVMContext &VMContext;
235private:
David Chisnall81a65f52011-03-26 11:48:37 +0000236 /// Placeholder for the class. Lots of things refer to the class before we've
237 /// actually emitted it. We use this alias as a placeholder, and then replace
238 /// it with a pointer to the class structure before finally emitting the
239 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000240 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000241 /// Placeholder for the metaclass. Lots of things refer to the class before
242 /// we've / actually emitted it. We use this alias as a placeholder, and then
243 /// replace / it with a pointer to the metaclass structure before finally
244 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000245 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000246 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000247 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000248 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000249 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000250 /// All of the Objective-C constant strings that have been generated for this
251 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000252 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000253 /// Map from string values to Objective-C constant strings in the output.
254 /// Used to prevent emitting Objective-C strings more than once. This should
255 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000256 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000257 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000258 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000259 /// For each variant of a selector, we store the type encoding and a
260 /// placeholder value. For an untyped selector, the type will be the empty
261 /// string. Selector references are all done via the module's selector table,
262 /// so we create an alias as a placeholder and then replace it with the real
263 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000264 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000265 /// Type of the selector map. This is roughly equivalent to the structure
266 /// used in the GNUstep runtime, which maintains a list of all of the valid
267 /// types for a selector in a table.
David Chisnall9f6614e2011-03-23 16:36:54 +0000268 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
269 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000270 /// A map from selectors to selector types. This allows us to emit all
271 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000272 SelectorMap SelectorTable;
273
David Chisnall81a65f52011-03-26 11:48:37 +0000274 /// Selectors related to memory management. When compiling in GC mode, we
275 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000276 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000277 /// Runtime functions used for memory management in GC mode. Note that clang
278 /// supports code generation for calling these functions, but neither GNU
279 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000280 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
281 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000282
David Chisnall9735ca62011-03-25 11:57:33 +0000283protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000284 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000285 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000286 /// Function used for rethrowing exceptions, used at the end of @finally or
287 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000288 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000289 /// Function called when entering a catch function. This is required for
290 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000291 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000292 /// Function called when exiting from a catch block. Used to do exception
293 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000294 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000295 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000296 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000298 LazyRuntimeFunction SyncExitFn;
299
David Chisnall9735ca62011-03-25 11:57:33 +0000300private:
301
David Chisnall81a65f52011-03-26 11:48:37 +0000302 /// Function called if fast enumeration detects that the collection is
303 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000304 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000305 /// Function for implementing synthesized property getters that return an
306 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000307 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000308 /// Function for implementing synthesized property setters that return an
309 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000310 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000311 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000312 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000313 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000314 LazyRuntimeFunction SetStructPropertyFn;
315
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// The version of the runtime that this class targets. Must match the
317 /// version in the runtime.
David Chisnall9f6614e2011-03-23 16:36:54 +0000318 const int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000319 /// The version of the protocol class. Used to differentiate between ObjC1
320 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
321 /// components and can not contain declared properties. We always emit
322 /// Objective-C 2 property structures, but we have to pretend that they're
323 /// Objective-C 1 property structures when targeting the GCC runtime or it
324 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000325 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000326private:
David Chisnall81a65f52011-03-26 11:48:37 +0000327 /// Generates an instance variable list structure. This is a structure
328 /// containing a size and an array of structures containing instance variable
329 /// metadata. This is used purely for introspection in the fragile ABI. In
330 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000331 llvm::Constant *GenerateIvarList(
332 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
333 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
334 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000335 /// Generates a method list structure. This is a structure containing a size
336 /// and an array of structures containing method metadata.
337 ///
338 /// This structure is used by both classes and categories, and contains a next
339 /// pointer allowing them to be chained together in a linked list.
David Chisnall9f6614e2011-03-23 16:36:54 +0000340 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
341 const llvm::StringRef &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +0000342 const llvm::SmallVectorImpl<Selector> &MethodSels,
343 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000344 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000345 /// Emits an empty protocol. This is used for @protocol() where no protocol
346 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
347 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000348 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000349 /// Generates a list of property metadata structures. This follows the same
350 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000351 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
352 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
353 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000354 /// Generates a list of referenced protocols. Classes, categories, and
355 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000356 llvm::Constant *GenerateProtocolList(
357 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000358 /// To ensure that all protocols are seen by the runtime, we add a category on
359 /// a class defined in the runtime, declaring no methods, but adopting the
360 /// protocols. This is a horribly ugly hack, but it allows us to collect all
361 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000362 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000363 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000364 llvm::Constant *GenerateClassStructure(
365 llvm::Constant *MetaClass,
366 llvm::Constant *SuperClass,
367 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000368 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000369 llvm::Constant *Version,
370 llvm::Constant *InstanceSize,
371 llvm::Constant *IVars,
372 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000373 llvm::Constant *Protocols,
374 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000375 llvm::Constant *Properties,
376 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000377 /// Generates a method list. This is used by protocols to define the required
378 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000379 llvm::Constant *GenerateProtocolMethodList(
380 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
381 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000382 /// Returns a selector with the specified type encoding. An empty string is
383 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000384 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
385 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000386 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000387 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
388 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000389 /// Emits a reference to a class. This allows the linker to object if there
390 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000391 void EmitClassRef(const std::string &className);
David Chisnallc7ef4622011-03-23 22:52:06 +0000392protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000393 /// Looks up the method for sending a message to the specified object. This
394 /// mechanism differs between the GCC and GNU runtimes, so this method must be
395 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000396 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
397 llvm::Value *&Receiver,
398 llvm::Value *cmd,
399 llvm::MDNode *node) = 0;
David Chisnall81a65f52011-03-26 11:48:37 +0000400 /// Looks up the method for sending a message to a superclass. This mechanism
401 /// differs between the GCC and GNU runtimes, so this method must be
402 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000403 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
404 llvm::Value *ObjCSuper,
405 llvm::Value *cmd) = 0;
Chris Lattner0f984262008-03-01 08:50:34 +0000406public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000407 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
408 unsigned protocolClassVersion);
409
David Chisnall0d13f6f2010-01-23 02:40:42 +0000410 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000411
412 virtual RValue
413 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000414 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000415 QualType ResultType,
416 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000417 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000418 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000419 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000420 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000421 virtual RValue
422 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000423 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000424 QualType ResultType,
425 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000426 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000427 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000428 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000429 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000430 const CallArgList &CallArgs,
431 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000432 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000433 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000434 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
435 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000436 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
437 *Method);
John McCall5a180392010-07-24 00:37:23 +0000438 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
440 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000441 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000442 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
443 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000444 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000445 const ObjCProtocolDecl *PD);
446 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000447 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000448 virtual llvm::Function *GetPropertyGetFunction();
449 virtual llvm::Function *GetPropertySetFunction();
David Chisnall8fac25d2010-12-26 22:13:16 +0000450 virtual llvm::Function *GetSetStructFunction();
451 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000452 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000453
David Chisnall9f6614e2011-03-23 16:36:54 +0000454 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000455 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000456 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000457 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000458 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000459 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000460 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000461 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000462 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000463 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000464 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000465 llvm::Value *src, llvm::Value *dest,
466 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000467 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000468 llvm::Value *src, llvm::Value *dest,
469 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000470 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000471 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000472 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000473 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000474 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000475 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000476 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000477 QualType ObjectTy,
478 llvm::Value *BaseValue,
479 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000480 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000481 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000482 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000483 const ObjCIvarDecl *Ivar);
David Chisnall9f6614e2011-03-23 16:36:54 +0000484 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000485 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000486 return NULLPtr;
487 }
Chris Lattner0f984262008-03-01 08:50:34 +0000488};
David Chisnall81a65f52011-03-26 11:48:37 +0000489/// Class representing the legacy GCC Objective-C ABI. This is the default when
490/// -fobjc-nonfragile-abi is not specified.
491///
492/// The GCC ABI target actually generates code that is approximately compatible
493/// with the new GNUstep runtime ABI, but refrains from using any features that
494/// would not work with the GCC runtime. For example, clang always generates
495/// the extended form of the class structure, and the extra fields are simply
496/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000497class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000498 /// The GCC ABI message lookup function. Returns an IMP pointing to the
499 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000500 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000501 /// The GCC ABI superclass message lookup function. Takes a pointer to a
502 /// structure describing the receiver and the class, and a selector as
503 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000504 LazyRuntimeFunction MsgLookupSuperFn;
505protected:
506 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
507 llvm::Value *&Receiver,
508 llvm::Value *cmd,
509 llvm::MDNode *node) {
510 CGBuilderTy &Builder = CGF.Builder;
511 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
512 EnforceType(Builder, Receiver, IdTy),
513 EnforceType(Builder, cmd, SelectorTy));
514 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
515 return imp;
516 }
517 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
518 llvm::Value *ObjCSuper,
519 llvm::Value *cmd) {
520 CGBuilderTy &Builder = CGF.Builder;
521 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
522 PtrToObjCSuperTy), cmd};
523 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
524 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000525 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000526 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
527 // IMP objc_msg_lookup(id, SEL);
528 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
529 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
530 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
531 PtrToObjCSuperTy, SelectorTy, NULL);
532 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000533};
David Chisnall81a65f52011-03-26 11:48:37 +0000534/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000535class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000536 /// The slot lookup function. Returns a pointer to a cacheable structure
537 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000538 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000539 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
540 /// a structure describing the receiver and the class, and a selector as
541 /// arguments. Returns the slot for the corresponding method. Superclass
542 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000543 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000544 /// Type of an slot structure pointer. This is returned by the various
545 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000546 llvm::Type *SlotTy;
547 protected:
548 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
549 llvm::Value *&Receiver,
550 llvm::Value *cmd,
551 llvm::MDNode *node) {
552 CGBuilderTy &Builder = CGF.Builder;
553 llvm::Function *LookupFn = SlotLookupFn;
554
555 // Store the receiver on the stack so that we can reload it later
556 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
557 Builder.CreateStore(Receiver, ReceiverPtr);
558
559 llvm::Value *self;
560
561 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
562 self = CGF.LoadObjCSelf();
563 } else {
564 self = llvm::ConstantPointerNull::get(IdTy);
565 }
566
567 // The lookup function is guaranteed not to capture the receiver pointer.
568 LookupFn->setDoesNotCapture(1);
569
570 llvm::CallInst *slot =
571 Builder.CreateCall3(LookupFn,
572 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
573 EnforceType(Builder, cmd, SelectorTy),
574 EnforceType(Builder, self, IdTy));
575 slot->setOnlyReadsMemory();
576 slot->setMetadata(msgSendMDKind, node);
577
578 // Load the imp from the slot
579 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
580
581 // The lookup function may have changed the receiver, so make sure we use
582 // the new one.
583 Receiver = Builder.CreateLoad(ReceiverPtr, true);
584 return imp;
585 }
586 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
587 llvm::Value *ObjCSuper,
588 llvm::Value *cmd) {
589 CGBuilderTy &Builder = CGF.Builder;
590 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
591
592 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
593 lookupArgs+2);
594 slot->setOnlyReadsMemory();
595
596 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
597 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000598 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000599 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
600 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
601 PtrTy, PtrTy, IntTy, IMPTy, NULL);
602 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
603 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
604 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
605 SelectorTy, IdTy, NULL);
606 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
607 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
608 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000609 // If we're in ObjC++ mode, then we want to make
610 if (CGM.getLangOptions().CPlusPlus) {
611 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
612 // void *__cxa_begin_catch(void *e)
613 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
614 // void __cxa_end_catch(void)
615 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
616 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000617 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000618 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000619 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000620};
621
Chris Lattner0f984262008-03-01 08:50:34 +0000622} // end anonymous namespace
623
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000624
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000625/// Emits a reference to a dummy variable which is emitted with each class.
626/// This ensures that a linker error will be generated when trying to link
627/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000628void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000629 std::string symbolRef = "__objc_class_ref_" + className;
630 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000631 if (TheModule.getGlobalVariable(symbolRef))
632 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000633 std::string symbolName = "__objc_class_name_" + className;
634 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
635 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000636 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
637 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000638 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000639 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000640 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000641}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000642
David Chisnall9f6614e2011-03-23 16:36:54 +0000643static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
644 const llvm::StringRef &CategoryName, const Selector MethodName,
645 bool isClassMethod) {
646 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000647 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
648 ':', '_');
David Chisnall9f6614e2011-03-23 16:36:54 +0000649 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
650 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000651}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000652
David Chisnall9f6614e2011-03-23 16:36:54 +0000653CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
654 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000655 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
656 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
657 ProtocolVersion(protocolClassVersion) {
David Chisnall9f6614e2011-03-23 16:36:54 +0000658
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000659
660 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
661
David Chisnall9f6614e2011-03-23 16:36:54 +0000662 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000663 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000664 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000665 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000666 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000667 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000668 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000669 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000670 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000671 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000673 Int8Ty = llvm::Type::getInt8Ty(VMContext);
674 // C string type. Used in lots of places.
675 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
676
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000677 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000678 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000679 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000680 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000681 QualType selTy = CGM.getContext().getObjCSelType();
682 if (QualType() == selTy) {
683 SelectorTy = PtrToInt8Ty;
684 } else {
685 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
686 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000687
Owen Anderson96e0fc72009-07-29 22:16:19 +0000688 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000689 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Chris Lattner391d77a2008-03-30 23:03:07 +0000691 // Object type
John McCallead608a2010-02-26 00:48:12 +0000692 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall0d13f6f2010-01-23 02:40:42 +0000693 if (QualType() == ASTIdTy) {
694 IdTy = PtrToInt8Ty;
695 } else {
696 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
697 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000698 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
David Chisnallc7ef4622011-03-23 22:52:06 +0000700 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
701 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
702
David Chisnall9f6614e2011-03-23 16:36:54 +0000703 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
704
705 // void objc_exception_throw(id);
706 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000707 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000708 // int objc_sync_enter(id);
709 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
710 // int objc_sync_exit(id);
711 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
712
713 // void objc_enumerationMutation (id)
714 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
715 IdTy, NULL);
716
717 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
718 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
719 PtrDiffTy, BoolTy, NULL);
720 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
721 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
722 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
723 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
724 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
725 PtrDiffTy, BoolTy, BoolTy, NULL);
726 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
727 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
728 PtrDiffTy, BoolTy, BoolTy, NULL);
729
Chris Lattner391d77a2008-03-30 23:03:07 +0000730 // IMP type
731 std::vector<const llvm::Type*> IMPArgs;
732 IMPArgs.push_back(IdTy);
733 IMPArgs.push_back(SelectorTy);
David Chisnallc7ef4622011-03-23 22:52:06 +0000734 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
735 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000736
David Chisnall9735ca62011-03-25 11:57:33 +0000737 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +0000738 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
739 // Get selectors needed in GC mode
740 RetainSel = GetNullarySelector("retain", CGM.getContext());
741 ReleaseSel = GetNullarySelector("release", CGM.getContext());
742 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
743
744 // Get functions needed in GC mode
745
746 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000747 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
748 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000749 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000750 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
751 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000752 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000753 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
754 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000755 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000756 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000757 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000758 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000759 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000760 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
761 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000762 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000763}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000764
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000765// This has to perform the lookup every time, since posing and related
766// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000767llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000768 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000769 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnall41d63ed2010-01-08 00:14:31 +0000770 // With the incompatible ABI, this will need to be replaced with a direct
771 // reference to the class symbol. For the compatible nonfragile ABI we are
772 // still performing this lookup at run time but emitting the symbol for the
773 // class externally so that we can make the switch later.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000774 EmitClassRef(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000775 ClassName = Builder.CreateStructGEP(ClassName, 0);
776
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000777 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000778 llvm::Constant *ClassLookupFn =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000779 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000780 Params,
781 true),
782 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000783 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000784}
785
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000786llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000787 const std::string &TypeEncoding, bool lval) {
788
789 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
790 llvm::GlobalAlias *SelValue = 0;
791
792
793 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
794 e = Types.end() ; i!=e ; i++) {
795 if (i->first == TypeEncoding) {
796 SelValue = i->second;
797 break;
798 }
799 }
800 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000801 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000802 llvm::GlobalValue::PrivateLinkage,
803 ".objc_selector_"+Sel.getAsString(), NULL,
804 &TheModule);
805 Types.push_back(TypedSelector(TypeEncoding, SelValue));
806 }
807
David Chisnallc7ef4622011-03-23 22:52:06 +0000808 if (lval) {
809 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
810 Builder.CreateStore(SelValue, tmp);
811 return tmp;
812 }
813 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000814}
815
816llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
817 bool lval) {
818 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000819}
820
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000821llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000822 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000823 std::string SelTypes;
824 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000825 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000826}
827
John McCall5a180392010-07-24 00:37:23 +0000828llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000829 if (!CGM.getLangOptions().CPlusPlus) {
830 if (T->isObjCIdType()
831 || T->isObjCQualifiedIdType()) {
832 // With the old ABI, there was only one kind of catchall, which broke
833 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
834 // a pointer indicating object catchalls, and NULL to indicate real
835 // catchalls
836 if (CGM.getLangOptions().ObjCNonFragileABI) {
837 return MakeConstantString("@id");
838 } else {
839 return 0;
840 }
841 }
842
843 // All other types should be Objective-C interface pointer types.
844 const ObjCObjectPointerType *OPT =
845 T->getAs<ObjCObjectPointerType>();
846 assert(OPT && "Invalid @catch type.");
847 const ObjCInterfaceDecl *IDecl =
848 OPT->getObjectType()->getInterface();
849 assert(IDecl && "Invalid @catch type.");
850 return MakeConstantString(IDecl->getIdentifier()->getName());
851 }
David Chisnall80558d22011-03-20 21:35:39 +0000852 // For Objective-C++, we want to provide the ability to catch both C++ and
853 // Objective-C objects in the same function.
854
855 // There's a particular fixed type info for 'id'.
856 if (T->isObjCIdType() ||
857 T->isObjCQualifiedIdType()) {
858 llvm::Constant *IDEHType =
859 CGM.getModule().getGlobalVariable("__objc_id_type_info");
860 if (!IDEHType)
861 IDEHType =
862 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
863 false,
864 llvm::GlobalValue::ExternalLinkage,
865 0, "__objc_id_type_info");
866 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
867 }
868
869 const ObjCObjectPointerType *PT =
870 T->getAs<ObjCObjectPointerType>();
871 assert(PT && "Invalid @catch type.");
872 const ObjCInterfaceType *IT = PT->getInterfaceType();
873 assert(IT && "Invalid @catch type.");
874 std::string className = IT->getDecl()->getIdentifier()->getName();
875
876 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
877
878 // Return the existing typeinfo if it exists
879 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
880 if (typeinfo) return typeinfo;
881
882 // Otherwise create it.
883
884 // vtable for gnustep::libobjc::__objc_class_type_info
885 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
886 // platform's name mangling.
887 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
888 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
889 if (!Vtable) {
890 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
891 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
892 }
893 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
894 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
895 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
896
897 llvm::Constant *typeName =
898 ExportUniqueString(className, "__objc_eh_typename_");
899
900 std::vector<llvm::Constant*> fields;
901 fields.push_back(Vtable);
902 fields.push_back(typeName);
903 llvm::Constant *TI =
904 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
905 NULL), fields, "__objc_eh_typeinfo_" + className,
906 llvm::GlobalValue::LinkOnceODRLinkage);
907 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000908}
909
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000910/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000911llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000912
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000913 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000914
David Chisnall48272a02010-01-27 12:49:23 +0000915 // Look for an existing one
916 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
917 if (old != ObjCStrings.end())
918 return old->getValue();
919
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000920 std::vector<llvm::Constant*> Ivars;
921 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000922 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000923 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000924 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson47a434f2009-08-05 23:18:46 +0000925 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000926 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000927 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
928 ObjCStrings[Str] = ObjCStr;
929 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000930 return ObjCStr;
931}
932
933///Generates a message send where the super is the receiver. This is a message
934///send to self with special delivery semantics indicating which class's method
935///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +0000936RValue
937CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000938 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000939 QualType ResultType,
940 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000941 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000942 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000943 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000944 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000945 const CallArgList &CallArgs,
946 const ObjCMethodDecl *Method) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000947 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
948 if (Sel == RetainSel || Sel == AutoreleaseSel) {
949 return RValue::get(Receiver);
950 }
951 if (Sel == ReleaseSel) {
952 return RValue::get(0);
953 }
954 }
David Chisnalldb831942010-05-01 12:37:16 +0000955
956 CGBuilderTy &Builder = CGF.Builder;
957 llvm::Value *cmd = GetSelector(Builder, Sel);
958
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000959
960 CallArgList ActualArgs;
961
962 ActualArgs.push_back(
David Chisnallc7ef4622011-03-23 22:52:06 +0000963 std::make_pair(RValue::get(EnforceType(Builder, Receiver, IdTy)),
David Chisnall0f436562009-08-17 16:35:33 +0000964 ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000965 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
966 CGF.getContext().getObjCSelType()));
967 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
968
969 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000970 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000971 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000972
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000973 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000974 if (isCategoryImpl) {
975 llvm::Constant *classLookupFunction = 0;
976 std::vector<const llvm::Type*> Params;
977 Params.push_back(PtrTy);
978 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000979 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000980 IdTy, Params, true), "objc_get_meta_class");
981 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000982 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000983 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000984 }
David Chisnalldb831942010-05-01 12:37:16 +0000985 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000986 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000987 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000988 // Set up global aliases for the metaclass or class pointer if they do not
989 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +0000990 // pointers to the class and metaclass structure created for the runtime
991 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000992 // super_class pointer from either the class or metaclass structure.
993 if (IsClassMessage) {
994 if (!MetaClassPtrAlias) {
995 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
996 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
997 Class->getNameAsString(), NULL, &TheModule);
998 }
999 ReceiverClass = MetaClassPtrAlias;
1000 } else {
1001 if (!ClassPtrAlias) {
1002 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1003 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1004 Class->getNameAsString(), NULL, &TheModule);
1005 }
1006 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001007 }
Chris Lattner71238f62009-04-25 23:19:45 +00001008 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001009 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001010 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001011 llvm::PointerType::getUnqual(
Owen Anderson47a434f2009-08-05 23:18:46 +00001012 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001013 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001014 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001015 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001016 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001017 // Construct the structure used to look up the IMP
Owen Anderson47a434f2009-08-05 23:18:46 +00001018 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
1019 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001020 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001021
David Chisnalldb831942010-05-01 12:37:16 +00001022 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1023 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001024
David Chisnallc7ef4622011-03-23 22:52:06 +00001025 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1026 const llvm::FunctionType *impType =
1027 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1028
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001029 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001030 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1031 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001032
David Chisnalldd5c98f2010-05-01 11:15:56 +00001033 llvm::Value *impMD[] = {
1034 llvm::MDString::get(VMContext, Sel.getAsString()),
1035 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1036 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1037 };
1038 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
1039
David Chisnall4b02afc2010-05-02 13:41:58 +00001040 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001041 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001042 0, &call);
1043 call->setMetadata(msgSendMDKind, node);
1044 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001045}
1046
Mike Stump1eb44332009-09-09 15:08:12 +00001047/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001048RValue
1049CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001050 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001051 QualType ResultType,
1052 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001053 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001054 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001055 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001056 const ObjCMethodDecl *Method) {
David Chisnall664b7c72010-04-27 15:08:48 +00001057 // Strip out message sends to retain / release in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +00001058 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1059 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1060 return RValue::get(Receiver);
1061 }
1062 if (Sel == ReleaseSel) {
1063 return RValue::get(0);
1064 }
1065 }
David Chisnall664b7c72010-04-27 15:08:48 +00001066
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001067 CGBuilderTy &Builder = CGF.Builder;
David Chisnall664b7c72010-04-27 15:08:48 +00001068
1069 // If the return type is something that goes in an integer register, the
1070 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1071 // ourselves.
1072 //
1073 // The language spec says the result of this kind of message send is
1074 // undefined, but lots of people seem to have forgotten to read that
1075 // paragraph and insist on sending messages to nil that have structure
1076 // returns. With GCC, this generates a random return value (whatever happens
1077 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001078 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1079 // the stack.
1080 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1081 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001082
1083 llvm::BasicBlock *startBB = 0;
1084 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001085 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001086
1087 if (!isPointerSizedReturn) {
1088 startBB = Builder.GetInsertBlock();
1089 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001090 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001091
1092 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1093 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001094 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001095 CGF.EmitBlock(messageBB);
1096 }
1097
David Chisnall0f436562009-08-17 16:35:33 +00001098 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001099 llvm::Value *cmd;
1100 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001101 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001102 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001103 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001104 cmd = EnforceType(Builder, cmd, SelectorTy);
1105 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001106
David Chisnallc7ef4622011-03-23 22:52:06 +00001107 llvm::Value *impMD[] = {
1108 llvm::MDString::get(VMContext, Sel.getAsString()),
1109 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1110 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1111 };
1112 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
1113
1114 // Get the IMP to call
1115 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1116
1117 CallArgList ActualArgs;
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001118 ActualArgs.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001119 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001120 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
1121 CGF.getContext().getObjCSelType()));
1122 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1123
1124 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001125 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001126 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +00001127 const llvm::FunctionType *impType =
1128 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001129 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001130
1131
Fariborz Jahanian34e65772009-05-22 20:17:16 +00001132 // For sender-aware dispatch, we pass the sender as the third argument to a
1133 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001134 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnall4b02afc2010-05-02 13:41:58 +00001135 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001136 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001137 0, &call);
1138 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001139
David Chisnalla54da052010-05-20 13:45:48 +00001140
David Chisnall664b7c72010-04-27 15:08:48 +00001141 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001142 messageBB = CGF.Builder.GetInsertBlock();
1143 CGF.Builder.CreateBr(continueBB);
1144 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001145 if (msgRet.isScalar()) {
1146 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001147 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001148 phi->addIncoming(v, messageBB);
1149 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1150 msgRet = RValue::get(phi);
1151 } else if (msgRet.isAggregate()) {
1152 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001153 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001154 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001155 llvm::AllocaInst *NullVal =
1156 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001157 CGF.InitTempAlloca(NullVal,
1158 llvm::Constant::getNullValue(RetTy->getElementType()));
1159 phi->addIncoming(v, messageBB);
1160 phi->addIncoming(NullVal, startBB);
1161 msgRet = RValue::getAggregate(phi);
1162 } else /* isComplex() */ {
1163 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001164 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001165 phi->addIncoming(v.first, messageBB);
1166 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1167 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001168 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001169 phi2->addIncoming(v.second, messageBB);
1170 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1171 startBB);
1172 msgRet = RValue::getComplex(phi, phi2);
1173 }
1174 }
1175 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001176}
1177
Mike Stump1eb44332009-09-09 15:08:12 +00001178/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001179/// objc_category structures.
David Chisnall9f6614e2011-03-23 16:36:54 +00001180llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1181 const llvm::StringRef &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +00001182 const llvm::SmallVectorImpl<Selector> &MethodSels,
1183 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001184 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001185 if (MethodSels.empty())
1186 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001187 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +00001188 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001189 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1190 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001191 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001192 NULL);
1193 std::vector<llvm::Constant*> Methods;
1194 std::vector<llvm::Constant*> Elements;
1195 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1196 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001197 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001198 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001199 MethodSels[i],
1200 isClassMethodList));
1201 assert(Method && "Can't generate metadata for method that doesn't exist");
1202 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1203 Elements.push_back(C);
1204 Elements.push_back(MethodTypes[i]);
1205 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001206 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001207 Elements.push_back(Method);
1208 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001209 }
1210
1211 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001212 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001213 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001214 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001215 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001216
1217 // Structure containing list pointer, array and array count
1218 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Anderson8c8f69e2009-08-13 23:27:53 +00001219 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001220 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson47a434f2009-08-05 23:18:46 +00001221 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump1eb44332009-09-09 15:08:12 +00001222 NextPtrTy,
1223 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001224 ObjCMethodArrayTy,
1225 NULL);
1226 // Refine next pointer type to concrete type
1227 llvm::cast<llvm::OpaqueType>(
1228 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1229 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1230
1231 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001232 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001233 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +00001234 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001235 MethodTypes.size()));
1236 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001238 // Create an instance of the structure
1239 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1240}
1241
1242/// Generates an IvarList. Used in construction of a objc_class.
1243llvm::Constant *CGObjCGNU::GenerateIvarList(
1244 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1245 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1246 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001247 if (IvarNames.size() == 0)
1248 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001249 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +00001250 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001251 PtrToInt8Ty,
1252 PtrToInt8Ty,
1253 IntTy,
1254 NULL);
1255 std::vector<llvm::Constant*> Ivars;
1256 std::vector<llvm::Constant*> Elements;
1257 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1258 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001259 Elements.push_back(IvarNames[i]);
1260 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001261 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001262 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001263 }
1264
1265 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001266 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001267 IvarNames.size());
1268
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001270 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001271 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001272 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001273 // Structure containing array and array count
Owen Anderson47a434f2009-08-05 23:18:46 +00001274 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001275 ObjCIvarArrayTy,
1276 NULL);
1277
1278 // Create an instance of the structure
1279 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1280}
1281
1282/// Generate a class structure
1283llvm::Constant *CGObjCGNU::GenerateClassStructure(
1284 llvm::Constant *MetaClass,
1285 llvm::Constant *SuperClass,
1286 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001287 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001288 llvm::Constant *Version,
1289 llvm::Constant *InstanceSize,
1290 llvm::Constant *IVars,
1291 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001292 llvm::Constant *Protocols,
1293 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001294 llvm::Constant *Properties,
1295 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001296 // Set up the class structure
1297 // Note: Several of these are char*s when they should be ids. This is
1298 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001299 //
1300 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1301 // anyway; the classes will still work with the GNU runtime, they will just
1302 // be ignored.
Owen Anderson47a434f2009-08-05 23:18:46 +00001303 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001304 PtrToInt8Ty, // class_pointer
1305 PtrToInt8Ty, // super_class
1306 PtrToInt8Ty, // name
1307 LongTy, // version
1308 LongTy, // info
1309 LongTy, // instance_size
1310 IVars->getType(), // ivars
1311 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001312 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001313 PtrTy, // dtable
1314 PtrTy, // subclass_list
1315 PtrTy, // sibling_class
1316 PtrTy, // protocols
1317 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001318 // New ABI:
1319 LongTy, // abi_version
1320 IvarOffsets->getType(), // ivar_offsets
1321 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001322 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001323 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001324 // Fill in the structure
1325 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001326 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001327 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001328 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001329 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001330 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001331 if (isMeta) {
1332 llvm::TargetData td(&TheModule);
1333 Elements.push_back(llvm::ConstantInt::get(LongTy,
1334 td.getTypeSizeInBits(ClassTy)/8));
1335 } else
1336 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001337 Elements.push_back(IVars);
1338 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001339 Elements.push_back(NULLPtr);
1340 Elements.push_back(NULLPtr);
1341 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001342 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001343 Elements.push_back(NULLPtr);
1344 Elements.push_back(Zero);
1345 Elements.push_back(IvarOffsets);
1346 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001347 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001348 // This is now an externally visible symbol, so that we can speed up class
1349 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +00001350 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1351 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001352}
1353
1354llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1355 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1356 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001357 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +00001358 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001359 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1360 PtrToInt8Ty,
1361 NULL);
1362 std::vector<llvm::Constant*> Methods;
1363 std::vector<llvm::Constant*> Elements;
1364 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1365 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001366 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001367 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001368 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001369 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001370 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001371 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001372 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001373 Methods);
Owen Anderson47a434f2009-08-05 23:18:46 +00001374 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001375 IntTy, ObjCMethodArrayTy, NULL);
1376 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001377 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001378 Methods.push_back(Array);
1379 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1380}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001381
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001382// Create the protocol list structure used in classes, categories and so on
1383llvm::Constant *CGObjCGNU::GenerateProtocolList(
1384 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001385 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001386 Protocols.size());
Owen Anderson47a434f2009-08-05 23:18:46 +00001387 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001388 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001389 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001390 ProtocolArrayTy,
1391 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001392 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001393 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1394 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001395 llvm::Constant *protocol = 0;
1396 llvm::StringMap<llvm::Constant*>::iterator value =
1397 ExistingProtocols.find(*iter);
1398 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001399 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001400 } else {
1401 protocol = value->getValue();
1402 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001403 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001404 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001405 Elements.push_back(Ptr);
1406 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001407 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001408 Elements);
1409 Elements.clear();
1410 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001411 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001412 Elements.push_back(ProtocolArray);
1413 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1414}
1415
Mike Stump1eb44332009-09-09 15:08:12 +00001416llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001417 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001418 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001419 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001420 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001421 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001422}
1423
1424llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1425 const std::string &ProtocolName) {
1426 llvm::SmallVector<std::string, 0> EmptyStringVector;
1427 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1428
1429 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001430 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001431 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1432 // Protocols are objects containing lists of the methods implemented and
1433 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001434 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001435 PtrToInt8Ty,
1436 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001437 MethodList->getType(),
1438 MethodList->getType(),
1439 MethodList->getType(),
1440 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001441 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001442 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001443 // The isa pointer must be set to a magic number so the runtime knows it's
1444 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001445 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001446 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1447 ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001448 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1449 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001450 Elements.push_back(MethodList);
1451 Elements.push_back(MethodList);
1452 Elements.push_back(MethodList);
1453 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001454 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001455}
1456
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001457void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1458 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001459 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001460 llvm::SmallVector<std::string, 16> Protocols;
1461 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1462 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001463 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001464 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1465 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001466 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1467 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001468 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1469 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001470 std::string TypeStr;
1471 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001472 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1473 InstanceMethodNames.push_back(
1474 MakeConstantString((*iter)->getSelector().getAsString()));
1475 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1476 } else {
1477 OptionalInstanceMethodNames.push_back(
1478 MakeConstantString((*iter)->getSelector().getAsString()));
1479 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1480 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001481 }
1482 // Collect information about class methods:
1483 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1484 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001485 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1486 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001487 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001488 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1489 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001490 std::string TypeStr;
1491 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001492 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1493 ClassMethodNames.push_back(
1494 MakeConstantString((*iter)->getSelector().getAsString()));
1495 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1496 } else {
1497 OptionalClassMethodNames.push_back(
1498 MakeConstantString((*iter)->getSelector().getAsString()));
1499 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1500 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001501 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001502
1503 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1504 llvm::Constant *InstanceMethodList =
1505 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1506 llvm::Constant *ClassMethodList =
1507 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001508 llvm::Constant *OptionalInstanceMethodList =
1509 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1510 OptionalInstanceMethodTypes);
1511 llvm::Constant *OptionalClassMethodList =
1512 GenerateProtocolMethodList(OptionalClassMethodNames,
1513 OptionalClassMethodTypes);
1514
1515 // Property metadata: name, attributes, isSynthesized, setter name, setter
1516 // types, getter name, getter types.
1517 // The isSynthesized value is always set to 0 in a protocol. It exists to
1518 // simplify the runtime library by allowing it to use the same data
1519 // structures for protocol metadata everywhere.
1520 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1521 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1522 PtrToInt8Ty, NULL);
1523 std::vector<llvm::Constant*> Properties;
1524 std::vector<llvm::Constant*> OptionalProperties;
1525
1526 // Add all of the property methods need adding to the method list and to the
1527 // property metadata list.
1528 for (ObjCContainerDecl::prop_iterator
1529 iter = PD->prop_begin(), endIter = PD->prop_end();
1530 iter != endIter ; iter++) {
1531 std::vector<llvm::Constant*> Fields;
1532 ObjCPropertyDecl *property = (*iter);
1533
1534 Fields.push_back(MakeConstantString(property->getNameAsString()));
1535 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1536 property->getPropertyAttributes()));
1537 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1538 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1539 std::string TypeStr;
1540 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1541 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1542 InstanceMethodTypes.push_back(TypeEncoding);
1543 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1544 Fields.push_back(TypeEncoding);
1545 } else {
1546 Fields.push_back(NULLPtr);
1547 Fields.push_back(NULLPtr);
1548 }
1549 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1550 std::string TypeStr;
1551 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1552 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1553 InstanceMethodTypes.push_back(TypeEncoding);
1554 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1555 Fields.push_back(TypeEncoding);
1556 } else {
1557 Fields.push_back(NULLPtr);
1558 Fields.push_back(NULLPtr);
1559 }
1560 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1561 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1562 } else {
1563 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1564 }
1565 }
1566 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1567 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1568 llvm::Constant* PropertyListInitFields[] =
1569 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1570
1571 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001572 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001573 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1574 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1575 PropertyListInit, ".objc_property_list");
1576
1577 llvm::Constant *OptionalPropertyArray =
1578 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1579 OptionalProperties.size()) , OptionalProperties);
1580 llvm::Constant* OptionalPropertyListInitFields[] = {
1581 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1582 OptionalPropertyArray };
1583
1584 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001585 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001586 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1587 OptionalPropertyListInit->getType(), false,
1588 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1589 ".objc_property_list");
1590
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001591 // Protocols are objects containing lists of the methods implemented and
1592 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001593 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001594 PtrToInt8Ty,
1595 ProtocolList->getType(),
1596 InstanceMethodList->getType(),
1597 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001598 OptionalInstanceMethodList->getType(),
1599 OptionalClassMethodList->getType(),
1600 PropertyList->getType(),
1601 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001602 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001603 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001604 // The isa pointer must be set to a magic number so the runtime knows it's
1605 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001606 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001607 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1608 ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001609 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1610 Elements.push_back(ProtocolList);
1611 Elements.push_back(InstanceMethodList);
1612 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001613 Elements.push_back(OptionalInstanceMethodList);
1614 Elements.push_back(OptionalClassMethodList);
1615 Elements.push_back(PropertyList);
1616 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001617 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001618 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001619 ".objc_protocol"), IdTy);
1620}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001621void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1622 // Collect information about instance methods
1623 llvm::SmallVector<Selector, 1> MethodSels;
1624 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1625
1626 std::vector<llvm::Constant*> Elements;
1627 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1628 const std::string CategoryName = "AnotherHack";
1629 Elements.push_back(MakeConstantString(CategoryName));
1630 Elements.push_back(MakeConstantString(ClassName));
1631 // Instance method list
1632 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1633 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1634 // Class method list
1635 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1636 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1637 // Protocol list
1638 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1639 ExistingProtocols.size());
1640 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1641 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001642 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001643 ProtocolArrayTy,
1644 NULL);
1645 std::vector<llvm::Constant*> ProtocolElements;
1646 for (llvm::StringMapIterator<llvm::Constant*> iter =
1647 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1648 iter != endIter ; iter++) {
1649 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1650 PtrTy);
1651 ProtocolElements.push_back(Ptr);
1652 }
1653 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1654 ProtocolElements);
1655 ProtocolElements.clear();
1656 ProtocolElements.push_back(NULLPtr);
1657 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1658 ExistingProtocols.size()));
1659 ProtocolElements.push_back(ProtocolArray);
1660 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1661 ProtocolElements, ".objc_protocol_list"), PtrTy));
1662 Categories.push_back(llvm::ConstantExpr::getBitCast(
1663 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1664 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1665}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001666
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001667void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001668 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1669 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001670 // Collect information about instance methods
1671 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1672 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001673 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001674 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001675 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001676 InstanceMethodSels.push_back((*iter)->getSelector());
1677 std::string TypeStr;
1678 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001679 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001680 }
1681
1682 // Collect information about class methods
1683 llvm::SmallVector<Selector, 16> ClassMethodSels;
1684 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001685 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001686 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001687 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001688 ClassMethodSels.push_back((*iter)->getSelector());
1689 std::string TypeStr;
1690 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001691 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001692 }
1693
1694 // Collect the names of referenced protocols
1695 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001696 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1697 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001698 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1699 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001700 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001701
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001702 std::vector<llvm::Constant*> Elements;
1703 Elements.push_back(MakeConstantString(CategoryName));
1704 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001705 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001706 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001707 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001708 false), PtrTy));
1709 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001710 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001711 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001712 PtrTy));
1713 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001714 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001715 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001716 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump1eb44332009-09-09 15:08:12 +00001717 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001718 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001719}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001720
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001721llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1722 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1723 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1724 ASTContext &Context = CGM.getContext();
1725 //
1726 // Property metadata: name, attributes, isSynthesized, setter name, setter
1727 // types, getter name, getter types.
1728 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1729 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1730 PtrToInt8Ty, NULL);
1731 std::vector<llvm::Constant*> Properties;
1732
1733
1734 // Add all of the property methods need adding to the method list and to the
1735 // property metadata list.
1736 for (ObjCImplDecl::propimpl_iterator
1737 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1738 iter != endIter ; iter++) {
1739 std::vector<llvm::Constant*> Fields;
1740 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001741 ObjCPropertyImplDecl *propertyImpl = *iter;
1742 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1743 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001744
1745 Fields.push_back(MakeConstantString(property->getNameAsString()));
1746 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1747 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001748 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001749 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001750 std::string TypeStr;
1751 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1752 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001753 if (isSynthesized) {
1754 InstanceMethodTypes.push_back(TypeEncoding);
1755 InstanceMethodSels.push_back(getter->getSelector());
1756 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001757 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1758 Fields.push_back(TypeEncoding);
1759 } else {
1760 Fields.push_back(NULLPtr);
1761 Fields.push_back(NULLPtr);
1762 }
1763 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001764 std::string TypeStr;
1765 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1766 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001767 if (isSynthesized) {
1768 InstanceMethodTypes.push_back(TypeEncoding);
1769 InstanceMethodSels.push_back(setter->getSelector());
1770 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001771 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1772 Fields.push_back(TypeEncoding);
1773 } else {
1774 Fields.push_back(NULLPtr);
1775 Fields.push_back(NULLPtr);
1776 }
1777 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1778 }
1779 llvm::ArrayType *PropertyArrayTy =
1780 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1781 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1782 Properties);
1783 llvm::Constant* PropertyListInitFields[] =
1784 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1785
1786 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001787 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001788 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1789 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1790 ".objc_property_list");
1791}
1792
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001793void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1794 ASTContext &Context = CGM.getContext();
1795
1796 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001797 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001798 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001799 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001800 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001801 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001802 EmitClassRef(SuperClassName);
1803 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001804
1805 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001806 ObjCInterfaceDecl *ClassDecl =
1807 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001808 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001809 // Emit the symbol that is used to generate linker errors if this class is
1810 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001811 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001812 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001813 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001814 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001815 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001816 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001817 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001818 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001819 }
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001821 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001822 int instanceSize =
1823 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001824
1825 // Collect information about instance variables.
1826 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1827 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1828 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001830 std::vector<llvm::Constant*> IvarOffsetValues;
1831
Mike Stump1eb44332009-09-09 15:08:12 +00001832 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001833 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001834 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1835 // class}. The runtime will then set this to the correct value on load.
1836 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1837 instanceSize = 0 - (instanceSize - superInstanceSize);
1838 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001839
1840 // Collect declared and synthesized ivars.
1841 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1842 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1843
1844 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1845 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001846 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001847 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001848 // Get the type encoding for this ivar
1849 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001850 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001851 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001852 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001853 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001854 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001855 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001856 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001857 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001858 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001859 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001860 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1861 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle0d98762010-11-03 16:12:44 +00001862 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001863 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001864 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001865 }
David Chisnall9f6614e2011-03-23 16:36:54 +00001866 llvm::GlobalVariable *IvarOffsetArray =
1867 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1868
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001869
1870 // Collect information about instance methods
1871 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1872 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001873 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001874 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001875 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001876 InstanceMethodSels.push_back((*iter)->getSelector());
1877 std::string TypeStr;
1878 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001879 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001880 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001881
1882 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1883 InstanceMethodTypes);
1884
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001885
1886 // Collect information about class methods
1887 llvm::SmallVector<Selector, 16> ClassMethodSels;
1888 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001889 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001890 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001891 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001892 ClassMethodSels.push_back((*iter)->getSelector());
1893 std::string TypeStr;
1894 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001895 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001896 }
1897 // Collect the names of referenced protocols
1898 llvm::SmallVector<std::string, 16> Protocols;
1899 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1900 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1901 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001902 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001903
1904
1905
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001906 // Get the superclass pointer.
1907 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001908 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001909 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1910 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001911 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001912 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001913 // Empty vector used to construct empty method lists
1914 llvm::SmallVector<llvm::Constant*, 1> empty;
1915 // Generate the method and instance variable lists
1916 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001917 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001918 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001919 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001920 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1921 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001922 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001923 // we emit a symbol containing the offset for each ivar in the class. This
1924 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1925 // for the legacy ABI, without causing problems. The converse is also
1926 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001927
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001928 // Offset pointer for getting at the correct field in the ivar list when
1929 // setting up the alias. These are: The base address for the global, the
1930 // ivar array (second field), the ivar in this list (set for each ivar), and
1931 // the offset (third field in ivar structure)
1932 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1933 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001934 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001935 llvm::ConstantInt::get(IndexTy, 2) };
1936
David Chisnalle0d98762010-11-03 16:12:44 +00001937
1938 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1939 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001940 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001941 + IVD->getNameAsString();
1942 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001943 // Get the correct ivar field
1944 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1945 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001946 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001947 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1948 if (offset) {
1949 offset->setInitializer(offsetValue);
1950 // If this is the real definition, change its linkage type so that
1951 // different modules will use this one, rather than their private
1952 // copy.
1953 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1954 } else {
1955 // Add a new alias if there isn't one already.
1956 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1957 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1958 }
1959 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001960 //Generate metaclass for class methods
1961 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001962 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001963 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001964
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001965 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001966 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001967 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001968 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001969 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001970 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1971 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001972
1973 // Resolve the class aliases, if they exist.
1974 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001975 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001976 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001977 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001978 ClassPtrAlias = 0;
1979 }
1980 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001981 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001982 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001983 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001984 MetaClassPtrAlias = 0;
1985 }
1986
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001987 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001988 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001989 Classes.push_back(ClassStruct);
1990}
1991
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001992
Mike Stump1eb44332009-09-09 15:08:12 +00001993llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001994 // Only emit an ObjC load function if no Objective-C stuff has been called
1995 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00001996 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001997 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00001998
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001999 // Add all referenced protocols to a category.
2000 GenerateProtocolHolderCategory();
2001
Chris Lattnere160c9b2009-01-27 05:06:01 +00002002 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2003 SelectorTy->getElementType());
2004 const llvm::Type *SelStructPtrTy = SelectorTy;
2005 bool isSelOpaque = false;
2006 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00002007 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
2008 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002009 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002010 isSelOpaque = true;
2011 }
2012
Eli Friedman1b8956e2008-06-01 16:00:02 +00002013 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00002014 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00002015 TheModule.addTypeName(".objc_id", IdTy);
2016 TheModule.addTypeName(".objc_imp", IMPTy);
2017
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002018 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002019 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002020 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002021 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002022 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002023 ConstantStrings.size() + 1);
2024 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002025
Daniel Dunbar1b096952009-11-29 02:38:47 +00002026 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002027
Daniel Dunbar1b096952009-11-29 02:38:47 +00002028 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002029
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002030 Elements.push_back(MakeConstantString(StringClass,
2031 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002032 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002033 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002034 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00002035 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002036 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002037 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002038 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002039 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002040 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002041 Elements.clear();
2042 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002043 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002044 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002045 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002046 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002047 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002048 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002049 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00002050 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00002051 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002052 llvm::Type::getInt16Ty(VMContext),
2053 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002054 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002055
2056 Elements.clear();
2057 // Pointer to an array of selectors used in this module.
2058 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002059 std::vector<llvm::GlobalAlias*> SelectorAliases;
2060 for (SelectorMap::iterator iter = SelectorTable.begin(),
2061 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2062
2063 std::string SelNameStr = iter->first.getAsString();
2064 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2065
2066 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2067 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2068 e = Types.end() ; i!=e ; i++) {
2069
2070 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2071 if (!i->first.empty())
2072 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2073
2074 Elements.push_back(SelName);
2075 Elements.push_back(SelectorTypeEncoding);
2076 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2077 Elements.clear();
2078
2079 // Store the selector alias for later replacement
2080 SelectorAliases.push_back(i->second);
2081 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002082 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002083 unsigned SelectorCount = Selectors.size();
2084 // NULL-terminate the selector list. This should not actually be required,
2085 // because the selector list has a length field. Unfortunately, the GCC
2086 // runtime decides to ignore the length field and expects a NULL terminator,
2087 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002088 Elements.push_back(NULLPtr);
2089 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002090 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002091 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002092
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002093 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002094 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2095 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002096 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002097 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002098 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002099
2100 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002101 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2102
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002103 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall9f6614e2011-03-23 16:36:54 +00002104 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2105 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002106 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2107 Idxs, 2);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002108 // If selectors are defined as an opaque type, cast the pointer to this
2109 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002110 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002111 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2112 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002113 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002114
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002115 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002116 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002117 Classes.size()));
2118 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002119 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002120 Categories.size()));
2121 // Create an array of classes, then categories, then static object instances
2122 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2123 // NULL-terminated list of static object instances (mainly constant strings)
2124 Classes.push_back(Statics);
2125 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002126 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002127 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002128 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002129 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2130
2131 // The symbol table is contained in a module which has some version-checking
2132 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00002133 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002134 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002135 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002136 // Runtime version, used for ABI compatibility checking.
2137 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002138 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002139 llvm::TargetData td(&TheModule);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002140 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Andersona1cf15f2009-07-14 23:10:40 +00002141 td.getTypeSizeInBits(ModuleTy)/8));
David Chisnall9f6614e2011-03-23 16:36:54 +00002142
2143 // The path to the source file where this module was declared
2144 SourceManager &SM = CGM.getContext().getSourceManager();
2145 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2146 std::string path =
2147 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2148 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2149
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002150 Elements.push_back(SymTab);
2151 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2152
2153 // Create the load function calling the runtime entry point with the module
2154 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002155 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002156 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002157 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2158 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002159 llvm::BasicBlock *EntryBB =
2160 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002161 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002162 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002163
2164 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002165 llvm::PointerType::getUnqual(ModuleTy));
2166 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00002167 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002168 Builder.CreateCall(Register, Module);
2169 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002170
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002171 return LoadFunction;
2172}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002173
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002174llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002175 const ObjCContainerDecl *CD) {
2176 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002177 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnall9f6614e2011-03-23 16:36:54 +00002178 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2179 llvm::StringRef ClassName = CD->getName();
2180 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002181 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002182
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002183 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00002184 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002185 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002186 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2187 MethodName, isClassMethod);
2188
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002189 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002190 = llvm::Function::Create(MethodTy,
2191 llvm::GlobalValue::InternalLinkage,
2192 FunctionName,
2193 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002194 return Method;
2195}
2196
Daniel Dunbar49f66022008-09-24 03:38:44 +00002197llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002198 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002199}
2200
2201llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002202 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002203}
2204
David Chisnall8fac25d2010-12-26 22:13:16 +00002205llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002206 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002207}
2208llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002209 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002210}
2211
Daniel Dunbar309a4362009-07-24 07:40:24 +00002212llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002213 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002214}
2215
David Chisnall9f6614e2011-03-23 16:36:54 +00002216void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002217 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002218 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002219}
Chris Lattner5dc08672009-05-08 00:11:50 +00002220
David Chisnall0faa5162009-12-24 02:26:34 +00002221
David Chisnall9f6614e2011-03-23 16:36:54 +00002222void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002223 const ObjCAtTryStmt &S) {
2224 // Unlike the Apple non-fragile runtimes, which also uses
2225 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2226 // EH support isn't a veneer over C++ EH. Instead, exception
2227 // objects are created by __objc_exception_throw and destroyed by
2228 // the personality function; this avoids the need for bracketing
2229 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2230 // (or even _Unwind_DeleteException), but probably doesn't
2231 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002232 //
David Chisnall80558d22011-03-20 21:35:39 +00002233 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002234 // exception handler.
2235 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2236 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002237}
2238
David Chisnall9f6614e2011-03-23 16:36:54 +00002239void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002240 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002241 llvm::Value *ExceptionAsObject;
2242
Chris Lattner5dc08672009-05-08 00:11:50 +00002243 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2244 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002245 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002246 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002247 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002248 "Unexpected rethrow outside @catch block.");
2249 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2250 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002251 ExceptionAsObject =
2252 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Chris Lattner5dc08672009-05-08 00:11:50 +00002254 // Note: This may have to be an invoke, if we want to support constructs like:
2255 // @try {
2256 // @throw(obj);
2257 // }
2258 // @catch(id) ...
2259 //
2260 // This is effectively turning @throw into an incredibly-expensive goto, but
2261 // it may happen as a result of inlining followed by missed optimizations, or
2262 // as a result of stupidity.
2263 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2264 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002265 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002266 CGF.Builder.CreateUnreachable();
2267 } else {
David Chisnall9f6614e2011-03-23 16:36:54 +00002268 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattner5dc08672009-05-08 00:11:50 +00002269 &ExceptionAsObject+1);
2270 }
2271 // Clear the insertion point to indicate we are in unreachable code.
2272 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002273}
2274
David Chisnall9f6614e2011-03-23 16:36:54 +00002275llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002276 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002277 CGBuilderTy B = CGF.Builder;
2278 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2279 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002280}
2281
David Chisnall9f6614e2011-03-23 16:36:54 +00002282void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002283 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002284 CGBuilderTy B = CGF.Builder;
2285 src = EnforceType(B, src, IdTy);
2286 dst = EnforceType(B, dst, PtrToIdTy);
2287 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002288}
2289
David Chisnall9f6614e2011-03-23 16:36:54 +00002290void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002291 llvm::Value *src, llvm::Value *dst,
2292 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002293 CGBuilderTy B = CGF.Builder;
2294 src = EnforceType(B, src, IdTy);
2295 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002296 if (!threadlocal)
2297 B.CreateCall2(GlobalAssignFn, src, dst);
2298 else
2299 // FIXME. Add threadloca assign API
2300 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002301}
2302
David Chisnall9f6614e2011-03-23 16:36:54 +00002303void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002304 llvm::Value *src, llvm::Value *dst,
2305 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002306 CGBuilderTy B = CGF.Builder;
2307 src = EnforceType(B, src, IdTy);
2308 dst = EnforceType(B, dst, PtrToIdTy);
2309 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002310}
2311
David Chisnall9f6614e2011-03-23 16:36:54 +00002312void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002313 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002314 CGBuilderTy B = CGF.Builder;
2315 src = EnforceType(B, src, IdTy);
2316 dst = EnforceType(B, dst, PtrToIdTy);
2317 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002318}
2319
David Chisnall9f6614e2011-03-23 16:36:54 +00002320void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002321 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002322 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002323 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002324 CGBuilderTy B = CGF.Builder;
2325 DestPtr = EnforceType(B, DestPtr, IdTy);
2326 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2327
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002328 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002329}
2330
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002331llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2332 const ObjCInterfaceDecl *ID,
2333 const ObjCIvarDecl *Ivar) {
2334 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2335 + '.' + Ivar->getNameAsString();
2336 // Emit the variable and initialize it with what we think the correct value
2337 // is. This allows code compiled with non-fragile ivars to work correctly
2338 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002339 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2340 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002341 // This will cause a run-time crash if we accidentally use it. A value of
2342 // 0 would seem more sensible, but will silently overwrite the isa pointer
2343 // causing a great deal of confusion.
2344 uint64_t Offset = -1;
2345 // We can't call ComputeIvarBaseOffset() here if we have the
2346 // implementation, because it will create an invalid ASTRecordLayout object
2347 // that we are then stuck with forever, so we only initialize the ivar
2348 // offset variable with a guess if we only have the interface. The
2349 // initializer will be reset later anyway, when we are generating the class
2350 // description.
2351 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002352 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002353 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2354
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002355 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002356 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002357 // Don't emit the guess in non-PIC code because the linker will not be able
2358 // to replace it with the real version for a library. In non-PIC code you
2359 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002360 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002361 if (CGM.getLangOptions().PICLevel) {
2362 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2363 llvm::Type::getInt32Ty(VMContext), false,
2364 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2365 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2366 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2367 IvarOffsetGV, Name);
2368 } else {
2369 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002370 llvm::Type::getInt32PtrTy(VMContext), false,
2371 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002372 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002373 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002374 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002375}
2376
David Chisnall9f6614e2011-03-23 16:36:54 +00002377LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002378 QualType ObjectTy,
2379 llvm::Value *BaseValue,
2380 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002381 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002382 const ObjCInterfaceDecl *ID =
2383 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002384 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2385 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002386}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002387
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002388static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2389 const ObjCInterfaceDecl *OID,
2390 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002391 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002392 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002393 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2394 if (OIVD == Ivars[k])
2395 return OID;
2396 }
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002398 // Otherwise check in the super class.
2399 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2400 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002402 return 0;
2403}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002404
David Chisnall9f6614e2011-03-23 16:36:54 +00002405llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002406 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002407 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002408 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002409 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002410 return CGF.Builder.CreateZExtOrBitCast(
2411 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2412 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2413 PtrDiffTy);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002414 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002415 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002416 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002417}
2418
David Chisnall9f6614e2011-03-23 16:36:54 +00002419CGObjCRuntime *
2420clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2421 if (CGM.getLangOptions().ObjCNonFragileABI)
2422 return new CGObjCGNUstep(CGM);
2423 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002424}