blob: 5f19dc6e5647c083b66ca14ae5eda7a1634c64e1 [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 McCall36f893c2011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000021
Chris Lattnerdce14062008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
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;
David Chisnall8fac25d2010-12-26 22:13:16 +000065 const llvm::IntegerType *SizeTy;
66 const llvm::IntegerType *PtrDiffTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000067 const llvm::PointerType *PtrToIntTy;
David Chisnall8fac25d2010-12-26 22:13:16 +000068 const llvm::Type *BoolTy;
Daniel Dunbar5efccb12009-05-04 15:31:17 +000069 llvm::GlobalAlias *ClassPtrAlias;
70 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000071 std::vector<llvm::Constant*> Classes;
72 std::vector<llvm::Constant*> Categories;
73 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall48272a02010-01-27 12:49:23 +000074 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000075 llvm::Function *LoadFunction;
76 llvm::StringMap<llvm::Constant*> ExistingProtocols;
77 typedef std::pair<std::string, std::string> TypedSelector;
78 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
79 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnallef6e0f32010-02-03 15:59:02 +000080 // Selectors that we don't emit in GC mode
81 Selector RetainSel, ReleaseSel, AutoreleaseSel;
82 // Functions used for GC.
83 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
84 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000085 // Some zeros used for GEPs in lots of places.
86 llvm::Constant *Zeros[2];
87 llvm::Constant *NULLPtr;
Owen Andersona1cf15f2009-07-14 23:10:40 +000088 llvm::LLVMContext &VMContext;
David Chisnallc6cd5fd2010-04-28 19:33:36 +000089 /// Metadata kind used to tie method lookups to message sends.
90 unsigned msgSendMDKind;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000091private:
92 llvm::Constant *GenerateIvarList(
93 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
94 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
95 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
96 llvm::Constant *GenerateMethodList(const std::string &ClassName,
97 const std::string &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +000098 const llvm::SmallVectorImpl<Selector> &MethodSels,
99 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000100 bool isClassMethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000101 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000102 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
103 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
104 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000105 llvm::Constant *GenerateProtocolList(
106 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000107 // To ensure that all protocols are seen by the runtime, we add a category on
108 // a class defined in the runtime, declaring no methods, but adopting the
109 // protocols.
110 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000111 llvm::Constant *GenerateClassStructure(
112 llvm::Constant *MetaClass,
113 llvm::Constant *SuperClass,
114 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000115 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000116 llvm::Constant *Version,
117 llvm::Constant *InstanceSize,
118 llvm::Constant *IVars,
119 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000120 llvm::Constant *Protocols,
121 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000122 llvm::Constant *Properties,
123 bool isMeta=false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000124 llvm::Constant *GenerateProtocolMethodList(
125 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
126 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
127 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
128 &Name="");
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000129 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
130 prefix);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000131 llvm::Constant *MakeGlobal(const llvm::StructType *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);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000134 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000135 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnall41d63ed2010-01-08 00:14:31 +0000136 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000137 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
138 const ObjCIvarDecl *Ivar);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000139 void EmitClassRef(const std::string &className);
David Chisnallef6e0f32010-02-03 15:59:02 +0000140 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
141 if (V->getType() == Ty) return V;
142 return B.CreateBitCast(V, Ty);
143 }
Chris Lattner0f984262008-03-01 08:50:34 +0000144public:
Chris Lattnerdce14062008-06-26 04:19:03 +0000145 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000146 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump1eb44332009-09-09 15:08:12 +0000147 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000148 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000149 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000150 QualType ResultType,
151 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000152 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000153 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000154 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000155 const ObjCMethodDecl *Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000156 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000157 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000158 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000159 QualType ResultType,
160 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000161 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000162 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000163 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000164 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000165 const CallArgList &CallArgs,
166 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000167 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000168 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000169 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
170 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000171 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
172 *Method);
John McCall5a180392010-07-24 00:37:23 +0000173 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000174
175 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000176 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000177 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
178 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000179 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000180 const ObjCProtocolDecl *PD);
181 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000182 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000183 virtual llvm::Function *GetPropertyGetFunction();
184 virtual llvm::Function *GetPropertySetFunction();
David Chisnall8fac25d2010-12-26 22:13:16 +0000185 virtual llvm::Function *GetSetStructFunction();
186 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000187 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000188
John McCallf1549f62010-07-06 01:34:17 +0000189 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
190 const ObjCAtTryStmt &S);
191 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
192 const ObjCAtSynchronizedStmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000193 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
194 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000195 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000196 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000197 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
198 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000199 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000200 llvm::Value *src, llvm::Value *dest,
201 bool threadlocal=false);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000202 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000203 llvm::Value *src, llvm::Value *dest,
204 llvm::Value *ivarOffset);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000205 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
206 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000207 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000208 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000209 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000210 llvm::Value *Size);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000211 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
212 QualType ObjectTy,
213 llvm::Value *BaseValue,
214 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000215 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000216 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000217 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000218 const ObjCIvarDecl *Ivar);
John McCall6b5a61b2011-02-07 10:33:21 +0000219 virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
220 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000221 return NULLPtr;
222 }
Chris Lattner0f984262008-03-01 08:50:34 +0000223};
224} // end anonymous namespace
225
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000226
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000227/// Emits a reference to a dummy variable which is emitted with each class.
228/// This ensures that a linker error will be generated when trying to link
229/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000230void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000231 std::string symbolRef = "__objc_class_ref_" + className;
232 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000233 if (TheModule.getGlobalVariable(symbolRef))
234 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000235 std::string symbolName = "__objc_class_name_" + className;
236 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
237 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000238 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
239 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000240 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000241 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000242 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000243}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000244
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000245static std::string SymbolNameForMethod(const std::string &ClassName, const
246 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
247{
David Chisnalld3467362010-01-14 14:08:19 +0000248 std::string MethodNameColonStripped = MethodName;
249 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
250 ':', '_');
251 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
252 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000253}
David Chisnall87935a82010-05-08 20:58:05 +0000254static std::string MangleSelectorTypes(const std::string &TypeString) {
255 std::string Mangled = TypeString;
David Chisnall22b88272010-05-09 01:01:43 +0000256 // Simple mangling to avoid breaking when we mix JIT / static code.
257 // Not part of the ABI, subject to change without notice.
David Chisnall87935a82010-05-08 20:58:05 +0000258 std::replace(Mangled.begin(), Mangled.end(), '@', '_');
David Chisnall22b88272010-05-09 01:01:43 +0000259 std::replace(Mangled.begin(), Mangled.end(), ':', 'J');
260 std::replace(Mangled.begin(), Mangled.end(), '*', 'e');
261 std::replace(Mangled.begin(), Mangled.end(), '#', 'E');
262 std::replace(Mangled.begin(), Mangled.end(), ':', 'j');
263 std::replace(Mangled.begin(), Mangled.end(), '(', 'g');
264 std::replace(Mangled.begin(), Mangled.end(), ')', 'G');
265 std::replace(Mangled.begin(), Mangled.end(), '[', 'h');
266 std::replace(Mangled.begin(), Mangled.end(), ']', 'H');
David Chisnall87935a82010-05-08 20:58:05 +0000267 return Mangled;
268}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000269
Chris Lattnerdce14062008-06-26 04:19:03 +0000270CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000271 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000272 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000273
274 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
275
Chris Lattnere160c9b2009-01-27 05:06:01 +0000276 IntTy = cast<llvm::IntegerType>(
277 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
278 LongTy = cast<llvm::IntegerType>(
279 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000280 SizeTy = cast<llvm::IntegerType>(
281 CGM.getTypes().ConvertType(CGM.getContext().getSizeType()));
282 PtrDiffTy = cast<llvm::IntegerType>(
283 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()));
284 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000286 Int8Ty = llvm::Type::getInt8Ty(VMContext);
287 // C string type. Used in lots of places.
288 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
289
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000290 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000291 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000292 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000293 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000294 QualType selTy = CGM.getContext().getObjCSelType();
295 if (QualType() == selTy) {
296 SelectorTy = PtrToInt8Ty;
297 } else {
298 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
299 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000300
Owen Anderson96e0fc72009-07-29 22:16:19 +0000301 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000302 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner391d77a2008-03-30 23:03:07 +0000304 // Object type
John McCallead608a2010-02-26 00:48:12 +0000305 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall0d13f6f2010-01-23 02:40:42 +0000306 if (QualType() == ASTIdTy) {
307 IdTy = PtrToInt8Ty;
308 } else {
309 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
310 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000311 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner391d77a2008-03-30 23:03:07 +0000313 // IMP type
314 std::vector<const llvm::Type*> IMPArgs;
315 IMPArgs.push_back(IdTy);
316 IMPArgs.push_back(SelectorTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000317 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnallef6e0f32010-02-03 15:59:02 +0000318
319 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
320 // Get selectors needed in GC mode
321 RetainSel = GetNullarySelector("retain", CGM.getContext());
322 ReleaseSel = GetNullarySelector("release", CGM.getContext());
323 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
324
325 // Get functions needed in GC mode
326
327 // id objc_assign_ivar(id, id, ptrdiff_t);
328 std::vector<const llvm::Type*> Args(1, IdTy);
329 Args.push_back(PtrToIdTy);
David Chisnall8fac25d2010-12-26 22:13:16 +0000330 Args.push_back(PtrDiffTy);
David Chisnallef6e0f32010-02-03 15:59:02 +0000331 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
332 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
333 // id objc_assign_strongCast (id, id*)
334 Args.pop_back();
335 FTy = llvm::FunctionType::get(IdTy, Args, false);
336 StrongCastAssignFn =
337 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
338 // id objc_assign_global(id, id*);
339 FTy = llvm::FunctionType::get(IdTy, Args, false);
340 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
341 // id objc_assign_weak(id, id*);
342 FTy = llvm::FunctionType::get(IdTy, Args, false);
343 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
344 // id objc_read_weak(id*);
345 Args.clear();
346 Args.push_back(PtrToIdTy);
347 FTy = llvm::FunctionType::get(IdTy, Args, false);
348 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
349 // void *objc_memmove_collectable(void*, void *, size_t);
350 Args.clear();
351 Args.push_back(PtrToInt8Ty);
352 Args.push_back(PtrToInt8Ty);
David Chisnall8fac25d2010-12-26 22:13:16 +0000353 Args.push_back(SizeTy);
David Chisnallef6e0f32010-02-03 15:59:02 +0000354 FTy = llvm::FunctionType::get(IdTy, Args, false);
355 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
356 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000357}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000358
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000359// This has to perform the lookup every time, since posing and related
360// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000361llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000362 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000363 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnall41d63ed2010-01-08 00:14:31 +0000364 // With the incompatible ABI, this will need to be replaced with a direct
365 // reference to the class symbol. For the compatible nonfragile ABI we are
366 // still performing this lookup at run time but emitting the symbol for the
367 // class externally so that we can make the switch later.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000368 EmitClassRef(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000369 ClassName = Builder.CreateStructGEP(ClassName, 0);
370
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000371 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000372 llvm::Constant *ClassLookupFn =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000373 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000374 Params,
375 true),
376 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000377 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000378}
379
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000380llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
381 bool lval) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000382 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner8e67b632008-06-26 04:37:12 +0000383 if (US == 0)
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000384 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000385 llvm::GlobalValue::PrivateLinkage,
386 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner8e67b632008-06-26 04:37:12 +0000387 NULL, &TheModule);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000388 if (lval)
389 return US;
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000390 return Builder.CreateLoad(US);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000391}
392
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000393llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000394 *Method) {
395
396 std::string SelName = Method->getSelector().getAsString();
397 std::string SelTypes;
398 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
399 // Typed selectors
400 TypedSelector Selector = TypedSelector(SelName,
401 SelTypes);
402
403 // If it's already cached, return it.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000404 if (TypedSelectors[Selector]) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000405 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000406 }
407
408 // If it isn't, cache it.
409 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000410 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000411 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000412 NULL, &TheModule);
413 TypedSelectors[Selector] = Sel;
414
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000415 return Builder.CreateLoad(Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000416}
417
John McCall5a180392010-07-24 00:37:23 +0000418llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
419 llvm_unreachable("asking for catch type for ObjC type in GNU runtime");
420 return 0;
421}
422
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000423llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
424 const std::string &Name) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000425 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000426 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000427}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000428llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
429 const std::string prefix) {
430 std::string name = prefix + Str;
431 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
432 if (!ConstStr) {
433 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
434 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
435 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
436 }
437 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
438}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000439
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000440llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000441 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000442 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson08e25242009-07-27 22:29:56 +0000443 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000444 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall0b9c22b2010-11-09 11:21:43 +0000445 linkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000446}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000447
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000448llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000449 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000450 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson7db6d832009-07-28 18:33:04 +0000451 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000452 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall0b9c22b2010-11-09 11:21:43 +0000453 linkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000454}
455
456/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000457llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000458
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000459 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000460
David Chisnall48272a02010-01-27 12:49:23 +0000461 // Look for an existing one
462 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
463 if (old != ObjCStrings.end())
464 return old->getValue();
465
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000466 std::vector<llvm::Constant*> Ivars;
467 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000468 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000469 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000470 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson47a434f2009-08-05 23:18:46 +0000471 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000472 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000473 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
474 ObjCStrings[Str] = ObjCStr;
475 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000476 return ObjCStr;
477}
478
479///Generates a message send where the super is the receiver. This is a message
480///send to self with special delivery semantics indicating which class's method
481///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000482CodeGen::RValue
483CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000484 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000485 QualType ResultType,
486 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000487 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000488 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000489 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000490 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000491 const CallArgList &CallArgs,
492 const ObjCMethodDecl *Method) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000493 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
494 if (Sel == RetainSel || Sel == AutoreleaseSel) {
495 return RValue::get(Receiver);
496 }
497 if (Sel == ReleaseSel) {
498 return RValue::get(0);
499 }
500 }
David Chisnalldb831942010-05-01 12:37:16 +0000501
502 CGBuilderTy &Builder = CGF.Builder;
503 llvm::Value *cmd = GetSelector(Builder, Sel);
504
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000505
506 CallArgList ActualArgs;
507
508 ActualArgs.push_back(
David Chisnalldb831942010-05-01 12:37:16 +0000509 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall0f436562009-08-17 16:35:33 +0000510 ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000511 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
512 CGF.getContext().getObjCSelType()));
513 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
514
515 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000516 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000517 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000518 const llvm::FunctionType *impType =
519 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000520
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000521 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000522 if (isCategoryImpl) {
523 llvm::Constant *classLookupFunction = 0;
524 std::vector<const llvm::Type*> Params;
525 Params.push_back(PtrTy);
526 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000527 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000528 IdTy, Params, true), "objc_get_meta_class");
529 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000530 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000531 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000532 }
David Chisnalldb831942010-05-01 12:37:16 +0000533 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000534 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000535 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000536 // Set up global aliases for the metaclass or class pointer if they do not
537 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +0000538 // pointers to the class and metaclass structure created for the runtime
539 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000540 // super_class pointer from either the class or metaclass structure.
541 if (IsClassMessage) {
542 if (!MetaClassPtrAlias) {
543 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
544 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
545 Class->getNameAsString(), NULL, &TheModule);
546 }
547 ReceiverClass = MetaClassPtrAlias;
548 } else {
549 if (!ClassPtrAlias) {
550 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
551 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
552 Class->getNameAsString(), NULL, &TheModule);
553 }
554 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000555 }
Chris Lattner71238f62009-04-25 23:19:45 +0000556 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000557 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +0000558 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000559 llvm::PointerType::getUnqual(
Owen Anderson47a434f2009-08-05 23:18:46 +0000560 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000561 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000562 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000563 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000564 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000565 // Construct the structure used to look up the IMP
Owen Anderson47a434f2009-08-05 23:18:46 +0000566 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
567 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +0000568 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000569
David Chisnalldb831942010-05-01 12:37:16 +0000570 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
571 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000572
573 // Get the IMP
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000574 std::vector<const llvm::Type*> Params;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000575 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000576 Params.push_back(SelectorTy);
David Chisnalldb831942010-05-01 12:37:16 +0000577
578 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
579 llvm::Value *imp;
580
581 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
582 // The lookup function returns a slot, which can be safely cached.
583 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
584 IntTy, llvm::PointerType::getUnqual(impType), NULL);
585
586 llvm::Constant *lookupFunction =
587 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
588 llvm::PointerType::getUnqual(SlotTy), Params, true),
589 "objc_slot_lookup_super");
590
591 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
592 lookupArgs+2);
593 slot->setOnlyReadsMemory();
594
595 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
596 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000597 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000598 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
599 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000600 "objc_msg_lookup_super");
David Chisnalldb831942010-05-01 12:37:16 +0000601 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
602 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000603
David Chisnalldd5c98f2010-05-01 11:15:56 +0000604 llvm::Value *impMD[] = {
605 llvm::MDString::get(VMContext, Sel.getAsString()),
606 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
607 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
608 };
609 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
610
David Chisnall4b02afc2010-05-02 13:41:58 +0000611 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000612 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000613 0, &call);
614 call->setMetadata(msgSendMDKind, node);
615 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000616}
617
Mike Stump1eb44332009-09-09 15:08:12 +0000618/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000619CodeGen::RValue
620CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000621 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000622 QualType ResultType,
623 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000624 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000625 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000626 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000627 const ObjCMethodDecl *Method) {
David Chisnall664b7c72010-04-27 15:08:48 +0000628 // Strip out message sends to retain / release in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +0000629 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
630 if (Sel == RetainSel || Sel == AutoreleaseSel) {
631 return RValue::get(Receiver);
632 }
633 if (Sel == ReleaseSel) {
634 return RValue::get(0);
635 }
636 }
David Chisnall664b7c72010-04-27 15:08:48 +0000637
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000638 CGBuilderTy &Builder = CGF.Builder;
David Chisnall664b7c72010-04-27 15:08:48 +0000639
640 // If the return type is something that goes in an integer register, the
641 // runtime will handle 0 returns. For other cases, we fill in the 0 value
642 // ourselves.
643 //
644 // The language spec says the result of this kind of message send is
645 // undefined, but lots of people seem to have forgotten to read that
646 // paragraph and insist on sending messages to nil that have structure
647 // returns. With GCC, this generates a random return value (whatever happens
648 // to be on the stack / in those registers at the time) on most platforms,
649 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
650 bool isPointerSizedReturn = false;
Douglas Gregor9d3347a2010-06-16 00:35:25 +0000651 if (ResultType->isAnyPointerType() ||
652 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType())
David Chisnall664b7c72010-04-27 15:08:48 +0000653 isPointerSizedReturn = true;
654
655 llvm::BasicBlock *startBB = 0;
656 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +0000657 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +0000658
659 if (!isPointerSizedReturn) {
660 startBB = Builder.GetInsertBlock();
661 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +0000662 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +0000663
664 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
665 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +0000666 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000667 CGF.EmitBlock(messageBB);
668 }
669
David Chisnall0f436562009-08-17 16:35:33 +0000670 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000671 llvm::Value *cmd;
672 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000673 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000674 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000675 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000676 CallArgList ActualArgs;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000677
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000678 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000679 ActualArgs.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000680 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000681 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
682 CGF.getContext().getObjCSelType()));
683 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
684
685 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000686 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000687 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000688 const llvm::FunctionType *impType =
689 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000690
David Chisnall63e742b2010-05-01 12:56:56 +0000691 llvm::Value *impMD[] = {
692 llvm::MDString::get(VMContext, Sel.getAsString()),
693 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
694 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
695 };
696 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
697
698
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000699 llvm::Value *imp;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000700 // For sender-aware dispatch, we pass the sender as the third argument to a
701 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000702 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
703 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
704
705 std::vector<const llvm::Type*> Params;
706 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
707 Builder.CreateStore(Receiver, ReceiverPtr);
708 Params.push_back(ReceiverPtr->getType());
709 Params.push_back(SelectorTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000710 llvm::Value *self;
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000711
David Chisnallf69ea952010-07-21 15:28:28 +0000712 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000713 self = CGF.LoadObjCSelf();
714 } else {
Owen Anderson03e20502009-07-30 23:11:26 +0000715 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000716 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000717
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000718 Params.push_back(self->getType());
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000719
720 // The lookup function returns a slot, which can be safely cached.
721 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
722 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump1eb44332009-09-09 15:08:12 +0000723 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000724 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000725 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000726 "objc_msg_lookup_sender");
727
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000728 // The lookup function is guaranteed not to capture the receiver pointer.
729 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
730 LookupFn->setDoesNotCapture(1);
731 }
732
David Chisnall866163b2010-04-30 13:36:12 +0000733 llvm::CallInst *slot =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000734 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnall866163b2010-04-30 13:36:12 +0000735 slot->setOnlyReadsMemory();
David Chisnall63e742b2010-05-01 12:56:56 +0000736 slot->setMetadata(msgSendMDKind, node);
David Chisnall866163b2010-04-30 13:36:12 +0000737
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000738 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000739
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000740 // The lookup function may have changed the receiver, so make sure we use
741 // the new one.
David Chisnall41d0c7a2010-07-21 12:55:25 +0000742 ActualArgs[0] = std::make_pair(RValue::get(
743 Builder.CreateLoad(ReceiverPtr, true)), ASTIdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000744 } else {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000745 std::vector<const llvm::Type*> Params;
746 Params.push_back(Receiver->getType());
747 Params.push_back(SelectorTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000748 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000749 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
750 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000751 "objc_msg_lookup");
752
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000753 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnall63e742b2010-05-01 12:56:56 +0000754 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000755 }
David Chisnall4b02afc2010-05-02 13:41:58 +0000756 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000757 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000758 0, &call);
759 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +0000760
David Chisnalla54da052010-05-20 13:45:48 +0000761
David Chisnall664b7c72010-04-27 15:08:48 +0000762 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +0000763 messageBB = CGF.Builder.GetInsertBlock();
764 CGF.Builder.CreateBr(continueBB);
765 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000766 if (msgRet.isScalar()) {
767 llvm::Value *v = msgRet.getScalarVal();
768 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
769 phi->addIncoming(v, messageBB);
770 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
771 msgRet = RValue::get(phi);
772 } else if (msgRet.isAggregate()) {
773 llvm::Value *v = msgRet.getAggregateAddr();
774 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
775 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +0000776 llvm::AllocaInst *NullVal =
777 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +0000778 CGF.InitTempAlloca(NullVal,
779 llvm::Constant::getNullValue(RetTy->getElementType()));
780 phi->addIncoming(v, messageBB);
781 phi->addIncoming(NullVal, startBB);
782 msgRet = RValue::getAggregate(phi);
783 } else /* isComplex() */ {
784 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
785 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
786 phi->addIncoming(v.first, messageBB);
787 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
788 startBB);
789 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
790 phi2->addIncoming(v.second, messageBB);
791 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
792 startBB);
793 msgRet = RValue::getComplex(phi, phi2);
794 }
795 }
796 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +0000797}
798
Mike Stump1eb44332009-09-09 15:08:12 +0000799/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000800/// objc_category structures.
801llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump1eb44332009-09-09 15:08:12 +0000802 const std::string &CategoryName,
803 const llvm::SmallVectorImpl<Selector> &MethodSels,
804 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000805 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +0000806 if (MethodSels.empty())
807 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000808 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000809 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000810 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
811 PtrToInt8Ty, // Method types
Owen Anderson96e0fc72009-07-29 22:16:19 +0000812 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000813 NULL);
814 std::vector<llvm::Constant*> Methods;
815 std::vector<llvm::Constant*> Elements;
816 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
817 Elements.clear();
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000818 if (llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000819 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000820 MethodSels[i].getAsString(),
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000821 isClassMethodList))) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000822 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
823 Elements.push_back(C);
824 Elements.push_back(MethodTypes[i]);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000825 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000826 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000827 Elements.push_back(Method);
Owen Anderson08e25242009-07-27 22:29:56 +0000828 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000829 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000830 }
831
832 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000833 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000834 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000835 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000836 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000837
838 // Structure containing list pointer, array and array count
839 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Anderson8c8f69e2009-08-13 23:27:53 +0000840 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000841 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson47a434f2009-08-05 23:18:46 +0000842 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump1eb44332009-09-09 15:08:12 +0000843 NextPtrTy,
844 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000845 ObjCMethodArrayTy,
846 NULL);
847 // Refine next pointer type to concrete type
848 llvm::cast<llvm::OpaqueType>(
849 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
850 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
851
852 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +0000853 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +0000854 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +0000855 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000856 MethodTypes.size()));
857 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000859 // Create an instance of the structure
860 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
861}
862
863/// Generates an IvarList. Used in construction of a objc_class.
864llvm::Constant *CGObjCGNU::GenerateIvarList(
865 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
866 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
867 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +0000868 if (IvarNames.size() == 0)
869 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000870 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000871 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000872 PtrToInt8Ty,
873 PtrToInt8Ty,
874 IntTy,
875 NULL);
876 std::vector<llvm::Constant*> Ivars;
877 std::vector<llvm::Constant*> Elements;
878 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
879 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000880 Elements.push_back(IvarNames[i]);
881 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000882 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000883 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000884 }
885
886 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000887 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000888 IvarNames.size());
889
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000891 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000892 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +0000893 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000894 // Structure containing array and array count
Owen Anderson47a434f2009-08-05 23:18:46 +0000895 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000896 ObjCIvarArrayTy,
897 NULL);
898
899 // Create an instance of the structure
900 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
901}
902
903/// Generate a class structure
904llvm::Constant *CGObjCGNU::GenerateClassStructure(
905 llvm::Constant *MetaClass,
906 llvm::Constant *SuperClass,
907 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000908 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000909 llvm::Constant *Version,
910 llvm::Constant *InstanceSize,
911 llvm::Constant *IVars,
912 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000913 llvm::Constant *Protocols,
914 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000915 llvm::Constant *Properties,
916 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000917 // Set up the class structure
918 // Note: Several of these are char*s when they should be ids. This is
919 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000920 //
921 // Fields marked New ABI are part of the GNUstep runtime. We emit them
922 // anyway; the classes will still work with the GNU runtime, they will just
923 // be ignored.
Owen Anderson47a434f2009-08-05 23:18:46 +0000924 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000925 PtrToInt8Ty, // class_pointer
926 PtrToInt8Ty, // super_class
927 PtrToInt8Ty, // name
928 LongTy, // version
929 LongTy, // info
930 LongTy, // instance_size
931 IVars->getType(), // ivars
932 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +0000933 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000934 PtrTy, // dtable
935 PtrTy, // subclass_list
936 PtrTy, // sibling_class
937 PtrTy, // protocols
938 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000939 // New ABI:
940 LongTy, // abi_version
941 IvarOffsets->getType(), // ivar_offsets
942 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000943 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000944 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 // Fill in the structure
946 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +0000947 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000948 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000949 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000950 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000951 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +0000952 if (isMeta) {
953 llvm::TargetData td(&TheModule);
954 Elements.push_back(llvm::ConstantInt::get(LongTy,
955 td.getTypeSizeInBits(ClassTy)/8));
956 } else
957 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000958 Elements.push_back(IVars);
959 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000960 Elements.push_back(NULLPtr);
961 Elements.push_back(NULLPtr);
962 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000963 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000964 Elements.push_back(NULLPtr);
965 Elements.push_back(Zero);
966 Elements.push_back(IvarOffsets);
967 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000968 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +0000969 // This is now an externally visible symbol, so that we can speed up class
970 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +0000971 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
972 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000973}
974
975llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
976 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
977 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +0000978 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000979 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000980 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
981 PtrToInt8Ty,
982 NULL);
983 std::vector<llvm::Constant*> Methods;
984 std::vector<llvm::Constant*> Elements;
985 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
986 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000987 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000988 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000989 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000990 }
Owen Anderson96e0fc72009-07-29 22:16:19 +0000991 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000992 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000993 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +0000994 Methods);
Owen Anderson47a434f2009-08-05 23:18:46 +0000995 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000996 IntTy, ObjCMethodArrayTy, NULL);
997 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000998 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000999 Methods.push_back(Array);
1000 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1001}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001002
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001003// Create the protocol list structure used in classes, categories and so on
1004llvm::Constant *CGObjCGNU::GenerateProtocolList(
1005 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001006 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001007 Protocols.size());
Owen Anderson47a434f2009-08-05 23:18:46 +00001008 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001009 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001010 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001011 ProtocolArrayTy,
1012 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001013 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001014 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1015 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001016 llvm::Constant *protocol = 0;
1017 llvm::StringMap<llvm::Constant*>::iterator value =
1018 ExistingProtocols.find(*iter);
1019 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001020 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001021 } else {
1022 protocol = value->getValue();
1023 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001024 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001025 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001026 Elements.push_back(Ptr);
1027 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001028 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001029 Elements);
1030 Elements.clear();
1031 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001032 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001033 Elements.push_back(ProtocolArray);
1034 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1035}
1036
Mike Stump1eb44332009-09-09 15:08:12 +00001037llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001038 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001039 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001040 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001041 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001042 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001043}
1044
1045llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1046 const std::string &ProtocolName) {
1047 llvm::SmallVector<std::string, 0> EmptyStringVector;
1048 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1049
1050 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001051 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001052 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1053 // Protocols are objects containing lists of the methods implemented and
1054 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001055 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001056 PtrToInt8Ty,
1057 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001058 MethodList->getType(),
1059 MethodList->getType(),
1060 MethodList->getType(),
1061 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001062 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001063 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001064 // The isa pointer must be set to a magic number so the runtime knows it's
1065 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001066 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1067 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001068 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001069 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001070 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1071 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001072 Elements.push_back(MethodList);
1073 Elements.push_back(MethodList);
1074 Elements.push_back(MethodList);
1075 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001076 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001077}
1078
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001079void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1080 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001081 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001082 llvm::SmallVector<std::string, 16> Protocols;
1083 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1084 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001085 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001086 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1087 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001088 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1089 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001090 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1091 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001092 std::string TypeStr;
1093 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001094 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1095 InstanceMethodNames.push_back(
1096 MakeConstantString((*iter)->getSelector().getAsString()));
1097 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1098 } else {
1099 OptionalInstanceMethodNames.push_back(
1100 MakeConstantString((*iter)->getSelector().getAsString()));
1101 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1102 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001103 }
1104 // Collect information about class methods:
1105 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1106 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001107 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1108 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001109 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001110 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1111 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001112 std::string TypeStr;
1113 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001114 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1115 ClassMethodNames.push_back(
1116 MakeConstantString((*iter)->getSelector().getAsString()));
1117 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1118 } else {
1119 OptionalClassMethodNames.push_back(
1120 MakeConstantString((*iter)->getSelector().getAsString()));
1121 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1122 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001123 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001124
1125 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1126 llvm::Constant *InstanceMethodList =
1127 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1128 llvm::Constant *ClassMethodList =
1129 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001130 llvm::Constant *OptionalInstanceMethodList =
1131 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1132 OptionalInstanceMethodTypes);
1133 llvm::Constant *OptionalClassMethodList =
1134 GenerateProtocolMethodList(OptionalClassMethodNames,
1135 OptionalClassMethodTypes);
1136
1137 // Property metadata: name, attributes, isSynthesized, setter name, setter
1138 // types, getter name, getter types.
1139 // The isSynthesized value is always set to 0 in a protocol. It exists to
1140 // simplify the runtime library by allowing it to use the same data
1141 // structures for protocol metadata everywhere.
1142 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1143 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1144 PtrToInt8Ty, NULL);
1145 std::vector<llvm::Constant*> Properties;
1146 std::vector<llvm::Constant*> OptionalProperties;
1147
1148 // Add all of the property methods need adding to the method list and to the
1149 // property metadata list.
1150 for (ObjCContainerDecl::prop_iterator
1151 iter = PD->prop_begin(), endIter = PD->prop_end();
1152 iter != endIter ; iter++) {
1153 std::vector<llvm::Constant*> Fields;
1154 ObjCPropertyDecl *property = (*iter);
1155
1156 Fields.push_back(MakeConstantString(property->getNameAsString()));
1157 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1158 property->getPropertyAttributes()));
1159 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1160 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1161 std::string TypeStr;
1162 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1163 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1164 InstanceMethodTypes.push_back(TypeEncoding);
1165 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1166 Fields.push_back(TypeEncoding);
1167 } else {
1168 Fields.push_back(NULLPtr);
1169 Fields.push_back(NULLPtr);
1170 }
1171 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1172 std::string TypeStr;
1173 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1174 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1175 InstanceMethodTypes.push_back(TypeEncoding);
1176 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1177 Fields.push_back(TypeEncoding);
1178 } else {
1179 Fields.push_back(NULLPtr);
1180 Fields.push_back(NULLPtr);
1181 }
1182 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1183 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1184 } else {
1185 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1186 }
1187 }
1188 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1189 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1190 llvm::Constant* PropertyListInitFields[] =
1191 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1192
1193 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001194 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001195 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1196 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1197 PropertyListInit, ".objc_property_list");
1198
1199 llvm::Constant *OptionalPropertyArray =
1200 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1201 OptionalProperties.size()) , OptionalProperties);
1202 llvm::Constant* OptionalPropertyListInitFields[] = {
1203 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1204 OptionalPropertyArray };
1205
1206 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001207 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001208 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1209 OptionalPropertyListInit->getType(), false,
1210 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1211 ".objc_property_list");
1212
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001213 // Protocols are objects containing lists of the methods implemented and
1214 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001215 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001216 PtrToInt8Ty,
1217 ProtocolList->getType(),
1218 InstanceMethodList->getType(),
1219 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001220 OptionalInstanceMethodList->getType(),
1221 OptionalClassMethodList->getType(),
1222 PropertyList->getType(),
1223 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001224 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001225 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001226 // The isa pointer must be set to a magic number so the runtime knows it's
1227 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001228 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1229 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001230 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001231 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001232 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1233 Elements.push_back(ProtocolList);
1234 Elements.push_back(InstanceMethodList);
1235 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001236 Elements.push_back(OptionalInstanceMethodList);
1237 Elements.push_back(OptionalClassMethodList);
1238 Elements.push_back(PropertyList);
1239 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001240 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001241 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001242 ".objc_protocol"), IdTy);
1243}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001244void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1245 // Collect information about instance methods
1246 llvm::SmallVector<Selector, 1> MethodSels;
1247 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1248
1249 std::vector<llvm::Constant*> Elements;
1250 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1251 const std::string CategoryName = "AnotherHack";
1252 Elements.push_back(MakeConstantString(CategoryName));
1253 Elements.push_back(MakeConstantString(ClassName));
1254 // Instance method list
1255 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1256 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1257 // Class method list
1258 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1259 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1260 // Protocol list
1261 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1262 ExistingProtocols.size());
1263 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1264 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001265 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001266 ProtocolArrayTy,
1267 NULL);
1268 std::vector<llvm::Constant*> ProtocolElements;
1269 for (llvm::StringMapIterator<llvm::Constant*> iter =
1270 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1271 iter != endIter ; iter++) {
1272 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1273 PtrTy);
1274 ProtocolElements.push_back(Ptr);
1275 }
1276 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1277 ProtocolElements);
1278 ProtocolElements.clear();
1279 ProtocolElements.push_back(NULLPtr);
1280 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1281 ExistingProtocols.size()));
1282 ProtocolElements.push_back(ProtocolArray);
1283 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1284 ProtocolElements, ".objc_protocol_list"), PtrTy));
1285 Categories.push_back(llvm::ConstantExpr::getBitCast(
1286 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1287 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1288}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001289
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001290void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001291 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1292 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001293 // Collect information about instance methods
1294 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1295 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001296 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001297 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001298 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001299 InstanceMethodSels.push_back((*iter)->getSelector());
1300 std::string TypeStr;
1301 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001302 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001303 }
1304
1305 // Collect information about class methods
1306 llvm::SmallVector<Selector, 16> ClassMethodSels;
1307 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001308 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001309 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001310 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001311 ClassMethodSels.push_back((*iter)->getSelector());
1312 std::string TypeStr;
1313 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001314 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001315 }
1316
1317 // Collect the names of referenced protocols
1318 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001319 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1320 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001321 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1322 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001323 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001324
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001325 std::vector<llvm::Constant*> Elements;
1326 Elements.push_back(MakeConstantString(CategoryName));
1327 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001328 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001329 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001330 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001331 false), PtrTy));
1332 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001333 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001334 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001335 PtrTy));
1336 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001337 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001338 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001339 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump1eb44332009-09-09 15:08:12 +00001340 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001341 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001342}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001343
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001344llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1345 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1346 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1347 ASTContext &Context = CGM.getContext();
1348 //
1349 // Property metadata: name, attributes, isSynthesized, setter name, setter
1350 // types, getter name, getter types.
1351 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1352 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1353 PtrToInt8Ty, NULL);
1354 std::vector<llvm::Constant*> Properties;
1355
1356
1357 // Add all of the property methods need adding to the method list and to the
1358 // property metadata list.
1359 for (ObjCImplDecl::propimpl_iterator
1360 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1361 iter != endIter ; iter++) {
1362 std::vector<llvm::Constant*> Fields;
1363 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001364 ObjCPropertyImplDecl *propertyImpl = *iter;
1365 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1366 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001367
1368 Fields.push_back(MakeConstantString(property->getNameAsString()));
1369 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1370 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001371 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001372 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001373 std::string TypeStr;
1374 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1375 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001376 if (isSynthesized) {
1377 InstanceMethodTypes.push_back(TypeEncoding);
1378 InstanceMethodSels.push_back(getter->getSelector());
1379 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001380 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1381 Fields.push_back(TypeEncoding);
1382 } else {
1383 Fields.push_back(NULLPtr);
1384 Fields.push_back(NULLPtr);
1385 }
1386 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001387 std::string TypeStr;
1388 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1389 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001390 if (isSynthesized) {
1391 InstanceMethodTypes.push_back(TypeEncoding);
1392 InstanceMethodSels.push_back(setter->getSelector());
1393 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001394 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1395 Fields.push_back(TypeEncoding);
1396 } else {
1397 Fields.push_back(NULLPtr);
1398 Fields.push_back(NULLPtr);
1399 }
1400 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1401 }
1402 llvm::ArrayType *PropertyArrayTy =
1403 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1404 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1405 Properties);
1406 llvm::Constant* PropertyListInitFields[] =
1407 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1408
1409 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001410 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001411 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1412 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1413 ".objc_property_list");
1414}
1415
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001416void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1417 ASTContext &Context = CGM.getContext();
1418
1419 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001420 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001421 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001422 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001423 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001424 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001425 EmitClassRef(SuperClassName);
1426 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001427
1428 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001429 ObjCInterfaceDecl *ClassDecl =
1430 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001431 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001432 // Emit the symbol that is used to generate linker errors if this class is
1433 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001434 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001435 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001436 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001437 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001438 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001439 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001440 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001441 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001444 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001445 int instanceSize =
1446 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001447
1448 // Collect information about instance variables.
1449 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1450 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1451 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001453 std::vector<llvm::Constant*> IvarOffsetValues;
1454
Mike Stump1eb44332009-09-09 15:08:12 +00001455 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001456 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001457 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1458 // class}. The runtime will then set this to the correct value on load.
1459 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1460 instanceSize = 0 - (instanceSize - superInstanceSize);
1461 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001462
1463 // Collect declared and synthesized ivars.
1464 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1465 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1466
1467 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1468 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001469 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001470 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001471 // Get the type encoding for this ivar
1472 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001473 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001474 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001475 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001476 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001477 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001478 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001479 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001480 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001481 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001482 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001483 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1484 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle0d98762010-11-03 16:12:44 +00001485 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001486 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001487 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001488 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001489 llvm::Constant *IvarOffsetArrayInit =
1490 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1491 IvarOffsetValues.size()), IvarOffsetValues);
1492 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1493 IvarOffsetArrayInit->getType(), false,
1494 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1495 ".ivar.offsets");
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001496
1497 // Collect information about instance methods
1498 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1499 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001500 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001501 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001502 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001503 InstanceMethodSels.push_back((*iter)->getSelector());
1504 std::string TypeStr;
1505 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001506 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001507 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001508
1509 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1510 InstanceMethodTypes);
1511
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001512
1513 // Collect information about class methods
1514 llvm::SmallVector<Selector, 16> ClassMethodSels;
1515 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001516 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001517 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001518 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001519 ClassMethodSels.push_back((*iter)->getSelector());
1520 std::string TypeStr;
1521 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001522 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001523 }
1524 // Collect the names of referenced protocols
1525 llvm::SmallVector<std::string, 16> Protocols;
1526 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1527 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1528 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001529 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001530
1531
1532
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001533 // Get the superclass pointer.
1534 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001535 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001536 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1537 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001538 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001539 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001540 // Empty vector used to construct empty method lists
1541 llvm::SmallVector<llvm::Constant*, 1> empty;
1542 // Generate the method and instance variable lists
1543 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001544 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001545 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001546 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001547 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1548 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001549 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001550 // we emit a symbol containing the offset for each ivar in the class. This
1551 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1552 // for the legacy ABI, without causing problems. The converse is also
1553 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001554
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001555 // Offset pointer for getting at the correct field in the ivar list when
1556 // setting up the alias. These are: The base address for the global, the
1557 // ivar array (second field), the ivar in this list (set for each ivar), and
1558 // the offset (third field in ivar structure)
1559 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1560 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001561 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001562 llvm::ConstantInt::get(IndexTy, 2) };
1563
David Chisnalle0d98762010-11-03 16:12:44 +00001564
1565 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1566 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001567 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001568 + IVD->getNameAsString();
1569 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001570 // Get the correct ivar field
1571 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1572 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001573 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001574 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1575 if (offset) {
1576 offset->setInitializer(offsetValue);
1577 // If this is the real definition, change its linkage type so that
1578 // different modules will use this one, rather than their private
1579 // copy.
1580 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1581 } else {
1582 // Add a new alias if there isn't one already.
1583 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1584 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1585 }
1586 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001587 //Generate metaclass for class methods
1588 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001589 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001590 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001591
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001592 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001593 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001594 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001595 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001596 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001597 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1598 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001599
1600 // Resolve the class aliases, if they exist.
1601 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001602 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001603 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001604 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001605 ClassPtrAlias = 0;
1606 }
1607 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001608 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001609 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001610 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001611 MetaClassPtrAlias = 0;
1612 }
1613
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001614 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001615 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001616 Classes.push_back(ClassStruct);
1617}
1618
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001619
Mike Stump1eb44332009-09-09 15:08:12 +00001620llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001621 // Only emit an ObjC load function if no Objective-C stuff has been called
1622 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1623 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +00001624 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001625 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00001626
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001627 // Add all referenced protocols to a category.
1628 GenerateProtocolHolderCategory();
1629
Chris Lattnere160c9b2009-01-27 05:06:01 +00001630 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1631 SelectorTy->getElementType());
1632 const llvm::Type *SelStructPtrTy = SelectorTy;
1633 bool isSelOpaque = false;
1634 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00001635 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1636 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001637 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001638 isSelOpaque = true;
1639 }
1640
Eli Friedman1b8956e2008-06-01 16:00:02 +00001641 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00001642 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00001643 TheModule.addTypeName(".objc_id", IdTy);
1644 TheModule.addTypeName(".objc_imp", IMPTy);
1645
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001646 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00001647 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001648 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00001649 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001650 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00001651 ConstantStrings.size() + 1);
1652 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001653
Daniel Dunbar1b096952009-11-29 02:38:47 +00001654 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1655 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001656 Elements.push_back(MakeConstantString(StringClass,
1657 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00001658 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00001659 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00001660 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00001661 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001662 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001663 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001664 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00001665 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001666 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00001667 Elements.clear();
1668 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001669 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00001670 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00001671 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001672 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001673 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00001674 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001675 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001676 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00001677 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00001678 llvm::Type::getInt16Ty(VMContext),
1679 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00001680 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001681
1682 Elements.clear();
1683 // Pointer to an array of selectors used in this module.
1684 std::vector<llvm::Constant*> Selectors;
1685 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1686 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1687 iter != iterEnd ; ++iter) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001688 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnalla7c5b082009-09-14 19:04:10 +00001689 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner630404b2008-06-26 04:10:42 +00001690 ".objc_sel_types"));
Owen Anderson08e25242009-07-27 22:29:56 +00001691 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001692 Elements.clear();
1693 }
1694 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1695 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +00001696 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001697 Elements.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001698 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001699 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001700 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001701 Elements.clear();
1702 }
1703 Elements.push_back(NULLPtr);
1704 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001705 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001706 Elements.clear();
1707 // Number of static selectors
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001708 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001709 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001710 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001711 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00001712 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00001713 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001714
1715 // Now that all of the static selectors exist, create pointers to them.
1716 int index = 0;
1717 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1718 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1719 iter != iterEnd; ++iter) {
1720 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001721 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001722 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001723 true, llvm::GlobalValue::LinkOnceODRLinkage,
1724 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1725 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1726 iter->first.second));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001727 // If selectors are defined as an opaque type, cast the pointer to this
1728 // type.
1729 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001730 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1731 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001732 }
David Chisnall87935a82010-05-08 20:58:05 +00001733 (*iter).second->replaceAllUsesWith(SelPtr);
1734 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001735 }
1736 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1737 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1738 iter != iterEnd; iter++) {
1739 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001740 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall87935a82010-05-08 20:58:05 +00001741 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001742 true, llvm::GlobalValue::LinkOnceODRLinkage,
1743 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1744 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001745 // If selectors are defined as an opaque type, cast the pointer to this
1746 // type.
1747 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001748 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1749 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001750 }
David Chisnall87935a82010-05-08 20:58:05 +00001751 (*iter).second->replaceAllUsesWith(SelPtr);
1752 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001753 }
1754 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00001755 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001756 Classes.size()));
1757 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00001758 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001759 Categories.size()));
1760 // Create an array of classes, then categories, then static object instances
1761 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1762 // NULL-terminated list of static object instances (mainly constant strings)
1763 Classes.push_back(Statics);
1764 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00001765 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001766 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00001767 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001768 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1769
1770 // The symbol table is contained in a module which has some version-checking
1771 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00001772 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001773 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001774 Elements.clear();
1775 // Runtime version used for compatibility checking.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001776 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001777 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001778 NonFragileRuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001779 } else {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001780 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001781 }
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00001782 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00001783 llvm::TargetData td(&TheModule);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001784 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001785 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001786 //FIXME: Should be the path to the file where this module was declared
1787 Elements.push_back(NULLPtr);
1788 Elements.push_back(SymTab);
1789 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1790
1791 // Create the load function calling the runtime entry point with the module
1792 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001793 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00001794 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001795 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1796 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00001797 llvm::BasicBlock *EntryBB =
1798 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001799 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001800 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001801
1802 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001803 llvm::PointerType::getUnqual(ModuleTy));
1804 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00001805 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001806 Builder.CreateCall(Register, Module);
1807 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001808
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001809 return LoadFunction;
1810}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001811
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001812llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00001813 const ObjCContainerDecl *CD) {
1814 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001815 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner077bf5e2008-11-24 03:33:13 +00001816 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall4c8c8e92010-03-20 19:53:29 +00001817 std::string ClassName = CD->getName();
Chris Lattner077bf5e2008-11-24 03:33:13 +00001818 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001819 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001820
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001821 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00001822 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001823 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001824 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1825 MethodName, isClassMethod);
1826
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001827 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00001828 = llvm::Function::Create(MethodTy,
1829 llvm::GlobalValue::InternalLinkage,
1830 FunctionName,
1831 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00001832 return Method;
1833}
1834
Daniel Dunbar49f66022008-09-24 03:38:44 +00001835llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001836 std::vector<const llvm::Type*> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001837 Params.push_back(IdTy);
1838 Params.push_back(SelectorTy);
David Chisnalle9c58162011-02-23 14:05:31 +00001839 Params.push_back(SizeTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001840 Params.push_back(BoolTy);
David Chisnalle9c58162011-02-23 14:05:31 +00001841 // void objc_getProperty (id, SEL, ptrdiff_t, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001842 const llvm::FunctionType *FTy =
1843 llvm::FunctionType::get(IdTy, Params, false);
1844 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1845 "objc_getProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001846}
1847
1848llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001849 std::vector<const llvm::Type*> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001850 Params.push_back(IdTy);
1851 Params.push_back(SelectorTy);
David Chisnalle9c58162011-02-23 14:05:31 +00001852 Params.push_back(SizeTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001853 Params.push_back(IdTy);
1854 Params.push_back(BoolTy);
1855 Params.push_back(BoolTy);
David Chisnalle9c58162011-02-23 14:05:31 +00001856 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001857 const llvm::FunctionType *FTy =
1858 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1859 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1860 "objc_setProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001861}
1862
David Chisnall8fac25d2010-12-26 22:13:16 +00001863llvm::Function *CGObjCGNU::GetGetStructFunction() {
1864 std::vector<const llvm::Type*> Params;
1865 Params.push_back(PtrTy);
1866 Params.push_back(PtrTy);
1867 Params.push_back(PtrDiffTy);
1868 Params.push_back(BoolTy);
1869 Params.push_back(BoolTy);
1870 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL)
1871 const llvm::FunctionType *FTy =
1872 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1873 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1874 "objc_getPropertyStruct"));
1875}
1876llvm::Function *CGObjCGNU::GetSetStructFunction() {
1877 std::vector<const llvm::Type*> Params;
1878 Params.push_back(PtrTy);
1879 Params.push_back(PtrTy);
1880 Params.push_back(PtrDiffTy);
1881 Params.push_back(BoolTy);
1882 Params.push_back(BoolTy);
1883 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL)
1884 const llvm::FunctionType *FTy =
1885 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1886 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1887 "objc_setPropertyStruct"));
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00001888}
1889
Daniel Dunbar309a4362009-07-24 07:40:24 +00001890llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1891 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1892 ASTContext &Ctx = CGM.getContext();
1893 // void objc_enumerationMutation (id)
John McCallead608a2010-02-26 00:48:12 +00001894 llvm::SmallVector<CanQualType,1> Params;
David Chisnall0f436562009-08-17 16:35:33 +00001895 Params.push_back(ASTIdTy);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001896 const llvm::FunctionType *FTy =
John McCall04a67a62010-02-05 21:31:56 +00001897 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindola264ba482010-03-30 20:24:48 +00001898 FunctionType::ExtInfo()), false);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001899 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001900}
1901
John McCall740e8072010-07-21 00:41:47 +00001902namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001903 struct CallSyncExit : EHScopeStack::Cleanup {
John McCall740e8072010-07-21 00:41:47 +00001904 llvm::Value *SyncExitFn;
1905 llvm::Value *SyncArg;
1906 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
1907 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
1908
1909 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
1910 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
1911 }
1912 };
1913}
1914
John McCallf1549f62010-07-06 01:34:17 +00001915void CGObjCGNU::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1916 const ObjCAtSynchronizedStmt &S) {
1917 std::vector<const llvm::Type*> Args(1, IdTy);
1918 llvm::FunctionType *FTy =
1919 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner5dc08672009-05-08 00:11:50 +00001920
John McCallf1549f62010-07-06 01:34:17 +00001921 // Evaluate the lock operand. This should dominate the cleanup.
1922 llvm::Value *SyncArg =
1923 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattner5dc08672009-05-08 00:11:50 +00001924
John McCallf1549f62010-07-06 01:34:17 +00001925 // Acquire the lock.
1926 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1927 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1928 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001929
John McCallf1549f62010-07-06 01:34:17 +00001930 // Register an all-paths cleanup to release the lock.
John McCall740e8072010-07-21 00:41:47 +00001931 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
John McCall1f0fca52010-07-21 07:22:38 +00001932 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExit, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001933
John McCallf1549f62010-07-06 01:34:17 +00001934 // Emit the body of the statement.
1935 CGF.EmitStmt(S.getSynchBody());
Chris Lattner5dc08672009-05-08 00:11:50 +00001936
John McCallf1549f62010-07-06 01:34:17 +00001937 // Pop the lock-release cleanup.
1938 CGF.PopCleanupBlock();
1939}
Chris Lattner5dc08672009-05-08 00:11:50 +00001940
John McCallf1549f62010-07-06 01:34:17 +00001941namespace {
1942 struct CatchHandler {
1943 const VarDecl *Variable;
1944 const Stmt *Body;
1945 llvm::BasicBlock *Block;
1946 llvm::Value *TypeInfo;
1947 };
1948}
David Chisnall0faa5162009-12-24 02:26:34 +00001949
John McCallf1549f62010-07-06 01:34:17 +00001950void CGObjCGNU::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1951 const ObjCAtTryStmt &S) {
1952 // Unlike the Apple non-fragile runtimes, which also uses
1953 // unwind-based zero cost exceptions, the GNU Objective C runtime's
1954 // EH support isn't a veneer over C++ EH. Instead, exception
1955 // objects are created by __objc_exception_throw and destroyed by
1956 // the personality function; this avoids the need for bracketing
1957 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
1958 // (or even _Unwind_DeleteException), but probably doesn't
1959 // interoperate very well with foreign exceptions.
1960
1961 // Jump destination for falling out of catch bodies.
1962 CodeGenFunction::JumpDest Cont;
1963 if (S.getNumCatchStmts())
1964 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
1965
1966 // We handle @finally statements by pushing them as a cleanup
1967 // before entering the catch.
1968 CodeGenFunction::FinallyInfo FinallyInfo;
1969 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
1970 std::vector<const llvm::Type*> Args(1, IdTy);
1971 llvm::FunctionType *FTy =
1972 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
1973 llvm::Constant *Rethrow =
1974 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1975
1976 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
1977 Rethrow);
David Chisnall0faa5162009-12-24 02:26:34 +00001978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
John McCallf1549f62010-07-06 01:34:17 +00001980 llvm::SmallVector<CatchHandler, 8> Handlers;
1981
1982 // Enter the catch, if there is one.
1983 if (S.getNumCatchStmts()) {
1984 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
1985 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
1986 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1987
1988 Handlers.push_back(CatchHandler());
1989 CatchHandler &Handler = Handlers.back();
1990 Handler.Variable = CatchDecl;
1991 Handler.Body = CatchStmt->getCatchBody();
1992 Handler.Block = CGF.createBasicBlock("catch");
1993
1994 // @catch() and @catch(id) both catch any ObjC exception.
1995 // Treat them as catch-alls.
1996 // FIXME: this is what this code was doing before, but should 'id'
1997 // really be catching foreign exceptions?
1998 if (!CatchDecl
1999 || CatchDecl->getType()->isObjCIdType()
2000 || CatchDecl->getType()->isObjCQualifiedIdType()) {
2001
2002 Handler.TypeInfo = 0; // catch-all
2003
2004 // Don't consider any other catches.
2005 break;
2006 }
2007
2008 // All other types should be Objective-C interface pointer types.
2009 const ObjCObjectPointerType *OPT =
2010 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
2011 assert(OPT && "Invalid @catch type.");
2012 const ObjCInterfaceDecl *IDecl =
2013 OPT->getObjectType()->getInterface();
2014 assert(IDecl && "Invalid @catch type.");
2015 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
2016 }
2017
2018 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2019 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2020 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2021 }
2022
2023 // Emit the try body.
2024 CGF.EmitStmt(S.getTryBody());
2025
2026 // Leave the try.
2027 if (S.getNumCatchStmts())
2028 CGF.EHStack.popCatch();
2029
2030 // Remember where we were.
2031 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2032
2033 // Emit the handlers.
2034 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2035 CatchHandler &Handler = Handlers[I];
2036 CGF.EmitBlock(Handler.Block);
2037
2038 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2039
2040 // Bind the catch parameter if it exists.
2041 if (const VarDecl *CatchParam = Handler.Variable) {
2042 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2043 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2044
John McCallb6bbcc92010-10-15 04:57:14 +00002045 CGF.EmitAutoVarDecl(*CatchParam);
John McCallf1549f62010-07-06 01:34:17 +00002046 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2047 }
2048
2049 CGF.ObjCEHValueStack.push_back(Exn);
2050 CGF.EmitStmt(Handler.Body);
2051 CGF.ObjCEHValueStack.pop_back();
2052
2053 CGF.EmitBranchThroughCleanup(Cont);
2054 }
2055
2056 // Go back to the try-statement fallthrough.
2057 CGF.Builder.restoreIP(SavedIP);
2058
2059 // Pop out of the finally.
2060 if (S.getFinallyStmt())
2061 CGF.ExitFinallyBlock(FinallyInfo);
2062
John McCallff8e1152010-07-23 21:56:41 +00002063 if (Cont.isValid()) {
2064 if (Cont.getBlock()->use_empty())
2065 delete Cont.getBlock();
2066 else
2067 CGF.EmitBlock(Cont.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00002068 }
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002069}
2070
2071void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002072 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002073 llvm::Value *ExceptionAsObject;
2074
2075 std::vector<const llvm::Type*> Args(1, IdTy);
2076 llvm::FunctionType *FTy =
Owen Anderson0032b272009-08-13 21:57:51 +00002077 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002078 llvm::Value *ThrowFn =
Chris Lattner5dc08672009-05-08 00:11:50 +00002079 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Chris Lattner5dc08672009-05-08 00:11:50 +00002081 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2082 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002083 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002084 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002085 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002086 "Unexpected rethrow outside @catch block.");
2087 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2088 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002089 ExceptionAsObject =
2090 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Chris Lattner5dc08672009-05-08 00:11:50 +00002092 // Note: This may have to be an invoke, if we want to support constructs like:
2093 // @try {
2094 // @throw(obj);
2095 // }
2096 // @catch(id) ...
2097 //
2098 // This is effectively turning @throw into an incredibly-expensive goto, but
2099 // it may happen as a result of inlining followed by missed optimizations, or
2100 // as a result of stupidity.
2101 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2102 if (!UnwindBB) {
2103 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2104 CGF.Builder.CreateUnreachable();
2105 } else {
2106 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2107 &ExceptionAsObject+1);
2108 }
2109 // Clear the insertion point to indicate we are in unreachable code.
2110 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002111}
2112
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002113llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002114 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002115 CGBuilderTy B = CGF.Builder;
2116 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2117 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002118}
2119
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002120void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002121 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002122 CGBuilderTy B = CGF.Builder;
2123 src = EnforceType(B, src, IdTy);
2124 dst = EnforceType(B, dst, PtrToIdTy);
2125 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002126}
2127
Fariborz Jahanian58626502008-11-19 00:59:10 +00002128void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002129 llvm::Value *src, llvm::Value *dst,
2130 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002131 CGBuilderTy B = CGF.Builder;
2132 src = EnforceType(B, src, IdTy);
2133 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002134 if (!threadlocal)
2135 B.CreateCall2(GlobalAssignFn, src, dst);
2136 else
2137 // FIXME. Add threadloca assign API
2138 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002139}
2140
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002141void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002142 llvm::Value *src, llvm::Value *dst,
2143 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002144 CGBuilderTy B = CGF.Builder;
2145 src = EnforceType(B, src, IdTy);
2146 dst = EnforceType(B, dst, PtrToIdTy);
2147 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002148}
2149
Fariborz Jahanian58626502008-11-19 00:59:10 +00002150void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002151 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002152 CGBuilderTy B = CGF.Builder;
2153 src = EnforceType(B, src, IdTy);
2154 dst = EnforceType(B, dst, PtrToIdTy);
2155 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002156}
2157
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002158void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002159 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002160 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002161 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002162 CGBuilderTy B = CGF.Builder;
2163 DestPtr = EnforceType(B, DestPtr, IdTy);
2164 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2165
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002166 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002167}
2168
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002169llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2170 const ObjCInterfaceDecl *ID,
2171 const ObjCIvarDecl *Ivar) {
2172 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2173 + '.' + Ivar->getNameAsString();
2174 // Emit the variable and initialize it with what we think the correct value
2175 // is. This allows code compiled with non-fragile ivars to work correctly
2176 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002177 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2178 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002179 // This will cause a run-time crash if we accidentally use it. A value of
2180 // 0 would seem more sensible, but will silently overwrite the isa pointer
2181 // causing a great deal of confusion.
2182 uint64_t Offset = -1;
2183 // We can't call ComputeIvarBaseOffset() here if we have the
2184 // implementation, because it will create an invalid ASTRecordLayout object
2185 // that we are then stuck with forever, so we only initialize the ivar
2186 // offset variable with a guess if we only have the interface. The
2187 // initializer will be reset later anyway, when we are generating the class
2188 // description.
2189 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002190 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002191 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2192
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002193 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002194 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002195 // Don't emit the guess in non-PIC code because the linker will not be able
2196 // to replace it with the real version for a library. In non-PIC code you
2197 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002198 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002199 if (CGM.getLangOptions().PICLevel) {
2200 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2201 llvm::Type::getInt32Ty(VMContext), false,
2202 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2203 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2204 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2205 IvarOffsetGV, Name);
2206 } else {
2207 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002208 llvm::Type::getInt32PtrTy(VMContext), false,
2209 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002210 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002211 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002212 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002213}
2214
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002215LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2216 QualType ObjectTy,
2217 llvm::Value *BaseValue,
2218 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002219 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002220 const ObjCInterfaceDecl *ID =
2221 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002222 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2223 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002224}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002225
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002226static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2227 const ObjCInterfaceDecl *OID,
2228 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002229 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002230 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002231 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2232 if (OIVD == Ivars[k])
2233 return OID;
2234 }
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002236 // Otherwise check in the super class.
2237 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2238 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002240 return 0;
2241}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002242
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002243llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002244 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002245 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002246 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002247 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002248 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2249 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002250 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002251 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002252 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002253}
2254
Mike Stumpbb1c8602009-07-31 21:31:32 +00002255CodeGen::CGObjCRuntime *
2256CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattnerdce14062008-06-26 04:19:03 +00002257 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002258}