blob: baf4ce4fb33b29922acaa19b91fba96f32fd4ebe [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000021
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnalle1d2584d2011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000038
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000039#include <map>
David Chisnalld7972f52011-03-23 16:36:54 +000040#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000041
42
Chris Lattner87ab27d2008-06-26 04:19:03 +000043using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000044using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000045using llvm::dyn_cast;
46
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048namespace {
David Chisnalld7972f52011-03-23 16:36:54 +000049/**
50 * Class that lazily initialises the runtime function. Avoids inserting the
51 * types and the function declaration into a module if they're not used, and
52 * avoids constructing the type more than once if it's used more than once.
53 */
54class LazyRuntimeFunction {
55 CodeGenModule *CGM;
56 std::vector<const llvm::Type*> ArgTys;
57 const char *FunctionName;
58 llvm::Function *Function;
59 public:
60 /**
61 * Constructor leaves this class uninitialized, because it is intended to
62 * be used as a field in another class and not all of the types that are
63 * used as arguments will necessarily be available at construction time.
64 */
65 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
66
67 /**
68 * Initialises the lazy function with the name, return type, and the types
69 * of the arguments.
70 */
71 END_WITH_NULL
72 void init(CodeGenModule *Mod, const char *name,
73 const llvm::Type *RetTy, ...) {
74 CGM =Mod;
75 FunctionName = name;
76 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000077 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000078 va_list Args;
79 va_start(Args, RetTy);
80 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
81 ArgTys.push_back(ArgTy);
82 va_end(Args);
83 // Push the return type on at the end so we can pop it off easily
84 ArgTys.push_back(RetTy);
85 }
86 /**
87 * Overloaded cast operator, allows the class to be implicitly cast to an
88 * LLVM constant.
89 */
90 operator llvm::Function*() {
91 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000092 if (0 == FunctionName) return 0;
93 // We put the return type on the end of the vector, so pop it back off
David Chisnalld7972f52011-03-23 16:36:54 +000094 const llvm::Type *RetTy = ArgTys.back();
95 ArgTys.pop_back();
96 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
97 Function =
98 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000099 // We won't need to use the types again, so we may as well clean up the
100 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +0000101 ArgTys.resize(0);
102 }
103 return Function;
104 }
105};
106
107
108/**
109 * GNU Objective-C runtime code generation. This class implements the parts of
110 * Objective-C support that are specific to the GNU family of runtimes (GCC and
111 * GNUstep).
112 */
113class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000114protected:
David Chisnalld7972f52011-03-23 16:36:54 +0000115 CodeGenModule &CGM;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000116 llvm::Module &TheModule;
David Chisnall76803412011-03-23 22:52:06 +0000117 const llvm::StructType *ObjCSuperTy;
118 const llvm::PointerType *PtrToObjCSuperTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000119 const llvm::PointerType *SelectorTy;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000120 const llvm::IntegerType *Int8Ty;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000121 const llvm::PointerType *PtrToInt8Ty;
David Chisnall76803412011-03-23 22:52:06 +0000122 const llvm::PointerType *IMPTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000123 const llvm::PointerType *IdTy;
David Chisnall5bb4efd2010-02-03 15:59:02 +0000124 const llvm::PointerType *PtrToIdTy;
John McCall2da83a32010-02-26 00:48:12 +0000125 CanQualType ASTIdTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000126 const llvm::IntegerType *IntTy;
127 const llvm::PointerType *PtrTy;
128 const llvm::IntegerType *LongTy;
David Chisnall168b80f2010-12-26 22:13:16 +0000129 const llvm::IntegerType *SizeTy;
130 const llvm::IntegerType *PtrDiffTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000131 const llvm::PointerType *PtrToIntTy;
David Chisnall168b80f2010-12-26 22:13:16 +0000132 const llvm::Type *BoolTy;
David Chisnall76803412011-03-23 22:52:06 +0000133 /// Metadata kind used to tie method lookups to message sends.
134 unsigned msgSendMDKind;
David Chisnalld3858d62011-03-25 11:57:33 +0000135 llvm::Constant *MakeConstantString(const std::string &Str,
136 const std::string &Name="") {
137 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
138 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
139 }
140 llvm::Constant *ExportUniqueString(const std::string &Str,
141 const std::string prefix) {
142 std::string name = prefix + Str;
143 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
144 if (!ConstStr) {
145 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
146 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
147 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
148 }
149 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
150 }
David Chisnall76803412011-03-23 22:52:06 +0000151
David Chisnall76803412011-03-23 22:52:06 +0000152 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000153 std::vector<llvm::Constant*> &V,
154 llvm::StringRef Name="",
155 llvm::GlobalValue::LinkageTypes linkage
156 =llvm::GlobalValue::InternalLinkage) {
157 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
158 return new llvm::GlobalVariable(TheModule, Ty, false,
159 linkage, C, Name);
160 }
161
David Chisnall76803412011-03-23 22:52:06 +0000162 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000163 std::vector<llvm::Constant*> &V,
164 llvm::StringRef Name="",
165 llvm::GlobalValue::LinkageTypes linkage
166 =llvm::GlobalValue::InternalLinkage) {
167 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
168 return new llvm::GlobalVariable(TheModule, Ty, false,
169 linkage, C, Name);
170 }
David Chisnall76803412011-03-23 22:52:06 +0000171 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000172 std::vector<llvm::Constant*> &V,
173 llvm::StringRef Name="",
174 llvm::GlobalValue::LinkageTypes linkage
175 =llvm::GlobalValue::InternalLinkage) {
176 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
177 return MakeGlobal(ArrayTy, V, Name, linkage);
178 }
179 /**
180 * Ensures that the value has the required type, by inserting a bitcast if
181 * required. This function lets us avoid inserting bitcasts that are
182 * redundant.
183 */
David Chisnall76803412011-03-23 22:52:06 +0000184 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
185 if (V->getType() == Ty) return V;
186 return B.CreateBitCast(V, Ty);
187 }
188 // Some zeros used for GEPs in lots of places.
189 llvm::Constant *Zeros[2];
David Chisnalld3858d62011-03-25 11:57:33 +0000190 /**
191 * Null pointer value. Mainly used as a terminator in various arrays.
192 */
David Chisnall76803412011-03-23 22:52:06 +0000193 llvm::Constant *NULLPtr;
194 llvm::LLVMContext &VMContext;
195private:
Daniel Dunbar566421c2009-05-04 15:31:17 +0000196 llvm::GlobalAlias *ClassPtrAlias;
197 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000198 std::vector<llvm::Constant*> Classes;
199 std::vector<llvm::Constant*> Categories;
200 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall358e7512010-01-27 12:49:23 +0000201 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000202 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnalld7972f52011-03-23 16:36:54 +0000203 /**
204 * For each variant of a selector, we store the type encoding and a
205 * placeholder value. For an untyped selector, the type will be the empty
206 * string. Selector references are all done via the module's selector table,
207 * so we create an alias as a placeholder and then replace it with the real
208 * value later.
209 */
210 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
211 /**
212 * A map from selectors to selector types. This allows us to emit all
213 * selectors of the same name and type together.
214 */
215 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
216 SelectorMap;
217 SelectorMap SelectorTable;
218
David Chisnall5bb4efd2010-02-03 15:59:02 +0000219 // Selectors that we don't emit in GC mode
220 Selector RetainSel, ReleaseSel, AutoreleaseSel;
221 // Functions used for GC.
David Chisnalld7972f52011-03-23 16:36:54 +0000222 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
223 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000224
David Chisnalld3858d62011-03-25 11:57:33 +0000225protected:
David Chisnalld7972f52011-03-23 16:36:54 +0000226 LazyRuntimeFunction ExceptionThrowFn;
David Chisnalld3858d62011-03-25 11:57:33 +0000227 LazyRuntimeFunction ExceptionReThrowFn;
228 LazyRuntimeFunction EnterCatchFn;
229 LazyRuntimeFunction ExitCatchFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000230 LazyRuntimeFunction SyncEnterFn;
231 LazyRuntimeFunction SyncExitFn;
232
David Chisnalld3858d62011-03-25 11:57:33 +0000233private:
234
David Chisnalld7972f52011-03-23 16:36:54 +0000235 LazyRuntimeFunction EnumerationMutationFn;
236 LazyRuntimeFunction GetPropertyFn;
237 LazyRuntimeFunction SetPropertyFn;
238 LazyRuntimeFunction GetStructPropertyFn;
239 LazyRuntimeFunction SetStructPropertyFn;
240
241 // The version of the runtime that this class targets. Must match the version
242 // in the runtime.
243 const int RuntimeVersion;
244 // The version of the protocol class. Used to differentiate between ObjC1
245 // and ObjC2 protocols.
246 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000247private:
248 llvm::Constant *GenerateIvarList(
249 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
250 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
251 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnalld7972f52011-03-23 16:36:54 +0000252 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
253 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000254 const llvm::SmallVectorImpl<Selector> &MethodSels,
255 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000256 bool isClassMethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000257 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000258 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
259 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
260 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000261 llvm::Constant *GenerateProtocolList(
262 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000263 // To ensure that all protocols are seen by the runtime, we add a category on
264 // a class defined in the runtime, declaring no methods, but adopting the
265 // protocols.
266 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000267 llvm::Constant *GenerateClassStructure(
268 llvm::Constant *MetaClass,
269 llvm::Constant *SuperClass,
270 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000271 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000272 llvm::Constant *Version,
273 llvm::Constant *InstanceSize,
274 llvm::Constant *IVars,
275 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000276 llvm::Constant *Protocols,
277 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000278 llvm::Constant *Properties,
279 bool isMeta=false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000280 llvm::Constant *GenerateProtocolMethodList(
281 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
282 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000283 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
284 const std::string &TypeEncoding, bool lval);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000285 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
286 const ObjCIvarDecl *Ivar);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000287 void EmitClassRef(const std::string &className);
David Chisnall76803412011-03-23 22:52:06 +0000288protected:
289 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
290 llvm::Value *&Receiver,
291 llvm::Value *cmd,
292 llvm::MDNode *node) = 0;
293 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
294 llvm::Value *ObjCSuper,
295 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000296public:
David Chisnalld7972f52011-03-23 16:36:54 +0000297 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
298 unsigned protocolClassVersion);
299
David Chisnall481e3a82010-01-23 02:40:42 +0000300 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000301
302 virtual RValue
303 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000304 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000305 QualType ResultType,
306 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000307 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000308 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000309 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000310 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000311 virtual RValue
312 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000313 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000314 QualType ResultType,
315 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000316 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000317 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000318 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000319 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000320 const CallArgList &CallArgs,
321 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000322 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000323 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000324 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
325 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000326 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
327 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000328 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000329
330 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000331 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000332 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
333 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000334 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000335 const ObjCProtocolDecl *PD);
336 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000337 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000338 virtual llvm::Function *GetPropertyGetFunction();
339 virtual llvm::Function *GetPropertySetFunction();
David Chisnall168b80f2010-12-26 22:13:16 +0000340 virtual llvm::Function *GetSetStructFunction();
341 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000342 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000343
David Chisnalld7972f52011-03-23 16:36:54 +0000344 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000345 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000346 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000347 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000348 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000349 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000350 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000351 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000352 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000353 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000354 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000355 llvm::Value *src, llvm::Value *dest,
356 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000357 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000358 llvm::Value *src, llvm::Value *dest,
359 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000360 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000361 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000362 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000363 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000364 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000365 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000366 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000367 QualType ObjectTy,
368 llvm::Value *BaseValue,
369 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000370 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000371 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000372 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000373 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000374 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000375 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000376 return NULLPtr;
377 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000378};
David Chisnalld7972f52011-03-23 16:36:54 +0000379/**
380 * Class representing the legacy GCC Objective-C ABI. This is the default when
381 * -fobjc-nonfragile-abi is not specified.
382 *
383 * The GCC ABI target actually generates code that is approximately compatible
384 * with the new GNUstep runtime ABI, but refrains from using any features that
385 * would not work with the GCC runtime. For example, clang always generates
386 * the extended form of the class structure, and the extra fields are simply
387 * ignored by GCC libobjc.
388 */
389class CGObjCGCC : public CGObjCGNU {
David Chisnall76803412011-03-23 22:52:06 +0000390 /**
391 * The GCC ABI message lookup function. Returns an IMP pointing to the
392 * method implementation for this message.
393 */
394 LazyRuntimeFunction MsgLookupFn;
395 /**
396 * The GCC ABI superclass message lookup function. Takes a pointer to a
397 * structure describing the receiver and the class, and a selector as
398 * arguments. Returns the IMP for the corresponding method.
399 */
400 LazyRuntimeFunction MsgLookupSuperFn;
401protected:
402 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
403 llvm::Value *&Receiver,
404 llvm::Value *cmd,
405 llvm::MDNode *node) {
406 CGBuilderTy &Builder = CGF.Builder;
407 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
408 EnforceType(Builder, Receiver, IdTy),
409 EnforceType(Builder, cmd, SelectorTy));
410 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
411 return imp;
412 }
413 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
414 llvm::Value *ObjCSuper,
415 llvm::Value *cmd) {
416 CGBuilderTy &Builder = CGF.Builder;
417 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
418 PtrToObjCSuperTy), cmd};
419 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
420 }
David Chisnalld7972f52011-03-23 16:36:54 +0000421 public:
David Chisnall76803412011-03-23 22:52:06 +0000422 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
423 // IMP objc_msg_lookup(id, SEL);
424 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
425 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
426 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
427 PtrToObjCSuperTy, SelectorTy, NULL);
428 }
David Chisnalld7972f52011-03-23 16:36:54 +0000429};
430/**
431 * Class used when targeting the new GNUstep runtime ABI.
432 */
433class CGObjCGNUstep : public CGObjCGNU {
David Chisnall76803412011-03-23 22:52:06 +0000434 /**
435 * The slot lookup function. Returns a pointer to a cacheable structure
436 * that contains (among other things) the IMP.
437 */
438 LazyRuntimeFunction SlotLookupFn;
439 /**
440 * The GNUstep ABI superclass message lookup function. Takes a pointer to
441 * a structure describing the receiver and the class, and a selector as
442 * arguments. Returns the slot for the corresponding method. Superclass
443 * message lookup rarely changes, so this is a good caching opportunity.
444 */
445 LazyRuntimeFunction SlotLookupSuperFn;
446 /**
447 * Type of an slot structure pointer. This is returned by the various
448 * lookup functions.
449 */
450 llvm::Type *SlotTy;
451 protected:
452 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
453 llvm::Value *&Receiver,
454 llvm::Value *cmd,
455 llvm::MDNode *node) {
456 CGBuilderTy &Builder = CGF.Builder;
457 llvm::Function *LookupFn = SlotLookupFn;
458
459 // Store the receiver on the stack so that we can reload it later
460 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
461 Builder.CreateStore(Receiver, ReceiverPtr);
462
463 llvm::Value *self;
464
465 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
466 self = CGF.LoadObjCSelf();
467 } else {
468 self = llvm::ConstantPointerNull::get(IdTy);
469 }
470
471 // The lookup function is guaranteed not to capture the receiver pointer.
472 LookupFn->setDoesNotCapture(1);
473
474 llvm::CallInst *slot =
475 Builder.CreateCall3(LookupFn,
476 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
477 EnforceType(Builder, cmd, SelectorTy),
478 EnforceType(Builder, self, IdTy));
479 slot->setOnlyReadsMemory();
480 slot->setMetadata(msgSendMDKind, node);
481
482 // Load the imp from the slot
483 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
484
485 // The lookup function may have changed the receiver, so make sure we use
486 // the new one.
487 Receiver = Builder.CreateLoad(ReceiverPtr, true);
488 return imp;
489 }
490 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
491 llvm::Value *ObjCSuper,
492 llvm::Value *cmd) {
493 CGBuilderTy &Builder = CGF.Builder;
494 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
495
496 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
497 lookupArgs+2);
498 slot->setOnlyReadsMemory();
499
500 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
501 }
David Chisnalld7972f52011-03-23 16:36:54 +0000502 public:
David Chisnall76803412011-03-23 22:52:06 +0000503 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
504 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
505 PtrTy, PtrTy, IntTy, IMPTy, NULL);
506 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
507 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
508 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
509 SelectorTy, IdTy, NULL);
510 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
511 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
512 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000513 // If we're in ObjC++ mode, then we want to make
514 if (CGM.getLangOptions().CPlusPlus) {
515 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
516 // void *__cxa_begin_catch(void *e)
517 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
518 // void __cxa_end_catch(void)
519 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
520 // void _Unwind_Resume_or_Rethrow(void*)
521 EnterCatchFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
522 }
David Chisnall76803412011-03-23 22:52:06 +0000523 }
David Chisnalld7972f52011-03-23 16:36:54 +0000524};
525
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000526} // end anonymous namespace
527
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000528
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000529/// Emits a reference to a dummy variable which is emitted with each class.
530/// This ensures that a linker error will be generated when trying to link
531/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000532void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000533 std::string symbolRef = "__objc_class_ref_" + className;
534 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000535 if (TheModule.getGlobalVariable(symbolRef))
536 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000537 std::string symbolName = "__objc_class_name_" + className;
538 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
539 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000540 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
541 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000542 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000543 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000544 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000545}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000546
David Chisnalld7972f52011-03-23 16:36:54 +0000547static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
548 const llvm::StringRef &CategoryName, const Selector MethodName,
549 bool isClassMethod) {
550 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000551 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
552 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000553 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
554 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000555}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000556
David Chisnalld7972f52011-03-23 16:36:54 +0000557CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
558 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000559 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
560 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
561 ProtocolVersion(protocolClassVersion) {
David Chisnalld7972f52011-03-23 16:36:54 +0000562
David Chisnall01aa4672010-04-28 19:33:36 +0000563
564 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
565
David Chisnalld7972f52011-03-23 16:36:54 +0000566 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000567 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000568 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000569 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000570 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000571 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000572 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000573 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000574 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000575 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000576
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000577 Int8Ty = llvm::Type::getInt8Ty(VMContext);
578 // C string type. Used in lots of places.
579 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
580
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000581 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000582 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000583 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000584 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000585 QualType selTy = CGM.getContext().getObjCSelType();
586 if (QualType() == selTy) {
587 SelectorTy = PtrToInt8Ty;
588 } else {
589 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
590 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000591
Owen Anderson9793f0e2009-07-29 22:16:19 +0000592 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000593 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattner4bd55962008-03-30 23:03:07 +0000595 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000596 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000597 if (QualType() == ASTIdTy) {
598 IdTy = PtrToInt8Ty;
599 } else {
600 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
601 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000602 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000603
David Chisnall76803412011-03-23 22:52:06 +0000604 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
605 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
606
David Chisnalld7972f52011-03-23 16:36:54 +0000607 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
608
609 // void objc_exception_throw(id);
610 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000611 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000612 // int objc_sync_enter(id);
613 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
614 // int objc_sync_exit(id);
615 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
616
617 // void objc_enumerationMutation (id)
618 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
619 IdTy, NULL);
620
621 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
622 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
623 PtrDiffTy, BoolTy, NULL);
624 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
625 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
626 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
627 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
628 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
629 PtrDiffTy, BoolTy, BoolTy, NULL);
630 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
631 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
632 PtrDiffTy, BoolTy, BoolTy, NULL);
633
Chris Lattner4bd55962008-03-30 23:03:07 +0000634 // IMP type
635 std::vector<const llvm::Type*> IMPArgs;
636 IMPArgs.push_back(IdTy);
637 IMPArgs.push_back(SelectorTy);
David Chisnall76803412011-03-23 22:52:06 +0000638 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
639 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000640
David Chisnalld3858d62011-03-25 11:57:33 +0000641 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000642 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
643 // Get selectors needed in GC mode
644 RetainSel = GetNullarySelector("retain", CGM.getContext());
645 ReleaseSel = GetNullarySelector("release", CGM.getContext());
646 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
647
648 // Get functions needed in GC mode
649
650 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000651 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
652 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000653 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000654 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
655 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000656 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000657 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
658 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000659 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000660 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000661 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000662 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000663 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000664 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
665 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000666 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000667}
Mike Stumpdd93a192009-07-31 21:31:32 +0000668
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000669// This has to perform the lookup every time, since posing and related
670// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000671llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000672 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000673 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000674 // With the incompatible ABI, this will need to be replaced with a direct
675 // reference to the class symbol. For the compatible nonfragile ABI we are
676 // still performing this lookup at run time but emitting the symbol for the
677 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000678 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000679 ClassName = Builder.CreateStructGEP(ClassName, 0);
680
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000681 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000682 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000683 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000684 Params,
685 true),
686 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000687 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000688}
689
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000690llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000691 const std::string &TypeEncoding, bool lval) {
692
693 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
694 llvm::GlobalAlias *SelValue = 0;
695
696
697 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
698 e = Types.end() ; i!=e ; i++) {
699 if (i->first == TypeEncoding) {
700 SelValue = i->second;
701 break;
702 }
703 }
704 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000705 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000706 llvm::GlobalValue::PrivateLinkage,
707 ".objc_selector_"+Sel.getAsString(), NULL,
708 &TheModule);
709 Types.push_back(TypedSelector(TypeEncoding, SelValue));
710 }
711
David Chisnall76803412011-03-23 22:52:06 +0000712 if (lval) {
713 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
714 Builder.CreateStore(SelValue, tmp);
715 return tmp;
716 }
717 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000718}
719
720llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
721 bool lval) {
722 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000723}
724
Daniel Dunbar45858d22010-02-03 20:11:42 +0000725llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000726 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000727 std::string SelTypes;
728 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000729 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000730}
731
John McCall2ca705e2010-07-24 00:37:23 +0000732llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000733 if (!CGM.getLangOptions().CPlusPlus) {
734 if (T->isObjCIdType()
735 || T->isObjCQualifiedIdType()) {
736 // With the old ABI, there was only one kind of catchall, which broke
737 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
738 // a pointer indicating object catchalls, and NULL to indicate real
739 // catchalls
740 if (CGM.getLangOptions().ObjCNonFragileABI) {
741 return MakeConstantString("@id");
742 } else {
743 return 0;
744 }
745 }
746
747 // All other types should be Objective-C interface pointer types.
748 const ObjCObjectPointerType *OPT =
749 T->getAs<ObjCObjectPointerType>();
750 assert(OPT && "Invalid @catch type.");
751 const ObjCInterfaceDecl *IDecl =
752 OPT->getObjectType()->getInterface();
753 assert(IDecl && "Invalid @catch type.");
754 return MakeConstantString(IDecl->getIdentifier()->getName());
755 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000756 // For Objective-C++, we want to provide the ability to catch both C++ and
757 // Objective-C objects in the same function.
758
759 // There's a particular fixed type info for 'id'.
760 if (T->isObjCIdType() ||
761 T->isObjCQualifiedIdType()) {
762 llvm::Constant *IDEHType =
763 CGM.getModule().getGlobalVariable("__objc_id_type_info");
764 if (!IDEHType)
765 IDEHType =
766 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
767 false,
768 llvm::GlobalValue::ExternalLinkage,
769 0, "__objc_id_type_info");
770 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
771 }
772
773 const ObjCObjectPointerType *PT =
774 T->getAs<ObjCObjectPointerType>();
775 assert(PT && "Invalid @catch type.");
776 const ObjCInterfaceType *IT = PT->getInterfaceType();
777 assert(IT && "Invalid @catch type.");
778 std::string className = IT->getDecl()->getIdentifier()->getName();
779
780 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
781
782 // Return the existing typeinfo if it exists
783 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
784 if (typeinfo) return typeinfo;
785
786 // Otherwise create it.
787
788 // vtable for gnustep::libobjc::__objc_class_type_info
789 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
790 // platform's name mangling.
791 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
792 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
793 if (!Vtable) {
794 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
795 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
796 }
797 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
798 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
799 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
800
801 llvm::Constant *typeName =
802 ExportUniqueString(className, "__objc_eh_typename_");
803
804 std::vector<llvm::Constant*> fields;
805 fields.push_back(Vtable);
806 fields.push_back(typeName);
807 llvm::Constant *TI =
808 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
809 NULL), fields, "__objc_eh_typeinfo_" + className,
810 llvm::GlobalValue::LinkOnceODRLinkage);
811 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000812}
813
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000814/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000815llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000816
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000817 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000818
David Chisnall358e7512010-01-27 12:49:23 +0000819 // Look for an existing one
820 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
821 if (old != ObjCStrings.end())
822 return old->getValue();
823
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000824 std::vector<llvm::Constant*> Ivars;
825 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000826 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000827 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000828 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000829 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000830 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000831 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
832 ObjCStrings[Str] = ObjCStr;
833 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000834 return ObjCStr;
835}
836
837///Generates a message send where the super is the receiver. This is a message
838///send to self with special delivery semantics indicating which class's method
839///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000840RValue
841CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000842 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000843 QualType ResultType,
844 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000845 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000846 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000847 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000848 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000849 const CallArgList &CallArgs,
850 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000851 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
852 if (Sel == RetainSel || Sel == AutoreleaseSel) {
853 return RValue::get(Receiver);
854 }
855 if (Sel == ReleaseSel) {
856 return RValue::get(0);
857 }
858 }
David Chisnallea529a42010-05-01 12:37:16 +0000859
860 CGBuilderTy &Builder = CGF.Builder;
861 llvm::Value *cmd = GetSelector(Builder, Sel);
862
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000863
864 CallArgList ActualArgs;
865
866 ActualArgs.push_back(
David Chisnall76803412011-03-23 22:52:06 +0000867 std::make_pair(RValue::get(EnforceType(Builder, Receiver, IdTy)),
David Chisnall9f57c292009-08-17 16:35:33 +0000868 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000869 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
870 CGF.getContext().getObjCSelType()));
871 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
872
873 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000874 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000875 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000876
Daniel Dunbar566421c2009-05-04 15:31:17 +0000877 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000878 if (isCategoryImpl) {
879 llvm::Constant *classLookupFunction = 0;
880 std::vector<const llvm::Type*> Params;
881 Params.push_back(PtrTy);
882 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000883 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000884 IdTy, Params, true), "objc_get_meta_class");
885 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000886 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000887 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000888 }
David Chisnallea529a42010-05-01 12:37:16 +0000889 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000890 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000891 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000892 // Set up global aliases for the metaclass or class pointer if they do not
893 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000894 // pointers to the class and metaclass structure created for the runtime
895 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000896 // super_class pointer from either the class or metaclass structure.
897 if (IsClassMessage) {
898 if (!MetaClassPtrAlias) {
899 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
900 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
901 Class->getNameAsString(), NULL, &TheModule);
902 }
903 ReceiverClass = MetaClassPtrAlias;
904 } else {
905 if (!ClassPtrAlias) {
906 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
907 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
908 Class->getNameAsString(), NULL, &TheModule);
909 }
910 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000911 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000912 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000913 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +0000914 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000915 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000916 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000917 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000918 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +0000919 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000920 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000921 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000922 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
923 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +0000924 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000925
David Chisnallea529a42010-05-01 12:37:16 +0000926 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
927 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000928
David Chisnall76803412011-03-23 22:52:06 +0000929 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
930 const llvm::FunctionType *impType =
931 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
932
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000933 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +0000934 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
935 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000936
David Chisnall9eecafa2010-05-01 11:15:56 +0000937 llvm::Value *impMD[] = {
938 llvm::MDString::get(VMContext, Sel.getAsString()),
939 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
940 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
941 };
942 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
943
David Chisnallff5f88c2010-05-02 13:41:58 +0000944 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +0000945 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000946 0, &call);
947 call->setMetadata(msgSendMDKind, node);
948 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000949}
950
Mike Stump11289f42009-09-09 15:08:12 +0000951/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +0000952RValue
953CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000954 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000955 QualType ResultType,
956 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000957 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000958 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000959 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000960 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +0000961 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000962 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
963 if (Sel == RetainSel || Sel == AutoreleaseSel) {
964 return RValue::get(Receiver);
965 }
966 if (Sel == ReleaseSel) {
967 return RValue::get(0);
968 }
969 }
David Chisnall75afda62010-04-27 15:08:48 +0000970
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000971 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +0000972
973 // If the return type is something that goes in an integer register, the
974 // runtime will handle 0 returns. For other cases, we fill in the 0 value
975 // ourselves.
976 //
977 // The language spec says the result of this kind of message send is
978 // undefined, but lots of people seem to have forgotten to read that
979 // paragraph and insist on sending messages to nil that have structure
980 // returns. With GCC, this generates a random return value (whatever happens
981 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +0000982 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
983 // the stack.
984 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
985 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +0000986
987 llvm::BasicBlock *startBB = 0;
988 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +0000989 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +0000990
991 if (!isPointerSizedReturn) {
992 startBB = Builder.GetInsertBlock();
993 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +0000994 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +0000995
996 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
997 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +0000998 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +0000999 CGF.EmitBlock(messageBB);
1000 }
1001
David Chisnall9f57c292009-08-17 16:35:33 +00001002 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001003 llvm::Value *cmd;
1004 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001005 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001006 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001007 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001008 cmd = EnforceType(Builder, cmd, SelectorTy);
1009 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001010
David Chisnall76803412011-03-23 22:52:06 +00001011 llvm::Value *impMD[] = {
1012 llvm::MDString::get(VMContext, Sel.getAsString()),
1013 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1014 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1015 };
1016 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
1017
1018 // Get the IMP to call
1019 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1020
1021 CallArgList ActualArgs;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001022 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001023 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001024 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
1025 CGF.getContext().getObjCSelType()));
1026 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1027
1028 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001029 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001030 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001031 const llvm::FunctionType *impType =
1032 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001033 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001034
1035
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001036 // For sender-aware dispatch, we pass the sender as the third argument to a
1037 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001038 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001039 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001040 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001041 0, &call);
1042 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001043
David Chisnall29cefd12010-05-20 13:45:48 +00001044
David Chisnall75afda62010-04-27 15:08:48 +00001045 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001046 messageBB = CGF.Builder.GetInsertBlock();
1047 CGF.Builder.CreateBr(continueBB);
1048 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001049 if (msgRet.isScalar()) {
1050 llvm::Value *v = msgRet.getScalarVal();
1051 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
1052 phi->addIncoming(v, messageBB);
1053 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1054 msgRet = RValue::get(phi);
1055 } else if (msgRet.isAggregate()) {
1056 llvm::Value *v = msgRet.getAggregateAddr();
1057 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
1058 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001059 llvm::AllocaInst *NullVal =
1060 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001061 CGF.InitTempAlloca(NullVal,
1062 llvm::Constant::getNullValue(RetTy->getElementType()));
1063 phi->addIncoming(v, messageBB);
1064 phi->addIncoming(NullVal, startBB);
1065 msgRet = RValue::getAggregate(phi);
1066 } else /* isComplex() */ {
1067 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1068 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
1069 phi->addIncoming(v.first, messageBB);
1070 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1071 startBB);
1072 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
1073 phi2->addIncoming(v.second, messageBB);
1074 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1075 startBB);
1076 msgRet = RValue::getComplex(phi, phi2);
1077 }
1078 }
1079 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001080}
1081
Mike Stump11289f42009-09-09 15:08:12 +00001082/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001083/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +00001084llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1085 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +00001086 const llvm::SmallVectorImpl<Selector> &MethodSels,
1087 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001088 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001089 if (MethodSels.empty())
1090 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001091 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001092 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001093 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1094 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001095 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001096 NULL);
1097 std::vector<llvm::Constant*> Methods;
1098 std::vector<llvm::Constant*> Elements;
1099 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1100 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001101 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001102 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001103 MethodSels[i],
1104 isClassMethodList));
1105 assert(Method && "Can't generate metadata for method that doesn't exist");
1106 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1107 Elements.push_back(C);
1108 Elements.push_back(MethodTypes[i]);
1109 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001110 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001111 Elements.push_back(Method);
1112 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001113 }
1114
1115 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001116 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001117 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001118 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001119 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001120
1121 // Structure containing list pointer, array and array count
1122 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001123 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001124 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001125 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001126 NextPtrTy,
1127 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001128 ObjCMethodArrayTy,
1129 NULL);
1130 // Refine next pointer type to concrete type
1131 llvm::cast<llvm::OpaqueType>(
1132 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1133 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1134
1135 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001136 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001137 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001138 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001139 MethodTypes.size()));
1140 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001141
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001142 // Create an instance of the structure
1143 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1144}
1145
1146/// Generates an IvarList. Used in construction of a objc_class.
1147llvm::Constant *CGObjCGNU::GenerateIvarList(
1148 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1149 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1150 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001151 if (IvarNames.size() == 0)
1152 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001153 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001154 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001155 PtrToInt8Ty,
1156 PtrToInt8Ty,
1157 IntTy,
1158 NULL);
1159 std::vector<llvm::Constant*> Ivars;
1160 std::vector<llvm::Constant*> Elements;
1161 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1162 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001163 Elements.push_back(IvarNames[i]);
1164 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001165 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001166 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001167 }
1168
1169 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001170 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001171 IvarNames.size());
1172
Mike Stump11289f42009-09-09 15:08:12 +00001173
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001174 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001175 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001176 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001177 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001178 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001179 ObjCIvarArrayTy,
1180 NULL);
1181
1182 // Create an instance of the structure
1183 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1184}
1185
1186/// Generate a class structure
1187llvm::Constant *CGObjCGNU::GenerateClassStructure(
1188 llvm::Constant *MetaClass,
1189 llvm::Constant *SuperClass,
1190 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001191 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001192 llvm::Constant *Version,
1193 llvm::Constant *InstanceSize,
1194 llvm::Constant *IVars,
1195 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001196 llvm::Constant *Protocols,
1197 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001198 llvm::Constant *Properties,
1199 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001200 // Set up the class structure
1201 // Note: Several of these are char*s when they should be ids. This is
1202 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001203 //
1204 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1205 // anyway; the classes will still work with the GNU runtime, they will just
1206 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001207 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001208 PtrToInt8Ty, // class_pointer
1209 PtrToInt8Ty, // super_class
1210 PtrToInt8Ty, // name
1211 LongTy, // version
1212 LongTy, // info
1213 LongTy, // instance_size
1214 IVars->getType(), // ivars
1215 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001216 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001217 PtrTy, // dtable
1218 PtrTy, // subclass_list
1219 PtrTy, // sibling_class
1220 PtrTy, // protocols
1221 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001222 // New ABI:
1223 LongTy, // abi_version
1224 IvarOffsets->getType(), // ivar_offsets
1225 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001226 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001227 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001228 // Fill in the structure
1229 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001230 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001231 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001232 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001233 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001234 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001235 if (isMeta) {
1236 llvm::TargetData td(&TheModule);
1237 Elements.push_back(llvm::ConstantInt::get(LongTy,
1238 td.getTypeSizeInBits(ClassTy)/8));
1239 } else
1240 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001241 Elements.push_back(IVars);
1242 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001243 Elements.push_back(NULLPtr);
1244 Elements.push_back(NULLPtr);
1245 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001246 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001247 Elements.push_back(NULLPtr);
1248 Elements.push_back(Zero);
1249 Elements.push_back(IvarOffsets);
1250 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001251 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001252 // This is now an externally visible symbol, so that we can speed up class
1253 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001254 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1255 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001256}
1257
1258llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1259 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1260 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001261 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001262 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001263 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1264 PtrToInt8Ty,
1265 NULL);
1266 std::vector<llvm::Constant*> Methods;
1267 std::vector<llvm::Constant*> Elements;
1268 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1269 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001270 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001271 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001272 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001273 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001274 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001275 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001276 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001277 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001278 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001279 IntTy, ObjCMethodArrayTy, NULL);
1280 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001281 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001282 Methods.push_back(Array);
1283 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1284}
Mike Stumpdd93a192009-07-31 21:31:32 +00001285
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001286// Create the protocol list structure used in classes, categories and so on
1287llvm::Constant *CGObjCGNU::GenerateProtocolList(
1288 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001289 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001290 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001291 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001292 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001293 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001294 ProtocolArrayTy,
1295 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001296 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001297 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1298 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001299 llvm::Constant *protocol = 0;
1300 llvm::StringMap<llvm::Constant*>::iterator value =
1301 ExistingProtocols.find(*iter);
1302 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001303 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001304 } else {
1305 protocol = value->getValue();
1306 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001307 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001308 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001309 Elements.push_back(Ptr);
1310 }
Owen Anderson47034e12009-07-28 18:33:04 +00001311 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001312 Elements);
1313 Elements.clear();
1314 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001315 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001316 Elements.push_back(ProtocolArray);
1317 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1318}
1319
Mike Stump11289f42009-09-09 15:08:12 +00001320llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001321 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001322 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001323 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001324 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001325 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001326}
1327
1328llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1329 const std::string &ProtocolName) {
1330 llvm::SmallVector<std::string, 0> EmptyStringVector;
1331 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1332
1333 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001334 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001335 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1336 // Protocols are objects containing lists of the methods implemented and
1337 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001338 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001339 PtrToInt8Ty,
1340 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001341 MethodList->getType(),
1342 MethodList->getType(),
1343 MethodList->getType(),
1344 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001345 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001346 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001347 // The isa pointer must be set to a magic number so the runtime knows it's
1348 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001349 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001350 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1351 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001352 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1353 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001354 Elements.push_back(MethodList);
1355 Elements.push_back(MethodList);
1356 Elements.push_back(MethodList);
1357 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001358 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001359}
1360
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001361void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1362 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001363 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001364 llvm::SmallVector<std::string, 16> Protocols;
1365 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1366 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001367 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001368 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1369 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001370 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1371 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001372 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1373 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001374 std::string TypeStr;
1375 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001376 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1377 InstanceMethodNames.push_back(
1378 MakeConstantString((*iter)->getSelector().getAsString()));
1379 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1380 } else {
1381 OptionalInstanceMethodNames.push_back(
1382 MakeConstantString((*iter)->getSelector().getAsString()));
1383 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1384 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001385 }
1386 // Collect information about class methods:
1387 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1388 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001389 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1390 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001391 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001392 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1393 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001394 std::string TypeStr;
1395 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001396 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1397 ClassMethodNames.push_back(
1398 MakeConstantString((*iter)->getSelector().getAsString()));
1399 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1400 } else {
1401 OptionalClassMethodNames.push_back(
1402 MakeConstantString((*iter)->getSelector().getAsString()));
1403 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1404 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001405 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001406
1407 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1408 llvm::Constant *InstanceMethodList =
1409 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1410 llvm::Constant *ClassMethodList =
1411 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001412 llvm::Constant *OptionalInstanceMethodList =
1413 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1414 OptionalInstanceMethodTypes);
1415 llvm::Constant *OptionalClassMethodList =
1416 GenerateProtocolMethodList(OptionalClassMethodNames,
1417 OptionalClassMethodTypes);
1418
1419 // Property metadata: name, attributes, isSynthesized, setter name, setter
1420 // types, getter name, getter types.
1421 // The isSynthesized value is always set to 0 in a protocol. It exists to
1422 // simplify the runtime library by allowing it to use the same data
1423 // structures for protocol metadata everywhere.
1424 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1425 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1426 PtrToInt8Ty, NULL);
1427 std::vector<llvm::Constant*> Properties;
1428 std::vector<llvm::Constant*> OptionalProperties;
1429
1430 // Add all of the property methods need adding to the method list and to the
1431 // property metadata list.
1432 for (ObjCContainerDecl::prop_iterator
1433 iter = PD->prop_begin(), endIter = PD->prop_end();
1434 iter != endIter ; iter++) {
1435 std::vector<llvm::Constant*> Fields;
1436 ObjCPropertyDecl *property = (*iter);
1437
1438 Fields.push_back(MakeConstantString(property->getNameAsString()));
1439 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1440 property->getPropertyAttributes()));
1441 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1442 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1443 std::string TypeStr;
1444 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1445 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1446 InstanceMethodTypes.push_back(TypeEncoding);
1447 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1448 Fields.push_back(TypeEncoding);
1449 } else {
1450 Fields.push_back(NULLPtr);
1451 Fields.push_back(NULLPtr);
1452 }
1453 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1454 std::string TypeStr;
1455 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1456 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1457 InstanceMethodTypes.push_back(TypeEncoding);
1458 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1459 Fields.push_back(TypeEncoding);
1460 } else {
1461 Fields.push_back(NULLPtr);
1462 Fields.push_back(NULLPtr);
1463 }
1464 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1465 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1466 } else {
1467 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1468 }
1469 }
1470 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1471 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1472 llvm::Constant* PropertyListInitFields[] =
1473 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1474
1475 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001476 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001477 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1478 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1479 PropertyListInit, ".objc_property_list");
1480
1481 llvm::Constant *OptionalPropertyArray =
1482 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1483 OptionalProperties.size()) , OptionalProperties);
1484 llvm::Constant* OptionalPropertyListInitFields[] = {
1485 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1486 OptionalPropertyArray };
1487
1488 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001489 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001490 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1491 OptionalPropertyListInit->getType(), false,
1492 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1493 ".objc_property_list");
1494
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001495 // Protocols are objects containing lists of the methods implemented and
1496 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001497 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001498 PtrToInt8Ty,
1499 ProtocolList->getType(),
1500 InstanceMethodList->getType(),
1501 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001502 OptionalInstanceMethodList->getType(),
1503 OptionalClassMethodList->getType(),
1504 PropertyList->getType(),
1505 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001506 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001507 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001508 // The isa pointer must be set to a magic number so the runtime knows it's
1509 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001510 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001511 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1512 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001513 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1514 Elements.push_back(ProtocolList);
1515 Elements.push_back(InstanceMethodList);
1516 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001517 Elements.push_back(OptionalInstanceMethodList);
1518 Elements.push_back(OptionalClassMethodList);
1519 Elements.push_back(PropertyList);
1520 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001521 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001522 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001523 ".objc_protocol"), IdTy);
1524}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001525void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1526 // Collect information about instance methods
1527 llvm::SmallVector<Selector, 1> MethodSels;
1528 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1529
1530 std::vector<llvm::Constant*> Elements;
1531 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1532 const std::string CategoryName = "AnotherHack";
1533 Elements.push_back(MakeConstantString(CategoryName));
1534 Elements.push_back(MakeConstantString(ClassName));
1535 // Instance method list
1536 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1537 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1538 // Class method list
1539 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1540 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1541 // Protocol list
1542 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1543 ExistingProtocols.size());
1544 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1545 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001546 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001547 ProtocolArrayTy,
1548 NULL);
1549 std::vector<llvm::Constant*> ProtocolElements;
1550 for (llvm::StringMapIterator<llvm::Constant*> iter =
1551 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1552 iter != endIter ; iter++) {
1553 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1554 PtrTy);
1555 ProtocolElements.push_back(Ptr);
1556 }
1557 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1558 ProtocolElements);
1559 ProtocolElements.clear();
1560 ProtocolElements.push_back(NULLPtr);
1561 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1562 ExistingProtocols.size()));
1563 ProtocolElements.push_back(ProtocolArray);
1564 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1565 ProtocolElements, ".objc_protocol_list"), PtrTy));
1566 Categories.push_back(llvm::ConstantExpr::getBitCast(
1567 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1568 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1569}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001570
Daniel Dunbar92992502008-08-15 22:20:32 +00001571void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001572 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1573 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001574 // Collect information about instance methods
1575 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1576 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001577 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001578 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001579 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001580 InstanceMethodSels.push_back((*iter)->getSelector());
1581 std::string TypeStr;
1582 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001583 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001584 }
1585
1586 // Collect information about class methods
1587 llvm::SmallVector<Selector, 16> ClassMethodSels;
1588 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001589 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001590 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001591 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001592 ClassMethodSels.push_back((*iter)->getSelector());
1593 std::string TypeStr;
1594 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001595 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001596 }
1597
1598 // Collect the names of referenced protocols
1599 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001600 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1601 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001602 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1603 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001604 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001605
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001606 std::vector<llvm::Constant*> Elements;
1607 Elements.push_back(MakeConstantString(CategoryName));
1608 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001609 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001610 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001611 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001612 false), PtrTy));
1613 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001614 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001615 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001616 PtrTy));
1617 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001618 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001619 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001620 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001621 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001622 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001623}
Daniel Dunbar92992502008-08-15 22:20:32 +00001624
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001625llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1626 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1627 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1628 ASTContext &Context = CGM.getContext();
1629 //
1630 // Property metadata: name, attributes, isSynthesized, setter name, setter
1631 // types, getter name, getter types.
1632 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1633 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1634 PtrToInt8Ty, NULL);
1635 std::vector<llvm::Constant*> Properties;
1636
1637
1638 // Add all of the property methods need adding to the method list and to the
1639 // property metadata list.
1640 for (ObjCImplDecl::propimpl_iterator
1641 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1642 iter != endIter ; iter++) {
1643 std::vector<llvm::Constant*> Fields;
1644 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001645 ObjCPropertyImplDecl *propertyImpl = *iter;
1646 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1647 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001648
1649 Fields.push_back(MakeConstantString(property->getNameAsString()));
1650 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1651 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001652 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001653 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001654 std::string TypeStr;
1655 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1656 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001657 if (isSynthesized) {
1658 InstanceMethodTypes.push_back(TypeEncoding);
1659 InstanceMethodSels.push_back(getter->getSelector());
1660 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001661 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1662 Fields.push_back(TypeEncoding);
1663 } else {
1664 Fields.push_back(NULLPtr);
1665 Fields.push_back(NULLPtr);
1666 }
1667 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001668 std::string TypeStr;
1669 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1670 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001671 if (isSynthesized) {
1672 InstanceMethodTypes.push_back(TypeEncoding);
1673 InstanceMethodSels.push_back(setter->getSelector());
1674 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001675 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1676 Fields.push_back(TypeEncoding);
1677 } else {
1678 Fields.push_back(NULLPtr);
1679 Fields.push_back(NULLPtr);
1680 }
1681 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1682 }
1683 llvm::ArrayType *PropertyArrayTy =
1684 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1685 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1686 Properties);
1687 llvm::Constant* PropertyListInitFields[] =
1688 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1689
1690 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001691 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001692 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1693 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1694 ".objc_property_list");
1695}
1696
Daniel Dunbar92992502008-08-15 22:20:32 +00001697void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1698 ASTContext &Context = CGM.getContext();
1699
1700 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001701 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001702 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001703 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001704 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001705 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001706 EmitClassRef(SuperClassName);
1707 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001708
1709 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001710 ObjCInterfaceDecl *ClassDecl =
1711 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001712 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001713 // Emit the symbol that is used to generate linker errors if this class is
1714 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001715 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001716 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001717 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001718 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001719 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001720 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001721 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001722 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
Daniel Dunbar12119b92009-05-03 10:46:44 +00001725 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001726 int instanceSize =
1727 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001728
1729 // Collect information about instance variables.
1730 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1731 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1732 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001733
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001734 std::vector<llvm::Constant*> IvarOffsetValues;
1735
Mike Stump11289f42009-09-09 15:08:12 +00001736 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001737 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001738 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1739 // class}. The runtime will then set this to the correct value on load.
1740 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1741 instanceSize = 0 - (instanceSize - superInstanceSize);
1742 }
David Chisnall18cf7372010-04-19 00:45:34 +00001743
1744 // Collect declared and synthesized ivars.
1745 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1746 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1747
1748 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1749 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001750 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001751 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001752 // Get the type encoding for this ivar
1753 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001754 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001755 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001756 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001757 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001758 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001759 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001760 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001761 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001762 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001763 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001764 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1765 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00001766 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001767 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001768 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001769 }
David Chisnalld7972f52011-03-23 16:36:54 +00001770 llvm::GlobalVariable *IvarOffsetArray =
1771 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1772
Daniel Dunbar92992502008-08-15 22:20:32 +00001773
1774 // Collect information about instance methods
1775 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1776 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001777 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001778 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001779 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001780 InstanceMethodSels.push_back((*iter)->getSelector());
1781 std::string TypeStr;
1782 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001783 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001784 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001785
1786 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1787 InstanceMethodTypes);
1788
Daniel Dunbar92992502008-08-15 22:20:32 +00001789
1790 // Collect information about class methods
1791 llvm::SmallVector<Selector, 16> ClassMethodSels;
1792 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001793 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001794 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001795 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001796 ClassMethodSels.push_back((*iter)->getSelector());
1797 std::string TypeStr;
1798 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001799 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001800 }
1801 // Collect the names of referenced protocols
1802 llvm::SmallVector<std::string, 16> Protocols;
1803 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1804 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1805 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001806 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001807
1808
1809
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001810 // Get the superclass pointer.
1811 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001812 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001813 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1814 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001815 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001816 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001817 // Empty vector used to construct empty method lists
1818 llvm::SmallVector<llvm::Constant*, 1> empty;
1819 // Generate the method and instance variable lists
1820 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001821 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001822 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001823 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001824 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1825 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001826 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001827 // we emit a symbol containing the offset for each ivar in the class. This
1828 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1829 // for the legacy ABI, without causing problems. The converse is also
1830 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001831
David Chisnall5778fce2009-08-31 16:41:57 +00001832 // Offset pointer for getting at the correct field in the ivar list when
1833 // setting up the alias. These are: The base address for the global, the
1834 // ivar array (second field), the ivar in this list (set for each ivar), and
1835 // the offset (third field in ivar structure)
1836 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1837 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001838 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001839 llvm::ConstantInt::get(IndexTy, 2) };
1840
David Chisnalle8431a72010-11-03 16:12:44 +00001841
1842 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1843 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00001844 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001845 + IVD->getNameAsString();
1846 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00001847 // Get the correct ivar field
1848 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1849 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00001850 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001851 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1852 if (offset) {
1853 offset->setInitializer(offsetValue);
1854 // If this is the real definition, change its linkage type so that
1855 // different modules will use this one, rather than their private
1856 // copy.
1857 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1858 } else {
1859 // Add a new alias if there isn't one already.
1860 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1861 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1862 }
1863 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001864 //Generate metaclass for class methods
1865 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001866 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001867 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001868
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001869 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001870 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001871 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001872 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001873 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001874 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1875 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001876
1877 // Resolve the class aliases, if they exist.
1878 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001879 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001880 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001881 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001882 ClassPtrAlias = 0;
1883 }
1884 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001885 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001886 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001887 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001888 MetaClassPtrAlias = 0;
1889 }
1890
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001891 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001892 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001893 Classes.push_back(ClassStruct);
1894}
1895
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001896
Mike Stump11289f42009-09-09 15:08:12 +00001897llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001898 // Only emit an ObjC load function if no Objective-C stuff has been called
1899 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00001900 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001901 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001902
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001903 // Add all referenced protocols to a category.
1904 GenerateProtocolHolderCategory();
1905
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001906 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1907 SelectorTy->getElementType());
1908 const llvm::Type *SelStructPtrTy = SelectorTy;
1909 bool isSelOpaque = false;
1910 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001911 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1912 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001913 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001914 isSelOpaque = true;
1915 }
1916
Eli Friedman412c6682008-06-01 16:00:02 +00001917 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001918 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001919 TheModule.addTypeName(".objc_id", IdTy);
1920 TheModule.addTypeName(".objc_imp", IMPTy);
1921
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001922 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001923 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001924 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001925 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001926 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001927 ConstantStrings.size() + 1);
1928 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001929
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001930 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00001931
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001932 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00001933
David Chisnall5778fce2009-08-31 16:41:57 +00001934 Elements.push_back(MakeConstantString(StringClass,
1935 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001936 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001937 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001938 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001939 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001940 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001941 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001942 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001943 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001944 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001945 Elements.clear();
1946 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001947 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001948 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001949 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001950 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001951 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001952 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001953 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001954 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001955 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001956 llvm::Type::getInt16Ty(VMContext),
1957 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001958 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001959
1960 Elements.clear();
1961 // Pointer to an array of selectors used in this module.
1962 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00001963 std::vector<llvm::GlobalAlias*> SelectorAliases;
1964 for (SelectorMap::iterator iter = SelectorTable.begin(),
1965 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
1966
1967 std::string SelNameStr = iter->first.getAsString();
1968 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
1969
1970 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
1971 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1972 e = Types.end() ; i!=e ; i++) {
1973
1974 llvm::Constant *SelectorTypeEncoding = NULLPtr;
1975 if (!i->first.empty())
1976 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
1977
1978 Elements.push_back(SelName);
1979 Elements.push_back(SelectorTypeEncoding);
1980 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1981 Elements.clear();
1982
1983 // Store the selector alias for later replacement
1984 SelectorAliases.push_back(i->second);
1985 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001986 }
David Chisnalld7972f52011-03-23 16:36:54 +00001987 unsigned SelectorCount = Selectors.size();
1988 // NULL-terminate the selector list. This should not actually be required,
1989 // because the selector list has a length field. Unfortunately, the GCC
1990 // runtime decides to ignore the length field and expects a NULL terminator,
1991 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001992 Elements.push_back(NULLPtr);
1993 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001994 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001995 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001996
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001997 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00001998 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
1999 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002000 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002001 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002002 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002003
2004 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002005 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2006
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002007 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00002008 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2009 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002010 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2011 Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002012 // If selectors are defined as an opaque type, cast the pointer to this
2013 // type.
David Chisnall76803412011-03-23 22:52:06 +00002014 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002015 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2016 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002017 }
David Chisnalld7972f52011-03-23 16:36:54 +00002018
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002019 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002020 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002021 Classes.size()));
2022 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002023 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002024 Categories.size()));
2025 // Create an array of classes, then categories, then static object instances
2026 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2027 // NULL-terminated list of static object instances (mainly constant strings)
2028 Classes.push_back(Statics);
2029 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002030 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002031 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002032 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002033 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2034
2035 // The symbol table is contained in a module which has some version-checking
2036 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00002037 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002038 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002039 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002040 // Runtime version, used for ABI compatibility checking.
2041 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002042 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002043 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002044 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00002045 td.getTypeSizeInBits(ModuleTy)/8));
David Chisnalld7972f52011-03-23 16:36:54 +00002046
2047 // The path to the source file where this module was declared
2048 SourceManager &SM = CGM.getContext().getSourceManager();
2049 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2050 std::string path =
2051 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2052 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2053
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002054 Elements.push_back(SymTab);
2055 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2056
2057 // Create the load function calling the runtime entry point with the module
2058 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002059 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002060 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002061 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2062 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002063 llvm::BasicBlock *EntryBB =
2064 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002065 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002066 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002067
2068 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002069 llvm::PointerType::getUnqual(ModuleTy));
2070 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00002071 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002072 Builder.CreateCall(Register, Module);
2073 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002074
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002075 return LoadFunction;
2076}
Daniel Dunbar92992502008-08-15 22:20:32 +00002077
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002078llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002079 const ObjCContainerDecl *CD) {
2080 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002081 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00002082 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2083 llvm::StringRef ClassName = CD->getName();
2084 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002085 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002086
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002087 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00002088 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002089 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002090 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2091 MethodName, isClassMethod);
2092
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002093 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002094 = llvm::Function::Create(MethodTy,
2095 llvm::GlobalValue::InternalLinkage,
2096 FunctionName,
2097 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002098 return Method;
2099}
2100
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002101llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002102 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002103}
2104
2105llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002106 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002107}
2108
David Chisnall168b80f2010-12-26 22:13:16 +00002109llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002110 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002111}
2112llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002113 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002114}
2115
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002116llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002117 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002118}
2119
David Chisnalld7972f52011-03-23 16:36:54 +00002120void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002121 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002122 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002123}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002124
David Chisnall3a509cd2009-12-24 02:26:34 +00002125
David Chisnalld7972f52011-03-23 16:36:54 +00002126void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002127 const ObjCAtTryStmt &S) {
2128 // Unlike the Apple non-fragile runtimes, which also uses
2129 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2130 // EH support isn't a veneer over C++ EH. Instead, exception
2131 // objects are created by __objc_exception_throw and destroyed by
2132 // the personality function; this avoids the need for bracketing
2133 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2134 // (or even _Unwind_DeleteException), but probably doesn't
2135 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002136 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002137 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002138 // exception handler.
2139 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2140 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002141}
2142
David Chisnalld7972f52011-03-23 16:36:54 +00002143void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002144 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002145 llvm::Value *ExceptionAsObject;
2146
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002147 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2148 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002149 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002150 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002151 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002152 "Unexpected rethrow outside @catch block.");
2153 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2154 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002155 ExceptionAsObject =
2156 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002157
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002158 // Note: This may have to be an invoke, if we want to support constructs like:
2159 // @try {
2160 // @throw(obj);
2161 // }
2162 // @catch(id) ...
2163 //
2164 // This is effectively turning @throw into an incredibly-expensive goto, but
2165 // it may happen as a result of inlining followed by missed optimizations, or
2166 // as a result of stupidity.
2167 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2168 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002169 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002170 CGF.Builder.CreateUnreachable();
2171 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002172 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002173 &ExceptionAsObject+1);
2174 }
2175 // Clear the insertion point to indicate we are in unreachable code.
2176 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002177}
2178
David Chisnalld7972f52011-03-23 16:36:54 +00002179llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002180 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002181 CGBuilderTy B = CGF.Builder;
2182 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2183 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002184}
2185
David Chisnalld7972f52011-03-23 16:36:54 +00002186void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002187 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002188 CGBuilderTy B = CGF.Builder;
2189 src = EnforceType(B, src, IdTy);
2190 dst = EnforceType(B, dst, PtrToIdTy);
2191 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002192}
2193
David Chisnalld7972f52011-03-23 16:36:54 +00002194void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002195 llvm::Value *src, llvm::Value *dst,
2196 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002197 CGBuilderTy B = CGF.Builder;
2198 src = EnforceType(B, src, IdTy);
2199 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002200 if (!threadlocal)
2201 B.CreateCall2(GlobalAssignFn, src, dst);
2202 else
2203 // FIXME. Add threadloca assign API
2204 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002205}
2206
David Chisnalld7972f52011-03-23 16:36:54 +00002207void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002208 llvm::Value *src, llvm::Value *dst,
2209 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002210 CGBuilderTy B = CGF.Builder;
2211 src = EnforceType(B, src, IdTy);
2212 dst = EnforceType(B, dst, PtrToIdTy);
2213 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002214}
2215
David Chisnalld7972f52011-03-23 16:36:54 +00002216void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002217 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002218 CGBuilderTy B = CGF.Builder;
2219 src = EnforceType(B, src, IdTy);
2220 dst = EnforceType(B, dst, PtrToIdTy);
2221 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002222}
2223
David Chisnalld7972f52011-03-23 16:36:54 +00002224void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002225 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002226 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002227 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002228 CGBuilderTy B = CGF.Builder;
2229 DestPtr = EnforceType(B, DestPtr, IdTy);
2230 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2231
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002232 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002233}
2234
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002235llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2236 const ObjCInterfaceDecl *ID,
2237 const ObjCIvarDecl *Ivar) {
2238 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2239 + '.' + Ivar->getNameAsString();
2240 // Emit the variable and initialize it with what we think the correct value
2241 // is. This allows code compiled with non-fragile ivars to work correctly
2242 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002243 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2244 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002245 // This will cause a run-time crash if we accidentally use it. A value of
2246 // 0 would seem more sensible, but will silently overwrite the isa pointer
2247 // causing a great deal of confusion.
2248 uint64_t Offset = -1;
2249 // We can't call ComputeIvarBaseOffset() here if we have the
2250 // implementation, because it will create an invalid ASTRecordLayout object
2251 // that we are then stuck with forever, so we only initialize the ivar
2252 // offset variable with a guess if we only have the interface. The
2253 // initializer will be reset later anyway, when we are generating the class
2254 // description.
2255 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002256 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002257 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2258
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002259 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002260 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002261 // Don't emit the guess in non-PIC code because the linker will not be able
2262 // to replace it with the real version for a library. In non-PIC code you
2263 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002264 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002265 if (CGM.getLangOptions().PICLevel) {
2266 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2267 llvm::Type::getInt32Ty(VMContext), false,
2268 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2269 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2270 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2271 IvarOffsetGV, Name);
2272 } else {
2273 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002274 llvm::Type::getInt32PtrTy(VMContext), false,
2275 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002276 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002277 }
David Chisnall5778fce2009-08-31 16:41:57 +00002278 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002279}
2280
David Chisnalld7972f52011-03-23 16:36:54 +00002281LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002282 QualType ObjectTy,
2283 llvm::Value *BaseValue,
2284 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002285 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002286 const ObjCInterfaceDecl *ID =
2287 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002288 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2289 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002290}
Mike Stumpdd93a192009-07-31 21:31:32 +00002291
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002292static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2293 const ObjCInterfaceDecl *OID,
2294 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002295 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002296 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002297 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2298 if (OIVD == Ivars[k])
2299 return OID;
2300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002302 // Otherwise check in the super class.
2303 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2304 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002305
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002306 return 0;
2307}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002308
David Chisnalld7972f52011-03-23 16:36:54 +00002309llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002310 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002311 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002312 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002313 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002314 return CGF.Builder.CreateZExtOrBitCast(
2315 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2316 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2317 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002318 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002319 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002320 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002321}
2322
David Chisnalld7972f52011-03-23 16:36:54 +00002323CGObjCRuntime *
2324clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2325 if (CGM.getLangOptions().ObjCNonFragileABI)
2326 return new CGObjCGNUstep(CGM);
2327 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002328}