blob: dff4eb7e7594c33b3279e3f09fab1dea08f75068 [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000020#include "CGException.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000021
Chris Lattnerdce14062008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000027
28#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000029#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000030#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000031#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000032#include "llvm/ADT/StringMap.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000033#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000034#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000035
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000036#include <map>
Chris Lattnere160c9b2009-01-27 05:06:01 +000037
38
Chris Lattnerdce14062008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041using llvm::dyn_cast;
42
43// The version of the runtime that this class targets. Must match the version
44// in the runtime.
45static const int RuntimeVersion = 8;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +000046static const int NonFragileRuntimeVersion = 9;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000047static const int ProtocolVersion = 2;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +000048static const int NonFragileProtocolVersion = 3;
Chris Lattner0f984262008-03-01 08:50:34 +000049
Chris Lattner0f984262008-03-01 08:50:34 +000050namespace {
Chris Lattnerdce14062008-06-26 04:19:03 +000051class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattner0f984262008-03-01 08:50:34 +000052private:
Chris Lattnerdce14062008-06-26 04:19:03 +000053 CodeGen::CodeGenModule &CGM;
Chris Lattner0f984262008-03-01 08:50:34 +000054 llvm::Module &TheModule;
Chris Lattnere160c9b2009-01-27 05:06:01 +000055 const llvm::PointerType *SelectorTy;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +000056 const llvm::IntegerType *Int8Ty;
Chris Lattnere160c9b2009-01-27 05:06:01 +000057 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +000058 const llvm::FunctionType *IMPTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000059 const llvm::PointerType *IdTy;
David Chisnallef6e0f32010-02-03 15:59:02 +000060 const llvm::PointerType *PtrToIdTy;
John McCallead608a2010-02-26 00:48:12 +000061 CanQualType ASTIdTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000062 const llvm::IntegerType *IntTy;
63 const llvm::PointerType *PtrTy;
64 const llvm::IntegerType *LongTy;
65 const llvm::PointerType *PtrToIntTy;
Daniel Dunbar5efccb12009-05-04 15:31:17 +000066 llvm::GlobalAlias *ClassPtrAlias;
67 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000068 std::vector<llvm::Constant*> Classes;
69 std::vector<llvm::Constant*> Categories;
70 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall48272a02010-01-27 12:49:23 +000071 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000072 llvm::Function *LoadFunction;
73 llvm::StringMap<llvm::Constant*> ExistingProtocols;
74 typedef std::pair<std::string, std::string> TypedSelector;
75 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
76 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnallef6e0f32010-02-03 15:59:02 +000077 // Selectors that we don't emit in GC mode
78 Selector RetainSel, ReleaseSel, AutoreleaseSel;
79 // Functions used for GC.
80 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
81 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000082 // Some zeros used for GEPs in lots of places.
83 llvm::Constant *Zeros[2];
84 llvm::Constant *NULLPtr;
Owen Andersona1cf15f2009-07-14 23:10:40 +000085 llvm::LLVMContext &VMContext;
David Chisnallc6cd5fd2010-04-28 19:33:36 +000086 /// Metadata kind used to tie method lookups to message sends.
87 unsigned msgSendMDKind;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000088private:
89 llvm::Constant *GenerateIvarList(
90 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
91 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
92 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
93 llvm::Constant *GenerateMethodList(const std::string &ClassName,
94 const std::string &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +000095 const llvm::SmallVectorImpl<Selector> &MethodSels,
96 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000097 bool isClassMethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +000098 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +000099 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
100 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
101 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000102 llvm::Constant *GenerateProtocolList(
103 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000104 // To ensure that all protocols are seen by the runtime, we add a category on
105 // a class defined in the runtime, declaring no methods, but adopting the
106 // protocols.
107 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000108 llvm::Constant *GenerateClassStructure(
109 llvm::Constant *MetaClass,
110 llvm::Constant *SuperClass,
111 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000112 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000113 llvm::Constant *Version,
114 llvm::Constant *InstanceSize,
115 llvm::Constant *IVars,
116 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000117 llvm::Constant *Protocols,
118 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000119 llvm::Constant *Properties,
120 bool isMeta=false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000121 llvm::Constant *GenerateProtocolMethodList(
122 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
123 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
124 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
125 &Name="");
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000126 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
127 prefix);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000128 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000129 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnall41d63ed2010-01-08 00:14:31 +0000130 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000131 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000132 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnall41d63ed2010-01-08 00:14:31 +0000133 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000134 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
135 const ObjCIvarDecl *Ivar);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000136 void EmitClassRef(const std::string &className);
David Chisnallef6e0f32010-02-03 15:59:02 +0000137 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
138 if (V->getType() == Ty) return V;
139 return B.CreateBitCast(V, Ty);
140 }
Chris Lattner0f984262008-03-01 08:50:34 +0000141public:
Chris Lattnerdce14062008-06-26 04:19:03 +0000142 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000143 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump1eb44332009-09-09 15:08:12 +0000144 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000145 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000146 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000147 QualType ResultType,
148 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000149 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000150 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000151 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000152 const ObjCMethodDecl *Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000153 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000154 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000155 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000156 QualType ResultType,
157 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000158 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000159 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000160 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000161 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000162 const CallArgList &CallArgs,
163 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000164 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000165 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000166 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
167 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000168 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
169 *Method);
John McCall5a180392010-07-24 00:37:23 +0000170 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000171
172 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000173 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000174 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
175 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000176 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000177 const ObjCProtocolDecl *PD);
178 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000179 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000180 virtual llvm::Function *GetPropertyGetFunction();
181 virtual llvm::Function *GetPropertySetFunction();
Fariborz Jahanian6cc59062010-04-12 18:18:10 +0000182 virtual llvm::Function *GetCopyStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000183 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
John McCallf1549f62010-07-06 01:34:17 +0000185 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
186 const ObjCAtTryStmt &S);
187 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
188 const ObjCAtSynchronizedStmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000189 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
190 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000191 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000192 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000193 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
194 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000195 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000196 llvm::Value *src, llvm::Value *dest,
197 bool threadlocal=false);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000198 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000199 llvm::Value *src, llvm::Value *dest,
200 llvm::Value *ivarOffset);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000201 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
202 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000203 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000204 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000205 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000206 llvm::Value *Size);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000207 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
208 QualType ObjectTy,
209 llvm::Value *BaseValue,
210 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000211 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000212 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000213 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000214 const ObjCIvarDecl *Ivar);
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000215 virtual llvm::Constant *GCBlockLayout(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanianc5904b42010-09-11 01:27:29 +0000216 const llvm::SmallVectorImpl<const Expr *> &) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000217 return NULLPtr;
218 }
Chris Lattner0f984262008-03-01 08:50:34 +0000219};
220} // end anonymous namespace
221
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000222
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000223/// Emits a reference to a dummy variable which is emitted with each class.
224/// This ensures that a linker error will be generated when trying to link
225/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000226void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000227 std::string symbolRef = "__objc_class_ref_" + className;
228 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000229 if (TheModule.getGlobalVariable(symbolRef))
230 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000231 std::string symbolName = "__objc_class_name_" + className;
232 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
233 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000234 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
235 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000236 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000237 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000238 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000239}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000240
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000241static std::string SymbolNameForMethod(const std::string &ClassName, const
242 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
243{
David Chisnalld3467362010-01-14 14:08:19 +0000244 std::string MethodNameColonStripped = MethodName;
245 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
246 ':', '_');
247 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
248 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000249}
David Chisnall87935a82010-05-08 20:58:05 +0000250static std::string MangleSelectorTypes(const std::string &TypeString) {
251 std::string Mangled = TypeString;
David Chisnall22b88272010-05-09 01:01:43 +0000252 // Simple mangling to avoid breaking when we mix JIT / static code.
253 // Not part of the ABI, subject to change without notice.
David Chisnall87935a82010-05-08 20:58:05 +0000254 std::replace(Mangled.begin(), Mangled.end(), '@', '_');
David Chisnall22b88272010-05-09 01:01:43 +0000255 std::replace(Mangled.begin(), Mangled.end(), ':', 'J');
256 std::replace(Mangled.begin(), Mangled.end(), '*', 'e');
257 std::replace(Mangled.begin(), Mangled.end(), '#', 'E');
258 std::replace(Mangled.begin(), Mangled.end(), ':', 'j');
259 std::replace(Mangled.begin(), Mangled.end(), '(', 'g');
260 std::replace(Mangled.begin(), Mangled.end(), ')', 'G');
261 std::replace(Mangled.begin(), Mangled.end(), '[', 'h');
262 std::replace(Mangled.begin(), Mangled.end(), ']', 'H');
David Chisnall87935a82010-05-08 20:58:05 +0000263 return Mangled;
264}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000265
Chris Lattnerdce14062008-06-26 04:19:03 +0000266CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000267 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000268 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000269
270 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
271
Chris Lattnere160c9b2009-01-27 05:06:01 +0000272 IntTy = cast<llvm::IntegerType>(
273 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
274 LongTy = cast<llvm::IntegerType>(
275 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000277 Int8Ty = llvm::Type::getInt8Ty(VMContext);
278 // C string type. Used in lots of places.
279 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
280
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000281 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000282 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000283 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000284 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000285 QualType selTy = CGM.getContext().getObjCSelType();
286 if (QualType() == selTy) {
287 SelectorTy = PtrToInt8Ty;
288 } else {
289 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
290 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000291
Owen Anderson96e0fc72009-07-29 22:16:19 +0000292 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000293 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattner391d77a2008-03-30 23:03:07 +0000295 // Object type
John McCallead608a2010-02-26 00:48:12 +0000296 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall0d13f6f2010-01-23 02:40:42 +0000297 if (QualType() == ASTIdTy) {
298 IdTy = PtrToInt8Ty;
299 } else {
300 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
301 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000302 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner391d77a2008-03-30 23:03:07 +0000304 // IMP type
305 std::vector<const llvm::Type*> IMPArgs;
306 IMPArgs.push_back(IdTy);
307 IMPArgs.push_back(SelectorTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000308 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnallef6e0f32010-02-03 15:59:02 +0000309
310 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
311 // Get selectors needed in GC mode
312 RetainSel = GetNullarySelector("retain", CGM.getContext());
313 ReleaseSel = GetNullarySelector("release", CGM.getContext());
314 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
315
316 // Get functions needed in GC mode
317
318 // id objc_assign_ivar(id, id, ptrdiff_t);
319 std::vector<const llvm::Type*> Args(1, IdTy);
320 Args.push_back(PtrToIdTy);
321 // FIXME: ptrdiff_t
322 Args.push_back(LongTy);
323 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
324 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
325 // id objc_assign_strongCast (id, id*)
326 Args.pop_back();
327 FTy = llvm::FunctionType::get(IdTy, Args, false);
328 StrongCastAssignFn =
329 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
330 // id objc_assign_global(id, id*);
331 FTy = llvm::FunctionType::get(IdTy, Args, false);
332 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
333 // id objc_assign_weak(id, id*);
334 FTy = llvm::FunctionType::get(IdTy, Args, false);
335 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
336 // id objc_read_weak(id*);
337 Args.clear();
338 Args.push_back(PtrToIdTy);
339 FTy = llvm::FunctionType::get(IdTy, Args, false);
340 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
341 // void *objc_memmove_collectable(void*, void *, size_t);
342 Args.clear();
343 Args.push_back(PtrToInt8Ty);
344 Args.push_back(PtrToInt8Ty);
345 // FIXME: size_t
346 Args.push_back(LongTy);
347 FTy = llvm::FunctionType::get(IdTy, Args, false);
348 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
349 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000350}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000351
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000352// This has to perform the lookup every time, since posing and related
353// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000354llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000355 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000356 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnall41d63ed2010-01-08 00:14:31 +0000357 // With the incompatible ABI, this will need to be replaced with a direct
358 // reference to the class symbol. For the compatible nonfragile ABI we are
359 // still performing this lookup at run time but emitting the symbol for the
360 // class externally so that we can make the switch later.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000361 EmitClassRef(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000362 ClassName = Builder.CreateStructGEP(ClassName, 0);
363
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000364 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000365 llvm::Constant *ClassLookupFn =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000366 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000367 Params,
368 true),
369 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000370 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000371}
372
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000373llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
374 bool lval) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000375 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner8e67b632008-06-26 04:37:12 +0000376 if (US == 0)
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000377 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000378 llvm::GlobalValue::PrivateLinkage,
379 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner8e67b632008-06-26 04:37:12 +0000380 NULL, &TheModule);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000381 if (lval)
382 return US;
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000383 return Builder.CreateLoad(US);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000384}
385
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000386llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000387 *Method) {
388
389 std::string SelName = Method->getSelector().getAsString();
390 std::string SelTypes;
391 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
392 // Typed selectors
393 TypedSelector Selector = TypedSelector(SelName,
394 SelTypes);
395
396 // If it's already cached, return it.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000397 if (TypedSelectors[Selector]) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000398 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000399 }
400
401 // If it isn't, cache it.
402 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000403 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000404 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000405 NULL, &TheModule);
406 TypedSelectors[Selector] = Sel;
407
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000408 return Builder.CreateLoad(Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000409}
410
John McCall5a180392010-07-24 00:37:23 +0000411llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
412 llvm_unreachable("asking for catch type for ObjC type in GNU runtime");
413 return 0;
414}
415
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000416llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
417 const std::string &Name) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000418 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000419 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000420}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000421llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
422 const std::string prefix) {
423 std::string name = prefix + Str;
424 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
425 if (!ConstStr) {
426 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
427 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
428 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
429 }
430 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
431}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000432
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000433llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000434 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000435 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson08e25242009-07-27 22:29:56 +0000436 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000437 return new llvm::GlobalVariable(TheModule, Ty, false,
438 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000439}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000440
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000441llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000442 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000443 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson7db6d832009-07-28 18:33:04 +0000444 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000445 return new llvm::GlobalVariable(TheModule, Ty, false,
Mike Stumpbb1c8602009-07-31 21:31:32 +0000446 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000447}
448
449/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000450llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000451
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000452 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000453
David Chisnall48272a02010-01-27 12:49:23 +0000454 // Look for an existing one
455 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
456 if (old != ObjCStrings.end())
457 return old->getValue();
458
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000459 std::vector<llvm::Constant*> Ivars;
460 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000461 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000462 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000463 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson47a434f2009-08-05 23:18:46 +0000464 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000465 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000466 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
467 ObjCStrings[Str] = ObjCStr;
468 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000469 return ObjCStr;
470}
471
472///Generates a message send where the super is the receiver. This is a message
473///send to self with special delivery semantics indicating which class's method
474///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000475CodeGen::RValue
476CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000477 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000478 QualType ResultType,
479 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000480 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000481 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000482 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000483 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000484 const CallArgList &CallArgs,
485 const ObjCMethodDecl *Method) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000486 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
487 if (Sel == RetainSel || Sel == AutoreleaseSel) {
488 return RValue::get(Receiver);
489 }
490 if (Sel == ReleaseSel) {
491 return RValue::get(0);
492 }
493 }
David Chisnalldb831942010-05-01 12:37:16 +0000494
495 CGBuilderTy &Builder = CGF.Builder;
496 llvm::Value *cmd = GetSelector(Builder, Sel);
497
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000498
499 CallArgList ActualArgs;
500
501 ActualArgs.push_back(
David Chisnalldb831942010-05-01 12:37:16 +0000502 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall0f436562009-08-17 16:35:33 +0000503 ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000504 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
505 CGF.getContext().getObjCSelType()));
506 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
507
508 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000509 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000510 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000511 const llvm::FunctionType *impType =
512 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000513
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000514 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000515 if (isCategoryImpl) {
516 llvm::Constant *classLookupFunction = 0;
517 std::vector<const llvm::Type*> Params;
518 Params.push_back(PtrTy);
519 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000520 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000521 IdTy, Params, true), "objc_get_meta_class");
522 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000523 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000524 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000525 }
David Chisnalldb831942010-05-01 12:37:16 +0000526 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000527 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000528 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000529 // Set up global aliases for the metaclass or class pointer if they do not
530 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +0000531 // pointers to the class and metaclass structure created for the runtime
532 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000533 // super_class pointer from either the class or metaclass structure.
534 if (IsClassMessage) {
535 if (!MetaClassPtrAlias) {
536 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
537 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
538 Class->getNameAsString(), NULL, &TheModule);
539 }
540 ReceiverClass = MetaClassPtrAlias;
541 } else {
542 if (!ClassPtrAlias) {
543 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
544 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
545 Class->getNameAsString(), NULL, &TheModule);
546 }
547 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000548 }
Chris Lattner71238f62009-04-25 23:19:45 +0000549 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000550 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +0000551 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000552 llvm::PointerType::getUnqual(
Owen Anderson47a434f2009-08-05 23:18:46 +0000553 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000554 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000555 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000556 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000557 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000558 // Construct the structure used to look up the IMP
Owen Anderson47a434f2009-08-05 23:18:46 +0000559 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
560 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +0000561 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000562
David Chisnalldb831942010-05-01 12:37:16 +0000563 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
564 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000565
566 // Get the IMP
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000567 std::vector<const llvm::Type*> Params;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000568 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000569 Params.push_back(SelectorTy);
David Chisnalldb831942010-05-01 12:37:16 +0000570
571 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
572 llvm::Value *imp;
573
574 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
575 // The lookup function returns a slot, which can be safely cached.
576 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
577 IntTy, llvm::PointerType::getUnqual(impType), NULL);
578
579 llvm::Constant *lookupFunction =
580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
581 llvm::PointerType::getUnqual(SlotTy), Params, true),
582 "objc_slot_lookup_super");
583
584 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
585 lookupArgs+2);
586 slot->setOnlyReadsMemory();
587
588 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
589 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000590 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
592 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000593 "objc_msg_lookup_super");
David Chisnalldb831942010-05-01 12:37:16 +0000594 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
595 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000596
David Chisnalldd5c98f2010-05-01 11:15:56 +0000597 llvm::Value *impMD[] = {
598 llvm::MDString::get(VMContext, Sel.getAsString()),
599 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
600 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
601 };
602 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
603
David Chisnall4b02afc2010-05-02 13:41:58 +0000604 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000605 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000606 0, &call);
607 call->setMetadata(msgSendMDKind, node);
608 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000609}
610
Mike Stump1eb44332009-09-09 15:08:12 +0000611/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000612CodeGen::RValue
613CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000614 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000615 QualType ResultType,
616 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000617 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000618 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000619 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000620 const ObjCMethodDecl *Method) {
David Chisnall664b7c72010-04-27 15:08:48 +0000621 // Strip out message sends to retain / release in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +0000622 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
623 if (Sel == RetainSel || Sel == AutoreleaseSel) {
624 return RValue::get(Receiver);
625 }
626 if (Sel == ReleaseSel) {
627 return RValue::get(0);
628 }
629 }
David Chisnall664b7c72010-04-27 15:08:48 +0000630
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000631 CGBuilderTy &Builder = CGF.Builder;
David Chisnall664b7c72010-04-27 15:08:48 +0000632
633 // If the return type is something that goes in an integer register, the
634 // runtime will handle 0 returns. For other cases, we fill in the 0 value
635 // ourselves.
636 //
637 // The language spec says the result of this kind of message send is
638 // undefined, but lots of people seem to have forgotten to read that
639 // paragraph and insist on sending messages to nil that have structure
640 // returns. With GCC, this generates a random return value (whatever happens
641 // to be on the stack / in those registers at the time) on most platforms,
642 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
643 bool isPointerSizedReturn = false;
Douglas Gregor9d3347a2010-06-16 00:35:25 +0000644 if (ResultType->isAnyPointerType() ||
645 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType())
David Chisnall664b7c72010-04-27 15:08:48 +0000646 isPointerSizedReturn = true;
647
648 llvm::BasicBlock *startBB = 0;
649 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +0000650 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +0000651
652 if (!isPointerSizedReturn) {
653 startBB = Builder.GetInsertBlock();
654 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +0000655 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +0000656
657 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
658 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +0000659 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000660 CGF.EmitBlock(messageBB);
661 }
662
David Chisnall0f436562009-08-17 16:35:33 +0000663 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000664 llvm::Value *cmd;
665 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000666 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000667 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000668 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000669 CallArgList ActualArgs;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000670
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000671 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000672 ActualArgs.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000673 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000674 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
675 CGF.getContext().getObjCSelType()));
676 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
677
678 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000679 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000680 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000681 const llvm::FunctionType *impType =
682 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000683
David Chisnall63e742b2010-05-01 12:56:56 +0000684 llvm::Value *impMD[] = {
685 llvm::MDString::get(VMContext, Sel.getAsString()),
686 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
687 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
688 };
689 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
690
691
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000692 llvm::Value *imp;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000693 // For sender-aware dispatch, we pass the sender as the third argument to a
694 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000695 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
696 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
697
698 std::vector<const llvm::Type*> Params;
699 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
700 Builder.CreateStore(Receiver, ReceiverPtr);
701 Params.push_back(ReceiverPtr->getType());
702 Params.push_back(SelectorTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000703 llvm::Value *self;
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000704
David Chisnallf69ea952010-07-21 15:28:28 +0000705 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000706 self = CGF.LoadObjCSelf();
707 } else {
Owen Anderson03e20502009-07-30 23:11:26 +0000708 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000709 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000710
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000711 Params.push_back(self->getType());
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000712
713 // The lookup function returns a slot, which can be safely cached.
714 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
715 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump1eb44332009-09-09 15:08:12 +0000716 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000717 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000718 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000719 "objc_msg_lookup_sender");
720
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000721 // The lookup function is guaranteed not to capture the receiver pointer.
722 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
723 LookupFn->setDoesNotCapture(1);
724 }
725
David Chisnall866163b2010-04-30 13:36:12 +0000726 llvm::CallInst *slot =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000727 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnall866163b2010-04-30 13:36:12 +0000728 slot->setOnlyReadsMemory();
David Chisnall63e742b2010-05-01 12:56:56 +0000729 slot->setMetadata(msgSendMDKind, node);
David Chisnall866163b2010-04-30 13:36:12 +0000730
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000731 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000732
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000733 // The lookup function may have changed the receiver, so make sure we use
734 // the new one.
David Chisnall41d0c7a2010-07-21 12:55:25 +0000735 ActualArgs[0] = std::make_pair(RValue::get(
736 Builder.CreateLoad(ReceiverPtr, true)), ASTIdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000737 } else {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000738 std::vector<const llvm::Type*> Params;
739 Params.push_back(Receiver->getType());
740 Params.push_back(SelectorTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000741 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000742 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
743 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000744 "objc_msg_lookup");
745
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000746 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnall63e742b2010-05-01 12:56:56 +0000747 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000748 }
David Chisnall4b02afc2010-05-02 13:41:58 +0000749 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000750 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000751 0, &call);
752 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +0000753
David Chisnalla54da052010-05-20 13:45:48 +0000754
David Chisnall664b7c72010-04-27 15:08:48 +0000755 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +0000756 messageBB = CGF.Builder.GetInsertBlock();
757 CGF.Builder.CreateBr(continueBB);
758 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000759 if (msgRet.isScalar()) {
760 llvm::Value *v = msgRet.getScalarVal();
761 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
762 phi->addIncoming(v, messageBB);
763 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
764 msgRet = RValue::get(phi);
765 } else if (msgRet.isAggregate()) {
766 llvm::Value *v = msgRet.getAggregateAddr();
767 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
768 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +0000769 llvm::AllocaInst *NullVal =
770 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +0000771 CGF.InitTempAlloca(NullVal,
772 llvm::Constant::getNullValue(RetTy->getElementType()));
773 phi->addIncoming(v, messageBB);
774 phi->addIncoming(NullVal, startBB);
775 msgRet = RValue::getAggregate(phi);
776 } else /* isComplex() */ {
777 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
778 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
779 phi->addIncoming(v.first, messageBB);
780 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
781 startBB);
782 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
783 phi2->addIncoming(v.second, messageBB);
784 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
785 startBB);
786 msgRet = RValue::getComplex(phi, phi2);
787 }
788 }
789 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +0000790}
791
Mike Stump1eb44332009-09-09 15:08:12 +0000792/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000793/// objc_category structures.
794llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump1eb44332009-09-09 15:08:12 +0000795 const std::string &CategoryName,
796 const llvm::SmallVectorImpl<Selector> &MethodSels,
797 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000798 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +0000799 if (MethodSels.empty())
800 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000801 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000802 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000803 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
804 PtrToInt8Ty, // Method types
Owen Anderson96e0fc72009-07-29 22:16:19 +0000805 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000806 NULL);
807 std::vector<llvm::Constant*> Methods;
808 std::vector<llvm::Constant*> Elements;
809 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
810 Elements.clear();
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000811 if (llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000812 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000813 MethodSels[i].getAsString(),
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000814 isClassMethodList))) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000815 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
816 Elements.push_back(C);
817 Elements.push_back(MethodTypes[i]);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000818 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000819 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000820 Elements.push_back(Method);
Owen Anderson08e25242009-07-27 22:29:56 +0000821 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000822 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000823 }
824
825 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000826 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000827 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000828 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000829 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000830
831 // Structure containing list pointer, array and array count
832 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Anderson8c8f69e2009-08-13 23:27:53 +0000833 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000834 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson47a434f2009-08-05 23:18:46 +0000835 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump1eb44332009-09-09 15:08:12 +0000836 NextPtrTy,
837 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000838 ObjCMethodArrayTy,
839 NULL);
840 // Refine next pointer type to concrete type
841 llvm::cast<llvm::OpaqueType>(
842 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
843 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
844
845 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +0000846 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +0000847 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +0000848 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000849 MethodTypes.size()));
850 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000852 // Create an instance of the structure
853 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
854}
855
856/// Generates an IvarList. Used in construction of a objc_class.
857llvm::Constant *CGObjCGNU::GenerateIvarList(
858 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
859 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
860 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +0000861 if (IvarNames.size() == 0)
862 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000863 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000864 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000865 PtrToInt8Ty,
866 PtrToInt8Ty,
867 IntTy,
868 NULL);
869 std::vector<llvm::Constant*> Ivars;
870 std::vector<llvm::Constant*> Elements;
871 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
872 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000873 Elements.push_back(IvarNames[i]);
874 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000875 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000876 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000877 }
878
879 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000880 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000881 IvarNames.size());
882
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000884 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000885 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +0000886 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000887 // Structure containing array and array count
Owen Anderson47a434f2009-08-05 23:18:46 +0000888 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000889 ObjCIvarArrayTy,
890 NULL);
891
892 // Create an instance of the structure
893 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
894}
895
896/// Generate a class structure
897llvm::Constant *CGObjCGNU::GenerateClassStructure(
898 llvm::Constant *MetaClass,
899 llvm::Constant *SuperClass,
900 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000901 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000902 llvm::Constant *Version,
903 llvm::Constant *InstanceSize,
904 llvm::Constant *IVars,
905 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000906 llvm::Constant *Protocols,
907 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000908 llvm::Constant *Properties,
909 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000910 // Set up the class structure
911 // Note: Several of these are char*s when they should be ids. This is
912 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000913 //
914 // Fields marked New ABI are part of the GNUstep runtime. We emit them
915 // anyway; the classes will still work with the GNU runtime, they will just
916 // be ignored.
Owen Anderson47a434f2009-08-05 23:18:46 +0000917 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000918 PtrToInt8Ty, // class_pointer
919 PtrToInt8Ty, // super_class
920 PtrToInt8Ty, // name
921 LongTy, // version
922 LongTy, // info
923 LongTy, // instance_size
924 IVars->getType(), // ivars
925 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +0000926 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000927 PtrTy, // dtable
928 PtrTy, // subclass_list
929 PtrTy, // sibling_class
930 PtrTy, // protocols
931 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000932 // New ABI:
933 LongTy, // abi_version
934 IvarOffsets->getType(), // ivar_offsets
935 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000936 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000937 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000938 // Fill in the structure
939 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +0000940 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000941 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000942 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000943 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000944 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 Elements.push_back(InstanceSize);
946 Elements.push_back(IVars);
947 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000948 Elements.push_back(NULLPtr);
949 Elements.push_back(NULLPtr);
950 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000951 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000952 Elements.push_back(NULLPtr);
953 Elements.push_back(Zero);
954 Elements.push_back(IvarOffsets);
955 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000956 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +0000957 // This is now an externally visible symbol, so that we can speed up class
958 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +0000959 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
960 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000961}
962
963llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
964 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
965 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +0000966 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000967 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000968 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
969 PtrToInt8Ty,
970 NULL);
971 std::vector<llvm::Constant*> Methods;
972 std::vector<llvm::Constant*> Elements;
973 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
974 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000975 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000976 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000977 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000978 }
Owen Anderson96e0fc72009-07-29 22:16:19 +0000979 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000980 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000981 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +0000982 Methods);
Owen Anderson47a434f2009-08-05 23:18:46 +0000983 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000984 IntTy, ObjCMethodArrayTy, NULL);
985 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000986 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000987 Methods.push_back(Array);
988 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
989}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000990
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000991// Create the protocol list structure used in classes, categories and so on
992llvm::Constant *CGObjCGNU::GenerateProtocolList(
993 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000994 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000995 Protocols.size());
Owen Anderson47a434f2009-08-05 23:18:46 +0000996 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000997 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
998 LongTy,//FIXME: Should be size_t
999 ProtocolArrayTy,
1000 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001001 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001002 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1003 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001004 llvm::Constant *protocol = 0;
1005 llvm::StringMap<llvm::Constant*>::iterator value =
1006 ExistingProtocols.find(*iter);
1007 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001008 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001009 } else {
1010 protocol = value->getValue();
1011 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001012 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001013 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001014 Elements.push_back(Ptr);
1015 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001016 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001017 Elements);
1018 Elements.clear();
1019 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001020 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001021 Elements.push_back(ProtocolArray);
1022 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1023}
1024
Mike Stump1eb44332009-09-09 15:08:12 +00001025llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001026 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001027 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001028 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001029 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001030 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001031}
1032
1033llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1034 const std::string &ProtocolName) {
1035 llvm::SmallVector<std::string, 0> EmptyStringVector;
1036 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1037
1038 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001039 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001040 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1041 // Protocols are objects containing lists of the methods implemented and
1042 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001043 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001044 PtrToInt8Ty,
1045 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001046 MethodList->getType(),
1047 MethodList->getType(),
1048 MethodList->getType(),
1049 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001050 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001051 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001052 // The isa pointer must be set to a magic number so the runtime knows it's
1053 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001054 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1055 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001056 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001057 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001058 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1059 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001060 Elements.push_back(MethodList);
1061 Elements.push_back(MethodList);
1062 Elements.push_back(MethodList);
1063 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001064 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001065}
1066
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001067void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1068 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001069 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001070 llvm::SmallVector<std::string, 16> Protocols;
1071 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1072 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001073 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001074 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1075 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001076 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1077 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001078 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1079 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001080 std::string TypeStr;
1081 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001082 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1083 InstanceMethodNames.push_back(
1084 MakeConstantString((*iter)->getSelector().getAsString()));
1085 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1086 } else {
1087 OptionalInstanceMethodNames.push_back(
1088 MakeConstantString((*iter)->getSelector().getAsString()));
1089 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1090 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001091 }
1092 // Collect information about class methods:
1093 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1094 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001095 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1096 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001097 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001098 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1099 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001100 std::string TypeStr;
1101 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001102 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1103 ClassMethodNames.push_back(
1104 MakeConstantString((*iter)->getSelector().getAsString()));
1105 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1106 } else {
1107 OptionalClassMethodNames.push_back(
1108 MakeConstantString((*iter)->getSelector().getAsString()));
1109 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1110 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001111 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001112
1113 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1114 llvm::Constant *InstanceMethodList =
1115 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1116 llvm::Constant *ClassMethodList =
1117 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001118 llvm::Constant *OptionalInstanceMethodList =
1119 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1120 OptionalInstanceMethodTypes);
1121 llvm::Constant *OptionalClassMethodList =
1122 GenerateProtocolMethodList(OptionalClassMethodNames,
1123 OptionalClassMethodTypes);
1124
1125 // Property metadata: name, attributes, isSynthesized, setter name, setter
1126 // types, getter name, getter types.
1127 // The isSynthesized value is always set to 0 in a protocol. It exists to
1128 // simplify the runtime library by allowing it to use the same data
1129 // structures for protocol metadata everywhere.
1130 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1131 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1132 PtrToInt8Ty, NULL);
1133 std::vector<llvm::Constant*> Properties;
1134 std::vector<llvm::Constant*> OptionalProperties;
1135
1136 // Add all of the property methods need adding to the method list and to the
1137 // property metadata list.
1138 for (ObjCContainerDecl::prop_iterator
1139 iter = PD->prop_begin(), endIter = PD->prop_end();
1140 iter != endIter ; iter++) {
1141 std::vector<llvm::Constant*> Fields;
1142 ObjCPropertyDecl *property = (*iter);
1143
1144 Fields.push_back(MakeConstantString(property->getNameAsString()));
1145 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1146 property->getPropertyAttributes()));
1147 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1148 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1149 std::string TypeStr;
1150 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1151 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1152 InstanceMethodTypes.push_back(TypeEncoding);
1153 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1154 Fields.push_back(TypeEncoding);
1155 } else {
1156 Fields.push_back(NULLPtr);
1157 Fields.push_back(NULLPtr);
1158 }
1159 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1160 std::string TypeStr;
1161 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1162 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1163 InstanceMethodTypes.push_back(TypeEncoding);
1164 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1165 Fields.push_back(TypeEncoding);
1166 } else {
1167 Fields.push_back(NULLPtr);
1168 Fields.push_back(NULLPtr);
1169 }
1170 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1171 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1172 } else {
1173 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1174 }
1175 }
1176 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1177 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1178 llvm::Constant* PropertyListInitFields[] =
1179 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1180
1181 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001182 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001183 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1184 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1185 PropertyListInit, ".objc_property_list");
1186
1187 llvm::Constant *OptionalPropertyArray =
1188 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1189 OptionalProperties.size()) , OptionalProperties);
1190 llvm::Constant* OptionalPropertyListInitFields[] = {
1191 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1192 OptionalPropertyArray };
1193
1194 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001195 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001196 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1197 OptionalPropertyListInit->getType(), false,
1198 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1199 ".objc_property_list");
1200
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001201 // Protocols are objects containing lists of the methods implemented and
1202 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001203 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001204 PtrToInt8Ty,
1205 ProtocolList->getType(),
1206 InstanceMethodList->getType(),
1207 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001208 OptionalInstanceMethodList->getType(),
1209 OptionalClassMethodList->getType(),
1210 PropertyList->getType(),
1211 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001212 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001213 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001214 // The isa pointer must be set to a magic number so the runtime knows it's
1215 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001216 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1217 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001218 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001219 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001220 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1221 Elements.push_back(ProtocolList);
1222 Elements.push_back(InstanceMethodList);
1223 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001224 Elements.push_back(OptionalInstanceMethodList);
1225 Elements.push_back(OptionalClassMethodList);
1226 Elements.push_back(PropertyList);
1227 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001228 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001229 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001230 ".objc_protocol"), IdTy);
1231}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001232void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1233 // Collect information about instance methods
1234 llvm::SmallVector<Selector, 1> MethodSels;
1235 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1236
1237 std::vector<llvm::Constant*> Elements;
1238 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1239 const std::string CategoryName = "AnotherHack";
1240 Elements.push_back(MakeConstantString(CategoryName));
1241 Elements.push_back(MakeConstantString(ClassName));
1242 // Instance method list
1243 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1244 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1245 // Class method list
1246 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1247 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1248 // Protocol list
1249 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1250 ExistingProtocols.size());
1251 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1252 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1253 LongTy,//FIXME: Should be size_t
1254 ProtocolArrayTy,
1255 NULL);
1256 std::vector<llvm::Constant*> ProtocolElements;
1257 for (llvm::StringMapIterator<llvm::Constant*> iter =
1258 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1259 iter != endIter ; iter++) {
1260 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1261 PtrTy);
1262 ProtocolElements.push_back(Ptr);
1263 }
1264 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1265 ProtocolElements);
1266 ProtocolElements.clear();
1267 ProtocolElements.push_back(NULLPtr);
1268 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1269 ExistingProtocols.size()));
1270 ProtocolElements.push_back(ProtocolArray);
1271 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1272 ProtocolElements, ".objc_protocol_list"), PtrTy));
1273 Categories.push_back(llvm::ConstantExpr::getBitCast(
1274 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1275 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1276}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001277
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001278void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001279 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1280 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001281 // Collect information about instance methods
1282 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1283 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001284 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001285 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001286 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001287 InstanceMethodSels.push_back((*iter)->getSelector());
1288 std::string TypeStr;
1289 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001290 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001291 }
1292
1293 // Collect information about class methods
1294 llvm::SmallVector<Selector, 16> ClassMethodSels;
1295 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001296 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001297 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001298 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001299 ClassMethodSels.push_back((*iter)->getSelector());
1300 std::string TypeStr;
1301 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001302 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001303 }
1304
1305 // Collect the names of referenced protocols
1306 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001307 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1308 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001309 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1310 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001311 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001312
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001313 std::vector<llvm::Constant*> Elements;
1314 Elements.push_back(MakeConstantString(CategoryName));
1315 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001316 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001317 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001318 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001319 false), PtrTy));
1320 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001321 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001322 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001323 PtrTy));
1324 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001325 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001326 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001327 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump1eb44332009-09-09 15:08:12 +00001328 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001329 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001330}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001331
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001332llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1333 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1334 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1335 ASTContext &Context = CGM.getContext();
1336 //
1337 // Property metadata: name, attributes, isSynthesized, setter name, setter
1338 // types, getter name, getter types.
1339 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1340 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1341 PtrToInt8Ty, NULL);
1342 std::vector<llvm::Constant*> Properties;
1343
1344
1345 // Add all of the property methods need adding to the method list and to the
1346 // property metadata list.
1347 for (ObjCImplDecl::propimpl_iterator
1348 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1349 iter != endIter ; iter++) {
1350 std::vector<llvm::Constant*> Fields;
1351 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001352 ObjCPropertyImplDecl *propertyImpl = *iter;
1353 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1354 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001355
1356 Fields.push_back(MakeConstantString(property->getNameAsString()));
1357 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1358 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001359 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001360 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001361 std::string TypeStr;
1362 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1363 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001364 if (isSynthesized) {
1365 InstanceMethodTypes.push_back(TypeEncoding);
1366 InstanceMethodSels.push_back(getter->getSelector());
1367 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001368 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1369 Fields.push_back(TypeEncoding);
1370 } else {
1371 Fields.push_back(NULLPtr);
1372 Fields.push_back(NULLPtr);
1373 }
1374 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001375 std::string TypeStr;
1376 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1377 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001378 if (isSynthesized) {
1379 InstanceMethodTypes.push_back(TypeEncoding);
1380 InstanceMethodSels.push_back(setter->getSelector());
1381 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001382 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1383 Fields.push_back(TypeEncoding);
1384 } else {
1385 Fields.push_back(NULLPtr);
1386 Fields.push_back(NULLPtr);
1387 }
1388 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1389 }
1390 llvm::ArrayType *PropertyArrayTy =
1391 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1392 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1393 Properties);
1394 llvm::Constant* PropertyListInitFields[] =
1395 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1396
1397 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001398 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001399 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1400 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1401 ".objc_property_list");
1402}
1403
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001404void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1405 ASTContext &Context = CGM.getContext();
1406
1407 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001408 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001409 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001410 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001411 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001412 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001413 EmitClassRef(SuperClassName);
1414 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001415
1416 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001417 ObjCInterfaceDecl *ClassDecl =
1418 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001419 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001420 // Emit the symbol that is used to generate linker errors if this class is
1421 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001422 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001423 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001424 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001425 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001426 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001427 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001428 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001429 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001432 // Get the size of instances.
1433 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001434
1435 // Collect information about instance variables.
1436 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1437 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1438 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001440 std::vector<llvm::Constant*> IvarOffsetValues;
1441
Mike Stump1eb44332009-09-09 15:08:12 +00001442 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001443 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1444 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1445 // class}. The runtime will then set this to the correct value on load.
1446 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1447 instanceSize = 0 - (instanceSize - superInstanceSize);
1448 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001449
1450 // Collect declared and synthesized ivars.
1451 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1452 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1453
1454 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1455 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001456 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001457 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001458 // Get the type encoding for this ivar
1459 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001460 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001461 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001462 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001463 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001464 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001465 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001466 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001467 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001468 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001469 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001470 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1471 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle0d98762010-11-03 16:12:44 +00001472 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001473 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001474 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001475 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001476 llvm::Constant *IvarOffsetArrayInit =
1477 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1478 IvarOffsetValues.size()), IvarOffsetValues);
1479 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1480 IvarOffsetArrayInit->getType(), false,
1481 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1482 ".ivar.offsets");
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001483
1484 // Collect information about instance methods
1485 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1486 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001487 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001488 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001489 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001490 InstanceMethodSels.push_back((*iter)->getSelector());
1491 std::string TypeStr;
1492 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001493 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001494 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001495
1496 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1497 InstanceMethodTypes);
1498
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001499
1500 // Collect information about class methods
1501 llvm::SmallVector<Selector, 16> ClassMethodSels;
1502 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001503 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001504 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001505 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001506 ClassMethodSels.push_back((*iter)->getSelector());
1507 std::string TypeStr;
1508 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001509 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001510 }
1511 // Collect the names of referenced protocols
1512 llvm::SmallVector<std::string, 16> Protocols;
1513 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1514 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1515 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001516 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001517
1518
1519
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001520 // Get the superclass pointer.
1521 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001522 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001523 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1524 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001525 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001526 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001527 // Empty vector used to construct empty method lists
1528 llvm::SmallVector<llvm::Constant*, 1> empty;
1529 // Generate the method and instance variable lists
1530 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001531 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001532 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001533 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001534 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1535 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001537 // we emit a symbol containing the offset for each ivar in the class. This
1538 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1539 // for the legacy ABI, without causing problems. The converse is also
1540 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001541
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001542 // Offset pointer for getting at the correct field in the ivar list when
1543 // setting up the alias. These are: The base address for the global, the
1544 // ivar array (second field), the ivar in this list (set for each ivar), and
1545 // the offset (third field in ivar structure)
1546 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1547 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001548 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001549 llvm::ConstantInt::get(IndexTy, 2) };
1550
David Chisnalle0d98762010-11-03 16:12:44 +00001551
1552 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1553 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001554 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001555 + IVD->getNameAsString();
1556 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001557 // Get the correct ivar field
1558 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1559 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001560 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001561 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1562 if (offset) {
1563 offset->setInitializer(offsetValue);
1564 // If this is the real definition, change its linkage type so that
1565 // different modules will use this one, rather than their private
1566 // copy.
1567 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1568 } else {
1569 // Add a new alias if there isn't one already.
1570 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1571 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1572 }
1573 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001574 //Generate metaclass for class methods
1575 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001576 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001577 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001578
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001579 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001580 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001581 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001582 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001583 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001584 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1585 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001586
1587 // Resolve the class aliases, if they exist.
1588 if (ClassPtrAlias) {
1589 ClassPtrAlias->setAliasee(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001590 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001591 ClassPtrAlias = 0;
1592 }
1593 if (MetaClassPtrAlias) {
1594 MetaClassPtrAlias->setAliasee(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001595 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001596 MetaClassPtrAlias = 0;
1597 }
1598
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001599 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001600 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001601 Classes.push_back(ClassStruct);
1602}
1603
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001604
Mike Stump1eb44332009-09-09 15:08:12 +00001605llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001606 // Only emit an ObjC load function if no Objective-C stuff has been called
1607 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1608 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +00001609 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001610 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00001611
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001612 // Add all referenced protocols to a category.
1613 GenerateProtocolHolderCategory();
1614
Chris Lattnere160c9b2009-01-27 05:06:01 +00001615 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1616 SelectorTy->getElementType());
1617 const llvm::Type *SelStructPtrTy = SelectorTy;
1618 bool isSelOpaque = false;
1619 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00001620 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1621 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001622 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001623 isSelOpaque = true;
1624 }
1625
Eli Friedman1b8956e2008-06-01 16:00:02 +00001626 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00001627 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00001628 TheModule.addTypeName(".objc_id", IdTy);
1629 TheModule.addTypeName(".objc_imp", IMPTy);
1630
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001631 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00001632 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001633 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00001634 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001635 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00001636 ConstantStrings.size() + 1);
1637 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001638
Daniel Dunbar1b096952009-11-29 02:38:47 +00001639 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1640 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001641 Elements.push_back(MakeConstantString(StringClass,
1642 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00001643 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00001644 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00001645 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00001646 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001647 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001648 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001649 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00001650 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001651 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00001652 Elements.clear();
1653 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001654 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00001655 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00001656 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001657 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001658 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00001659 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001660 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001661 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00001662 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00001663 llvm::Type::getInt16Ty(VMContext),
1664 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00001665 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001666
1667 Elements.clear();
1668 // Pointer to an array of selectors used in this module.
1669 std::vector<llvm::Constant*> Selectors;
1670 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1671 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1672 iter != iterEnd ; ++iter) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001673 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnalla7c5b082009-09-14 19:04:10 +00001674 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner630404b2008-06-26 04:10:42 +00001675 ".objc_sel_types"));
Owen Anderson08e25242009-07-27 22:29:56 +00001676 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001677 Elements.clear();
1678 }
1679 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1680 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +00001681 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001682 Elements.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001683 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001684 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001685 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001686 Elements.clear();
1687 }
1688 Elements.push_back(NULLPtr);
1689 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001690 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001691 Elements.clear();
1692 // Number of static selectors
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001693 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001694 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001695 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001696 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00001697 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00001698 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001699
1700 // Now that all of the static selectors exist, create pointers to them.
1701 int index = 0;
1702 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1703 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1704 iter != iterEnd; ++iter) {
1705 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001706 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001707 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001708 true, llvm::GlobalValue::LinkOnceODRLinkage,
1709 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1710 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1711 iter->first.second));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001712 // If selectors are defined as an opaque type, cast the pointer to this
1713 // type.
1714 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001715 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1716 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001717 }
David Chisnall87935a82010-05-08 20:58:05 +00001718 (*iter).second->replaceAllUsesWith(SelPtr);
1719 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001720 }
1721 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1722 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1723 iter != iterEnd; iter++) {
1724 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001725 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall87935a82010-05-08 20:58:05 +00001726 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001727 true, llvm::GlobalValue::LinkOnceODRLinkage,
1728 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1729 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001730 // If selectors are defined as an opaque type, cast the pointer to this
1731 // type.
1732 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001733 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1734 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001735 }
David Chisnall87935a82010-05-08 20:58:05 +00001736 (*iter).second->replaceAllUsesWith(SelPtr);
1737 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001738 }
1739 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00001740 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001741 Classes.size()));
1742 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00001743 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001744 Categories.size()));
1745 // Create an array of classes, then categories, then static object instances
1746 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1747 // NULL-terminated list of static object instances (mainly constant strings)
1748 Classes.push_back(Statics);
1749 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00001750 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001751 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00001752 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001753 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1754
1755 // The symbol table is contained in a module which has some version-checking
1756 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00001757 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001758 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001759 Elements.clear();
1760 // Runtime version used for compatibility checking.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001761 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001762 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001763 NonFragileRuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001764 } else {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001765 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001766 }
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00001767 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00001768 llvm::TargetData td(&TheModule);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001769 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001770 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001771 //FIXME: Should be the path to the file where this module was declared
1772 Elements.push_back(NULLPtr);
1773 Elements.push_back(SymTab);
1774 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1775
1776 // Create the load function calling the runtime entry point with the module
1777 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001778 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00001779 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001780 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1781 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00001782 llvm::BasicBlock *EntryBB =
1783 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001784 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001785 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001786
1787 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001788 llvm::PointerType::getUnqual(ModuleTy));
1789 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00001790 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001791 Builder.CreateCall(Register, Module);
1792 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001793
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001794 return LoadFunction;
1795}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001796
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001797llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00001798 const ObjCContainerDecl *CD) {
1799 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001800 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner077bf5e2008-11-24 03:33:13 +00001801 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall4c8c8e92010-03-20 19:53:29 +00001802 std::string ClassName = CD->getName();
Chris Lattner077bf5e2008-11-24 03:33:13 +00001803 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001804 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001805
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001806 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00001807 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001808 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001809 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1810 MethodName, isClassMethod);
1811
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001812 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00001813 = llvm::Function::Create(MethodTy,
1814 llvm::GlobalValue::InternalLinkage,
1815 FunctionName,
1816 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00001817 return Method;
1818}
1819
Daniel Dunbar49f66022008-09-24 03:38:44 +00001820llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001821 std::vector<const llvm::Type*> Params;
1822 const llvm::Type *BoolTy =
1823 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1824 Params.push_back(IdTy);
1825 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001826 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001827 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001828 // void objc_getProperty (id, SEL, int, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001829 const llvm::FunctionType *FTy =
1830 llvm::FunctionType::get(IdTy, Params, false);
1831 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1832 "objc_getProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001833}
1834
1835llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001836 std::vector<const llvm::Type*> Params;
1837 const llvm::Type *BoolTy =
1838 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1839 Params.push_back(IdTy);
1840 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001841 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001842 Params.push_back(IdTy);
1843 Params.push_back(BoolTy);
1844 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001845 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001846 const llvm::FunctionType *FTy =
1847 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1848 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1849 "objc_setProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001850}
1851
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00001852// FIXME. Implement this.
1853llvm::Function *CGObjCGNU::GetCopyStructFunction() {
1854 return 0;
1855}
1856
Daniel Dunbar309a4362009-07-24 07:40:24 +00001857llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1858 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1859 ASTContext &Ctx = CGM.getContext();
1860 // void objc_enumerationMutation (id)
John McCallead608a2010-02-26 00:48:12 +00001861 llvm::SmallVector<CanQualType,1> Params;
David Chisnall0f436562009-08-17 16:35:33 +00001862 Params.push_back(ASTIdTy);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001863 const llvm::FunctionType *FTy =
John McCall04a67a62010-02-05 21:31:56 +00001864 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindola264ba482010-03-30 20:24:48 +00001865 FunctionType::ExtInfo()), false);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001866 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001867}
1868
John McCall740e8072010-07-21 00:41:47 +00001869namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001870 struct CallSyncExit : EHScopeStack::Cleanup {
John McCall740e8072010-07-21 00:41:47 +00001871 llvm::Value *SyncExitFn;
1872 llvm::Value *SyncArg;
1873 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
1874 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
1875
1876 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
1877 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
1878 }
1879 };
1880}
1881
John McCallf1549f62010-07-06 01:34:17 +00001882void CGObjCGNU::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1883 const ObjCAtSynchronizedStmt &S) {
1884 std::vector<const llvm::Type*> Args(1, IdTy);
1885 llvm::FunctionType *FTy =
1886 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner5dc08672009-05-08 00:11:50 +00001887
John McCallf1549f62010-07-06 01:34:17 +00001888 // Evaluate the lock operand. This should dominate the cleanup.
1889 llvm::Value *SyncArg =
1890 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattner5dc08672009-05-08 00:11:50 +00001891
John McCallf1549f62010-07-06 01:34:17 +00001892 // Acquire the lock.
1893 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1894 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1895 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001896
John McCallf1549f62010-07-06 01:34:17 +00001897 // Register an all-paths cleanup to release the lock.
John McCall740e8072010-07-21 00:41:47 +00001898 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
John McCall1f0fca52010-07-21 07:22:38 +00001899 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExit, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001900
John McCallf1549f62010-07-06 01:34:17 +00001901 // Emit the body of the statement.
1902 CGF.EmitStmt(S.getSynchBody());
Chris Lattner5dc08672009-05-08 00:11:50 +00001903
John McCallf1549f62010-07-06 01:34:17 +00001904 // Pop the lock-release cleanup.
1905 CGF.PopCleanupBlock();
1906}
Chris Lattner5dc08672009-05-08 00:11:50 +00001907
John McCallf1549f62010-07-06 01:34:17 +00001908namespace {
1909 struct CatchHandler {
1910 const VarDecl *Variable;
1911 const Stmt *Body;
1912 llvm::BasicBlock *Block;
1913 llvm::Value *TypeInfo;
1914 };
1915}
David Chisnall0faa5162009-12-24 02:26:34 +00001916
John McCallf1549f62010-07-06 01:34:17 +00001917void CGObjCGNU::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1918 const ObjCAtTryStmt &S) {
1919 // Unlike the Apple non-fragile runtimes, which also uses
1920 // unwind-based zero cost exceptions, the GNU Objective C runtime's
1921 // EH support isn't a veneer over C++ EH. Instead, exception
1922 // objects are created by __objc_exception_throw and destroyed by
1923 // the personality function; this avoids the need for bracketing
1924 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
1925 // (or even _Unwind_DeleteException), but probably doesn't
1926 // interoperate very well with foreign exceptions.
1927
1928 // Jump destination for falling out of catch bodies.
1929 CodeGenFunction::JumpDest Cont;
1930 if (S.getNumCatchStmts())
1931 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
1932
1933 // We handle @finally statements by pushing them as a cleanup
1934 // before entering the catch.
1935 CodeGenFunction::FinallyInfo FinallyInfo;
1936 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
1937 std::vector<const llvm::Type*> Args(1, IdTy);
1938 llvm::FunctionType *FTy =
1939 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
1940 llvm::Constant *Rethrow =
1941 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1942
1943 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
1944 Rethrow);
David Chisnall0faa5162009-12-24 02:26:34 +00001945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
John McCallf1549f62010-07-06 01:34:17 +00001947 llvm::SmallVector<CatchHandler, 8> Handlers;
1948
1949 // Enter the catch, if there is one.
1950 if (S.getNumCatchStmts()) {
1951 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
1952 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
1953 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1954
1955 Handlers.push_back(CatchHandler());
1956 CatchHandler &Handler = Handlers.back();
1957 Handler.Variable = CatchDecl;
1958 Handler.Body = CatchStmt->getCatchBody();
1959 Handler.Block = CGF.createBasicBlock("catch");
1960
1961 // @catch() and @catch(id) both catch any ObjC exception.
1962 // Treat them as catch-alls.
1963 // FIXME: this is what this code was doing before, but should 'id'
1964 // really be catching foreign exceptions?
1965 if (!CatchDecl
1966 || CatchDecl->getType()->isObjCIdType()
1967 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1968
1969 Handler.TypeInfo = 0; // catch-all
1970
1971 // Don't consider any other catches.
1972 break;
1973 }
1974
1975 // All other types should be Objective-C interface pointer types.
1976 const ObjCObjectPointerType *OPT =
1977 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
1978 assert(OPT && "Invalid @catch type.");
1979 const ObjCInterfaceDecl *IDecl =
1980 OPT->getObjectType()->getInterface();
1981 assert(IDecl && "Invalid @catch type.");
1982 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
1983 }
1984
1985 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
1986 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
1987 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
1988 }
1989
1990 // Emit the try body.
1991 CGF.EmitStmt(S.getTryBody());
1992
1993 // Leave the try.
1994 if (S.getNumCatchStmts())
1995 CGF.EHStack.popCatch();
1996
1997 // Remember where we were.
1998 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1999
2000 // Emit the handlers.
2001 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2002 CatchHandler &Handler = Handlers[I];
2003 CGF.EmitBlock(Handler.Block);
2004
2005 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2006
2007 // Bind the catch parameter if it exists.
2008 if (const VarDecl *CatchParam = Handler.Variable) {
2009 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2010 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2011
John McCallb6bbcc92010-10-15 04:57:14 +00002012 CGF.EmitAutoVarDecl(*CatchParam);
John McCallf1549f62010-07-06 01:34:17 +00002013 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2014 }
2015
2016 CGF.ObjCEHValueStack.push_back(Exn);
2017 CGF.EmitStmt(Handler.Body);
2018 CGF.ObjCEHValueStack.pop_back();
2019
2020 CGF.EmitBranchThroughCleanup(Cont);
2021 }
2022
2023 // Go back to the try-statement fallthrough.
2024 CGF.Builder.restoreIP(SavedIP);
2025
2026 // Pop out of the finally.
2027 if (S.getFinallyStmt())
2028 CGF.ExitFinallyBlock(FinallyInfo);
2029
John McCallff8e1152010-07-23 21:56:41 +00002030 if (Cont.isValid()) {
2031 if (Cont.getBlock()->use_empty())
2032 delete Cont.getBlock();
2033 else
2034 CGF.EmitBlock(Cont.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00002035 }
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002036}
2037
2038void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002039 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002040 llvm::Value *ExceptionAsObject;
2041
2042 std::vector<const llvm::Type*> Args(1, IdTy);
2043 llvm::FunctionType *FTy =
Owen Anderson0032b272009-08-13 21:57:51 +00002044 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002045 llvm::Value *ThrowFn =
Chris Lattner5dc08672009-05-08 00:11:50 +00002046 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattner5dc08672009-05-08 00:11:50 +00002048 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2049 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002050 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002051 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002052 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002053 "Unexpected rethrow outside @catch block.");
2054 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2055 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002056 ExceptionAsObject =
2057 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Chris Lattner5dc08672009-05-08 00:11:50 +00002059 // Note: This may have to be an invoke, if we want to support constructs like:
2060 // @try {
2061 // @throw(obj);
2062 // }
2063 // @catch(id) ...
2064 //
2065 // This is effectively turning @throw into an incredibly-expensive goto, but
2066 // it may happen as a result of inlining followed by missed optimizations, or
2067 // as a result of stupidity.
2068 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2069 if (!UnwindBB) {
2070 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2071 CGF.Builder.CreateUnreachable();
2072 } else {
2073 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2074 &ExceptionAsObject+1);
2075 }
2076 // Clear the insertion point to indicate we are in unreachable code.
2077 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002078}
2079
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002080llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002081 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002082 CGBuilderTy B = CGF.Builder;
2083 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2084 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002085}
2086
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002087void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002088 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002089 CGBuilderTy B = CGF.Builder;
2090 src = EnforceType(B, src, IdTy);
2091 dst = EnforceType(B, dst, PtrToIdTy);
2092 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002093}
2094
Fariborz Jahanian58626502008-11-19 00:59:10 +00002095void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002096 llvm::Value *src, llvm::Value *dst,
2097 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002098 CGBuilderTy B = CGF.Builder;
2099 src = EnforceType(B, src, IdTy);
2100 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002101 if (!threadlocal)
2102 B.CreateCall2(GlobalAssignFn, src, dst);
2103 else
2104 // FIXME. Add threadloca assign API
2105 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002106}
2107
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002108void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002109 llvm::Value *src, llvm::Value *dst,
2110 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002111 CGBuilderTy B = CGF.Builder;
2112 src = EnforceType(B, src, IdTy);
2113 dst = EnforceType(B, dst, PtrToIdTy);
2114 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002115}
2116
Fariborz Jahanian58626502008-11-19 00:59:10 +00002117void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002118 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002119 CGBuilderTy B = CGF.Builder;
2120 src = EnforceType(B, src, IdTy);
2121 dst = EnforceType(B, dst, PtrToIdTy);
2122 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002123}
2124
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002125void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002126 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002127 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002128 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002129 CGBuilderTy B = CGF.Builder;
2130 DestPtr = EnforceType(B, DestPtr, IdTy);
2131 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2132
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002133 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002134}
2135
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002136llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2137 const ObjCInterfaceDecl *ID,
2138 const ObjCIvarDecl *Ivar) {
2139 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2140 + '.' + Ivar->getNameAsString();
2141 // Emit the variable and initialize it with what we think the correct value
2142 // is. This allows code compiled with non-fragile ivars to work correctly
2143 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002144 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2145 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002146 // This will cause a run-time crash if we accidentally use it. A value of
2147 // 0 would seem more sensible, but will silently overwrite the isa pointer
2148 // causing a great deal of confusion.
2149 uint64_t Offset = -1;
2150 // We can't call ComputeIvarBaseOffset() here if we have the
2151 // implementation, because it will create an invalid ASTRecordLayout object
2152 // that we are then stuck with forever, so we only initialize the ivar
2153 // offset variable with a guess if we only have the interface. The
2154 // initializer will be reset later anyway, when we are generating the class
2155 // description.
2156 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002157 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002158 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2159
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002160 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002161 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002162 // Don't emit the guess in non-PIC code because the linker will not be able
2163 // to replace it with the real version for a library. In non-PIC code you
2164 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002165 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002166 if (CGM.getLangOptions().PICLevel) {
2167 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2168 llvm::Type::getInt32Ty(VMContext), false,
2169 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2170 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2171 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2172 IvarOffsetGV, Name);
2173 } else {
2174 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002175 llvm::Type::getInt32PtrTy(VMContext), false,
2176 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002177 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002178 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002179 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002180}
2181
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002182LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2183 QualType ObjectTy,
2184 llvm::Value *BaseValue,
2185 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002186 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002187 const ObjCInterfaceDecl *ID =
2188 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002189 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2190 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002191}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002192
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002193static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2194 const ObjCInterfaceDecl *OID,
2195 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002196 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002197 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002198 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2199 if (OIVD == Ivars[k])
2200 return OID;
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002203 // Otherwise check in the super class.
2204 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2205 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002207 return 0;
2208}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002209
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002210llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002211 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002212 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002213 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002214 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002215 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2216 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002217 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002218 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002219 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002220}
2221
Mike Stumpbb1c8602009-07-31 21:31:32 +00002222CodeGen::CGObjCRuntime *
2223CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattnerdce14062008-06-26 04:19:03 +00002224 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002225}