blob: e39769d9477eb52cbffe509aaf750816f42a89ad [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000020
Chris Lattner87ab27d2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000026
27#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000028#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000029#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000030#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000031#include "llvm/ADT/StringMap.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000032#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000033#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000034
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000035#include <map>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000036
37
Chris Lattner87ab27d2008-06-26 04:19:03 +000038using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000039using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040using llvm::dyn_cast;
41
42// The version of the runtime that this class targets. Must match the version
43// in the runtime.
44static const int RuntimeVersion = 8;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +000045static const int NonFragileRuntimeVersion = 9;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000046static const int ProtocolVersion = 2;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000047static const int NonFragileProtocolVersion = 3;
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048
Chris Lattnerb7256cd2008-03-01 08:50:34 +000049namespace {
Chris Lattner87ab27d2008-06-26 04:19:03 +000050class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattnerb7256cd2008-03-01 08:50:34 +000051private:
Chris Lattner87ab27d2008-06-26 04:19:03 +000052 CodeGen::CodeGenModule &CGM;
Chris Lattnerb7256cd2008-03-01 08:50:34 +000053 llvm::Module &TheModule;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000054 const llvm::PointerType *SelectorTy;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000055 const llvm::IntegerType *Int8Ty;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000056 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +000057 const llvm::FunctionType *IMPTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000058 const llvm::PointerType *IdTy;
David Chisnall5bb4efd2010-02-03 15:59:02 +000059 const llvm::PointerType *PtrToIdTy;
John McCall2da83a32010-02-26 00:48:12 +000060 CanQualType ASTIdTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000061 const llvm::IntegerType *IntTy;
62 const llvm::PointerType *PtrTy;
63 const llvm::IntegerType *LongTy;
64 const llvm::PointerType *PtrToIntTy;
Daniel Dunbar566421c2009-05-04 15:31:17 +000065 llvm::GlobalAlias *ClassPtrAlias;
66 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000067 std::vector<llvm::Constant*> Classes;
68 std::vector<llvm::Constant*> Categories;
69 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall358e7512010-01-27 12:49:23 +000070 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000071 llvm::Function *LoadFunction;
72 llvm::StringMap<llvm::Constant*> ExistingProtocols;
73 typedef std::pair<std::string, std::string> TypedSelector;
74 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
75 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnall5bb4efd2010-02-03 15:59:02 +000076 // Selectors that we don't emit in GC mode
77 Selector RetainSel, ReleaseSel, AutoreleaseSel;
78 // Functions used for GC.
79 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
80 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000081 // Some zeros used for GEPs in lots of places.
82 llvm::Constant *Zeros[2];
83 llvm::Constant *NULLPtr;
Owen Anderson170229f2009-07-14 23:10:40 +000084 llvm::LLVMContext &VMContext;
David Chisnall01aa4672010-04-28 19:33:36 +000085 /// Metadata kind used to tie method lookups to message sends.
86 unsigned msgSendMDKind;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000087private:
88 llvm::Constant *GenerateIvarList(
89 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
90 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
91 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
92 llvm::Constant *GenerateMethodList(const std::string &ClassName,
93 const std::string &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +000094 const llvm::SmallVectorImpl<Selector> &MethodSels,
95 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000096 bool isClassMethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +000097 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000098 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
99 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
100 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000101 llvm::Constant *GenerateProtocolList(
102 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000103 // To ensure that all protocols are seen by the runtime, we add a category on
104 // a class defined in the runtime, declaring no methods, but adopting the
105 // protocols.
106 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000107 llvm::Constant *GenerateClassStructure(
108 llvm::Constant *MetaClass,
109 llvm::Constant *SuperClass,
110 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000111 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000112 llvm::Constant *Version,
113 llvm::Constant *InstanceSize,
114 llvm::Constant *IVars,
115 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000116 llvm::Constant *Protocols,
117 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000118 llvm::Constant *Properties,
119 bool isMeta=false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000120 llvm::Constant *GenerateProtocolMethodList(
121 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
122 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
123 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
124 &Name="");
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000125 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
126 prefix);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000127 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000128 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnalldf349172010-01-08 00:14:31 +0000129 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000130 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000131 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnalldf349172010-01-08 00:14:31 +0000132 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000133 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
134 const ObjCIvarDecl *Ivar);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000135 void EmitClassRef(const std::string &className);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000136 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
137 if (V->getType() == Ty) return V;
138 return B.CreateBitCast(V, Ty);
139 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000140public:
Chris Lattner87ab27d2008-06-26 04:19:03 +0000141 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall481e3a82010-01-23 02:40:42 +0000142 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump11289f42009-09-09 15:08:12 +0000143 virtual CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000144 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000145 QualType ResultType,
146 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000147 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000148 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000149 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000150 const ObjCMethodDecl *Method);
Mike Stump11289f42009-09-09 15:08:12 +0000151 virtual CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000152 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000153 QualType ResultType,
154 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000155 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000156 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000157 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000158 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000159 const CallArgList &CallArgs,
160 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000161 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000162 const ObjCInterfaceDecl *OID);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000163 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
164 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
165 *Method);
Mike Stump11289f42009-09-09 15:08:12 +0000166
167 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000168 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000169 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
170 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000171 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000172 const ObjCProtocolDecl *PD);
173 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000174 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000175 virtual llvm::Function *GetPropertyGetFunction();
176 virtual llvm::Function *GetPropertySetFunction();
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000177 virtual llvm::Function *GetCopyStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000178 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000179
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +0000180 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
181 const Stmt &S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000182 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
183 const ObjCAtThrowStmt &S);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000184 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000185 llvm::Value *AddrWeakObj);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000186 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
187 llvm::Value *src, llvm::Value *dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000188 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
189 llvm::Value *src, llvm::Value *dest);
Fariborz Jahaniane881b532008-11-20 19:23:36 +0000190 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000191 llvm::Value *src, llvm::Value *dest,
192 llvm::Value *ivarOffset);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000193 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
194 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000195 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000196 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000197 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000198 QualType Ty);
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000199 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
200 QualType ObjectTy,
201 llvm::Value *BaseValue,
202 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000203 unsigned CVRQualifiers);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000204 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000205 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000206 const ObjCIvarDecl *Ivar);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000207};
208} // end anonymous namespace
209
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000210
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000211/// Emits a reference to a dummy variable which is emitted with each class.
212/// This ensures that a linker error will be generated when trying to link
213/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000214void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000215 std::string symbolRef = "__objc_class_ref_" + className;
216 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000217 if (TheModule.getGlobalVariable(symbolRef))
218 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000219 std::string symbolName = "__objc_class_name_" + className;
220 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
221 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000222 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
223 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000224 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000225 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000226 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000227}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000228
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000229static std::string SymbolNameForMethod(const std::string &ClassName, const
230 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
231{
David Chisnall035ead22010-01-14 14:08:19 +0000232 std::string MethodNameColonStripped = MethodName;
233 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
234 ':', '_');
235 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
236 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000237}
David Chisnall0a24fd32010-05-08 20:58:05 +0000238static std::string MangleSelectorTypes(const std::string &TypeString) {
239 std::string Mangled = TypeString;
240 std::replace(Mangled.begin(), Mangled.end(), '@', '_');
241 return Mangled;
242}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000243
Chris Lattner87ab27d2008-06-26 04:19:03 +0000244CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar566421c2009-05-04 15:31:17 +0000245 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Anderson170229f2009-07-14 23:10:40 +0000246 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnall01aa4672010-04-28 19:33:36 +0000247
248 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
249
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000250 IntTy = cast<llvm::IntegerType>(
251 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
252 LongTy = cast<llvm::IntegerType>(
253 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Mike Stump11289f42009-09-09 15:08:12 +0000254
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000255 Int8Ty = llvm::Type::getInt8Ty(VMContext);
256 // C string type. Used in lots of places.
257 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
258
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000259 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000260 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000261 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000262 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000263 QualType selTy = CGM.getContext().getObjCSelType();
264 if (QualType() == selTy) {
265 SelectorTy = PtrToInt8Ty;
266 } else {
267 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
268 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000269
Owen Anderson9793f0e2009-07-29 22:16:19 +0000270 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000271 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner4bd55962008-03-30 23:03:07 +0000273 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000274 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000275 if (QualType() == ASTIdTy) {
276 IdTy = PtrToInt8Ty;
277 } else {
278 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
279 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000280 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Chris Lattner4bd55962008-03-30 23:03:07 +0000282 // IMP type
283 std::vector<const llvm::Type*> IMPArgs;
284 IMPArgs.push_back(IdTy);
285 IMPArgs.push_back(SelectorTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000286 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000287
288 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
289 // Get selectors needed in GC mode
290 RetainSel = GetNullarySelector("retain", CGM.getContext());
291 ReleaseSel = GetNullarySelector("release", CGM.getContext());
292 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
293
294 // Get functions needed in GC mode
295
296 // id objc_assign_ivar(id, id, ptrdiff_t);
297 std::vector<const llvm::Type*> Args(1, IdTy);
298 Args.push_back(PtrToIdTy);
299 // FIXME: ptrdiff_t
300 Args.push_back(LongTy);
301 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
302 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
303 // id objc_assign_strongCast (id, id*)
304 Args.pop_back();
305 FTy = llvm::FunctionType::get(IdTy, Args, false);
306 StrongCastAssignFn =
307 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
308 // id objc_assign_global(id, id*);
309 FTy = llvm::FunctionType::get(IdTy, Args, false);
310 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
311 // id objc_assign_weak(id, id*);
312 FTy = llvm::FunctionType::get(IdTy, Args, false);
313 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
314 // id objc_read_weak(id*);
315 Args.clear();
316 Args.push_back(PtrToIdTy);
317 FTy = llvm::FunctionType::get(IdTy, Args, false);
318 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
319 // void *objc_memmove_collectable(void*, void *, size_t);
320 Args.clear();
321 Args.push_back(PtrToInt8Ty);
322 Args.push_back(PtrToInt8Ty);
323 // FIXME: size_t
324 Args.push_back(LongTy);
325 FTy = llvm::FunctionType::get(IdTy, Args, false);
326 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
327 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000328}
Mike Stumpdd93a192009-07-31 21:31:32 +0000329
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000330// This has to perform the lookup every time, since posing and related
331// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000332llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000333 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000334 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000335 // With the incompatible ABI, this will need to be replaced with a direct
336 // reference to the class symbol. For the compatible nonfragile ABI we are
337 // still performing this lookup at run time but emitting the symbol for the
338 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000339 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000340 ClassName = Builder.CreateStructGEP(ClassName, 0);
341
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000342 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000343 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000344 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000345 Params,
346 true),
347 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000348 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000349}
350
Daniel Dunbar45858d22010-02-03 20:11:42 +0000351llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Chris Lattnere4b95692008-11-24 03:33:13 +0000352 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner6d522c02008-06-26 04:37:12 +0000353 if (US == 0)
Daniel Dunbar45858d22010-02-03 20:11:42 +0000354 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall9f57c292009-08-17 16:35:33 +0000355 llvm::GlobalValue::PrivateLinkage,
356 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner6d522c02008-06-26 04:37:12 +0000357 NULL, &TheModule);
Mike Stump11289f42009-09-09 15:08:12 +0000358
Daniel Dunbar45858d22010-02-03 20:11:42 +0000359 return Builder.CreateLoad(US);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000360}
361
Daniel Dunbar45858d22010-02-03 20:11:42 +0000362llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000363 *Method) {
364
365 std::string SelName = Method->getSelector().getAsString();
366 std::string SelTypes;
367 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
368 // Typed selectors
369 TypedSelector Selector = TypedSelector(SelName,
370 SelTypes);
371
372 // If it's already cached, return it.
Mike Stumpdd93a192009-07-31 21:31:32 +0000373 if (TypedSelectors[Selector]) {
Daniel Dunbar45858d22010-02-03 20:11:42 +0000374 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000375 }
376
377 // If it isn't, cache it.
378 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar45858d22010-02-03 20:11:42 +0000379 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall9f57c292009-08-17 16:35:33 +0000380 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000381 NULL, &TheModule);
382 TypedSelectors[Selector] = Sel;
383
Daniel Dunbar45858d22010-02-03 20:11:42 +0000384 return Builder.CreateLoad(Sel);
Chris Lattner6d522c02008-06-26 04:37:12 +0000385}
386
Chris Lattnerd9b98862008-06-26 04:44:19 +0000387llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
388 const std::string &Name) {
David Chisnall5778fce2009-08-31 16:41:57 +0000389 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Andersonade90fd2009-07-29 18:54:39 +0000390 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000391}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000392llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
393 const std::string prefix) {
394 std::string name = prefix + Str;
395 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
396 if (!ConstStr) {
397 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
398 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
399 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
400 }
401 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
402}
Mike Stumpdd93a192009-07-31 21:31:32 +0000403
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000404llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000405 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000406 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson0e0189d2009-07-27 22:29:56 +0000407 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000408 return new llvm::GlobalVariable(TheModule, Ty, false,
409 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000410}
Mike Stumpdd93a192009-07-31 21:31:32 +0000411
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000412llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000413 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000414 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson47034e12009-07-28 18:33:04 +0000415 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000416 return new llvm::GlobalVariable(TheModule, Ty, false,
Mike Stumpdd93a192009-07-31 21:31:32 +0000417 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000418}
419
420/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000421llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000422
David Chisnall481e3a82010-01-23 02:40:42 +0000423 std::string Str(SL->getStrData(), SL->getByteLength());
424
David Chisnall358e7512010-01-27 12:49:23 +0000425 // Look for an existing one
426 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
427 if (old != ObjCStrings.end())
428 return old->getValue();
429
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000430 std::vector<llvm::Constant*> Ivars;
431 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000432 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000433 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000434 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000435 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000436 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000437 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
438 ObjCStrings[Str] = ObjCStr;
439 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000440 return ObjCStr;
441}
442
443///Generates a message send where the super is the receiver. This is a message
444///send to self with special delivery semantics indicating which class's method
445///should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000446CodeGen::RValue
447CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000448 QualType ResultType,
449 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000450 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000451 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000452 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000453 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000454 const CallArgList &CallArgs,
455 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000456 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
457 if (Sel == RetainSel || Sel == AutoreleaseSel) {
458 return RValue::get(Receiver);
459 }
460 if (Sel == ReleaseSel) {
461 return RValue::get(0);
462 }
463 }
David Chisnallea529a42010-05-01 12:37:16 +0000464
465 CGBuilderTy &Builder = CGF.Builder;
466 llvm::Value *cmd = GetSelector(Builder, Sel);
467
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000468
469 CallArgList ActualArgs;
470
471 ActualArgs.push_back(
David Chisnallea529a42010-05-01 12:37:16 +0000472 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall9f57c292009-08-17 16:35:33 +0000473 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000474 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
475 CGF.getContext().getObjCSelType()));
476 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
477
478 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000479 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000480 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000481 const llvm::FunctionType *impType =
482 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000483
Daniel Dunbar566421c2009-05-04 15:31:17 +0000484 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000485 if (isCategoryImpl) {
486 llvm::Constant *classLookupFunction = 0;
487 std::vector<const llvm::Type*> Params;
488 Params.push_back(PtrTy);
489 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000490 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000491 IdTy, Params, true), "objc_get_meta_class");
492 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000493 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000494 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000495 }
David Chisnallea529a42010-05-01 12:37:16 +0000496 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000497 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000498 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000499 // Set up global aliases for the metaclass or class pointer if they do not
500 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000501 // pointers to the class and metaclass structure created for the runtime
502 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000503 // super_class pointer from either the class or metaclass structure.
504 if (IsClassMessage) {
505 if (!MetaClassPtrAlias) {
506 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
507 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
508 Class->getNameAsString(), NULL, &TheModule);
509 }
510 ReceiverClass = MetaClassPtrAlias;
511 } else {
512 if (!ClassPtrAlias) {
513 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
514 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
515 Class->getNameAsString(), NULL, &TheModule);
516 }
517 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000518 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000519 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000520 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +0000521 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000522 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000523 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000524 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000525 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +0000526 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000527 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000528 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000529 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
530 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +0000531 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000532
David Chisnallea529a42010-05-01 12:37:16 +0000533 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
534 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000535
536 // Get the IMP
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000537 std::vector<const llvm::Type*> Params;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000538 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000539 Params.push_back(SelectorTy);
David Chisnallea529a42010-05-01 12:37:16 +0000540
541 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
542 llvm::Value *imp;
543
544 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
545 // The lookup function returns a slot, which can be safely cached.
546 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
547 IntTy, llvm::PointerType::getUnqual(impType), NULL);
548
549 llvm::Constant *lookupFunction =
550 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
551 llvm::PointerType::getUnqual(SlotTy), Params, true),
552 "objc_slot_lookup_super");
553
554 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
555 lookupArgs+2);
556 slot->setOnlyReadsMemory();
557
558 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
559 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000560 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000561 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
562 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000563 "objc_msg_lookup_super");
David Chisnallea529a42010-05-01 12:37:16 +0000564 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
565 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000566
David Chisnall9eecafa2010-05-01 11:15:56 +0000567 llvm::Value *impMD[] = {
568 llvm::MDString::get(VMContext, Sel.getAsString()),
569 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
570 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
571 };
572 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
573
David Chisnallff5f88c2010-05-02 13:41:58 +0000574 llvm::Instruction *call;
575 RValue msgRet = CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs,
576 0, &call);
577 call->setMetadata(msgSendMDKind, node);
578 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000579}
580
Mike Stump11289f42009-09-09 15:08:12 +0000581/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000582CodeGen::RValue
583CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000584 QualType ResultType,
585 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000586 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000587 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000588 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000589 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +0000590 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000591 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
592 if (Sel == RetainSel || Sel == AutoreleaseSel) {
593 return RValue::get(Receiver);
594 }
595 if (Sel == ReleaseSel) {
596 return RValue::get(0);
597 }
598 }
David Chisnall75afda62010-04-27 15:08:48 +0000599
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000600 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +0000601
602 // If the return type is something that goes in an integer register, the
603 // runtime will handle 0 returns. For other cases, we fill in the 0 value
604 // ourselves.
605 //
606 // The language spec says the result of this kind of message send is
607 // undefined, but lots of people seem to have forgotten to read that
608 // paragraph and insist on sending messages to nil that have structure
609 // returns. With GCC, this generates a random return value (whatever happens
610 // to be on the stack / in those registers at the time) on most platforms,
611 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
612 bool isPointerSizedReturn = false;
David Chisnalle6d00732010-04-27 20:33:30 +0000613 if (ResultType->isAnyPointerType() || ResultType->isIntegralType() ||
614 ResultType->isVoidType())
David Chisnall75afda62010-04-27 15:08:48 +0000615 isPointerSizedReturn = true;
616
617 llvm::BasicBlock *startBB = 0;
618 llvm::BasicBlock *messageBB = 0;
619 llvm::BasicBlock *contiueBB = 0;
620
621 if (!isPointerSizedReturn) {
622 startBB = Builder.GetInsertBlock();
623 messageBB = CGF.createBasicBlock("msgSend");
624 contiueBB = CGF.createBasicBlock("continue");
625
626 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
627 llvm::Constant::getNullValue(Receiver->getType()));
628 Builder.CreateCondBr(isNil, contiueBB, messageBB);
629 CGF.EmitBlock(messageBB);
630 }
631
David Chisnall9f57c292009-08-17 16:35:33 +0000632 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000633 llvm::Value *cmd;
634 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000635 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000636 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000637 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000638 CallArgList ActualArgs;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000639
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000640 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000641 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000642 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000643 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
644 CGF.getContext().getObjCSelType()));
645 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
646
647 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000648 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000649 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000650 const llvm::FunctionType *impType =
651 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000652
David Chisnallc0cf4222010-05-01 12:56:56 +0000653 llvm::Value *impMD[] = {
654 llvm::MDString::get(VMContext, Sel.getAsString()),
655 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
656 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
657 };
658 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
659
660
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000661 llvm::Value *imp;
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000662 // For sender-aware dispatch, we pass the sender as the third argument to a
663 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000664 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
665 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
666
667 std::vector<const llvm::Type*> Params;
668 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
669 Builder.CreateStore(Receiver, ReceiverPtr);
670 Params.push_back(ReceiverPtr->getType());
671 Params.push_back(SelectorTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000672 llvm::Value *self;
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000673
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000674 if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
675 self = CGF.LoadObjCSelf();
676 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +0000677 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000678 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000679
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000680 Params.push_back(self->getType());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000681
682 // The lookup function returns a slot, which can be safely cached.
683 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
684 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000685 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000686 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000687 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000688 "objc_msg_lookup_sender");
689
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000690 // The lookup function is guaranteed not to capture the receiver pointer.
691 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
692 LookupFn->setDoesNotCapture(1);
693 }
694
David Chisnalld6a6af62010-04-30 13:36:12 +0000695 llvm::CallInst *slot =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000696 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnalld6a6af62010-04-30 13:36:12 +0000697 slot->setOnlyReadsMemory();
David Chisnallc0cf4222010-05-01 12:56:56 +0000698 slot->setMetadata(msgSendMDKind, node);
David Chisnalld6a6af62010-04-30 13:36:12 +0000699
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000700 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnall01aa4672010-04-28 19:33:36 +0000701
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000702 // The lookup function may have changed the receiver, so make sure we use
703 // the new one.
704 ActualArgs[0] =
705 std::make_pair(RValue::get(Builder.CreateLoad(ReceiverPtr)), ASTIdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000706 } else {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000707 std::vector<const llvm::Type*> Params;
708 Params.push_back(Receiver->getType());
709 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000710 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000711 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
712 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000713 "objc_msg_lookup");
714
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000715 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnallc0cf4222010-05-01 12:56:56 +0000716 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000717 }
David Chisnallff5f88c2010-05-02 13:41:58 +0000718 llvm::Instruction *call;
David Chisnall9eecafa2010-05-01 11:15:56 +0000719 RValue msgRet = CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000720 0, &call);
721 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +0000722
723 if (!isPointerSizedReturn) {
724 CGF.EmitBlock(contiueBB);
725 if (msgRet.isScalar()) {
726 llvm::Value *v = msgRet.getScalarVal();
727 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
728 phi->addIncoming(v, messageBB);
729 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
730 msgRet = RValue::get(phi);
731 } else if (msgRet.isAggregate()) {
732 llvm::Value *v = msgRet.getAggregateAddr();
733 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
734 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +0000735 llvm::AllocaInst *NullVal =
736 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +0000737 CGF.InitTempAlloca(NullVal,
738 llvm::Constant::getNullValue(RetTy->getElementType()));
739 phi->addIncoming(v, messageBB);
740 phi->addIncoming(NullVal, startBB);
741 msgRet = RValue::getAggregate(phi);
742 } else /* isComplex() */ {
743 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
744 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
745 phi->addIncoming(v.first, messageBB);
746 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
747 startBB);
748 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
749 phi2->addIncoming(v.second, messageBB);
750 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
751 startBB);
752 msgRet = RValue::getComplex(phi, phi2);
753 }
754 }
755 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000756}
757
Mike Stump11289f42009-09-09 15:08:12 +0000758/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000759/// objc_category structures.
760llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump11289f42009-09-09 15:08:12 +0000761 const std::string &CategoryName,
762 const llvm::SmallVectorImpl<Selector> &MethodSels,
763 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000764 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +0000765 if (MethodSels.empty())
766 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000767 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000768 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000769 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
770 PtrToInt8Ty, // Method types
Owen Anderson9793f0e2009-07-29 22:16:19 +0000771 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000772 NULL);
773 std::vector<llvm::Constant*> Methods;
774 std::vector<llvm::Constant*> Elements;
775 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
776 Elements.clear();
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000777 if (llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000778 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnere4b95692008-11-24 03:33:13 +0000779 MethodSels[i].getAsString(),
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000780 isClassMethodList))) {
David Chisnall5778fce2009-08-31 16:41:57 +0000781 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
782 Elements.push_back(C);
783 Elements.push_back(MethodTypes[i]);
Owen Andersonade90fd2009-07-29 18:54:39 +0000784 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000785 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000786 Elements.push_back(Method);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000787 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000788 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000789 }
790
791 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000792 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000793 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000794 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +0000795 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000796
797 // Structure containing list pointer, array and array count
798 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +0000799 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000800 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +0000801 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +0000802 NextPtrTy,
803 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000804 ObjCMethodArrayTy,
805 NULL);
806 // Refine next pointer type to concrete type
807 llvm::cast<llvm::OpaqueType>(
808 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
809 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
810
811 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +0000812 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +0000813 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +0000814 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000815 MethodTypes.size()));
816 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000818 // Create an instance of the structure
819 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
820}
821
822/// Generates an IvarList. Used in construction of a objc_class.
823llvm::Constant *CGObjCGNU::GenerateIvarList(
824 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
825 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
826 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +0000827 if (IvarNames.size() == 0)
828 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000829 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000830 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000831 PtrToInt8Ty,
832 PtrToInt8Ty,
833 IntTy,
834 NULL);
835 std::vector<llvm::Constant*> Ivars;
836 std::vector<llvm::Constant*> Elements;
837 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
838 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +0000839 Elements.push_back(IvarNames[i]);
840 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000841 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000842 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000843 }
844
845 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000846 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000847 IvarNames.size());
848
Mike Stump11289f42009-09-09 15:08:12 +0000849
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000850 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000851 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +0000852 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000853 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +0000854 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000855 ObjCIvarArrayTy,
856 NULL);
857
858 // Create an instance of the structure
859 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
860}
861
862/// Generate a class structure
863llvm::Constant *CGObjCGNU::GenerateClassStructure(
864 llvm::Constant *MetaClass,
865 llvm::Constant *SuperClass,
866 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000867 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000868 llvm::Constant *Version,
869 llvm::Constant *InstanceSize,
870 llvm::Constant *IVars,
871 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000872 llvm::Constant *Protocols,
873 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000874 llvm::Constant *Properties,
875 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000876 // Set up the class structure
877 // Note: Several of these are char*s when they should be ids. This is
878 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000879 //
880 // Fields marked New ABI are part of the GNUstep runtime. We emit them
881 // anyway; the classes will still work with the GNU runtime, they will just
882 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +0000883 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000884 PtrToInt8Ty, // class_pointer
885 PtrToInt8Ty, // super_class
886 PtrToInt8Ty, // name
887 LongTy, // version
888 LongTy, // info
889 LongTy, // instance_size
890 IVars->getType(), // ivars
891 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +0000892 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000893 PtrTy, // dtable
894 PtrTy, // subclass_list
895 PtrTy, // sibling_class
896 PtrTy, // protocols
897 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000898 // New ABI:
899 LongTy, // abi_version
900 IvarOffsets->getType(), // ivar_offsets
901 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000902 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000903 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000904 // Fill in the structure
905 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +0000906 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000907 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +0000908 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000909 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000910 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000911 Elements.push_back(InstanceSize);
912 Elements.push_back(IVars);
913 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000914 Elements.push_back(NULLPtr);
915 Elements.push_back(NULLPtr);
916 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +0000917 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000918 Elements.push_back(NULLPtr);
919 Elements.push_back(Zero);
920 Elements.push_back(IvarOffsets);
921 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000922 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +0000923 // This is now an externally visible symbol, so that we can speed up class
924 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +0000925 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
926 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000927}
928
929llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
930 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
931 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +0000932 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000933 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000934 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
935 PtrToInt8Ty,
936 NULL);
937 std::vector<llvm::Constant*> Methods;
938 std::vector<llvm::Constant*> Elements;
939 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
940 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000941 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +0000942 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000943 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000944 }
Owen Anderson9793f0e2009-07-29 22:16:19 +0000945 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000946 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000947 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +0000948 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +0000949 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000950 IntTy, ObjCMethodArrayTy, NULL);
951 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000952 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000953 Methods.push_back(Array);
954 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
955}
Mike Stumpdd93a192009-07-31 21:31:32 +0000956
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000957// Create the protocol list structure used in classes, categories and so on
958llvm::Constant *CGObjCGNU::GenerateProtocolList(
959 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000960 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000961 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +0000962 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000963 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
964 LongTy,//FIXME: Should be size_t
965 ProtocolArrayTy,
966 NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000967 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000968 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
969 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +0000970 llvm::Constant *protocol = 0;
971 llvm::StringMap<llvm::Constant*>::iterator value =
972 ExistingProtocols.find(*iter);
973 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000974 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +0000975 } else {
976 protocol = value->getValue();
977 }
Owen Andersonade90fd2009-07-29 18:54:39 +0000978 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +0000979 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000980 Elements.push_back(Ptr);
981 }
Owen Anderson47034e12009-07-28 18:33:04 +0000982 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000983 Elements);
984 Elements.clear();
985 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000986 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000987 Elements.push_back(ProtocolArray);
988 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
989}
990
Mike Stump11289f42009-09-09 15:08:12 +0000991llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000992 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000993 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +0000994 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000995 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +0000996 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000997}
998
999llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1000 const std::string &ProtocolName) {
1001 llvm::SmallVector<std::string, 0> EmptyStringVector;
1002 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1003
1004 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001005 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001006 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1007 // Protocols are objects containing lists of the methods implemented and
1008 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001009 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001010 PtrToInt8Ty,
1011 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001012 MethodList->getType(),
1013 MethodList->getType(),
1014 MethodList->getType(),
1015 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001016 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001017 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001018 // The isa pointer must be set to a magic number so the runtime knows it's
1019 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001020 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1021 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +00001022 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001023 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001024 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1025 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001026 Elements.push_back(MethodList);
1027 Elements.push_back(MethodList);
1028 Elements.push_back(MethodList);
1029 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001030 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001031}
1032
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001033void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1034 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001035 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001036 llvm::SmallVector<std::string, 16> Protocols;
1037 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1038 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001039 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001040 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1041 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001042 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1043 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001044 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1045 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001046 std::string TypeStr;
1047 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001048 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1049 InstanceMethodNames.push_back(
1050 MakeConstantString((*iter)->getSelector().getAsString()));
1051 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1052 } else {
1053 OptionalInstanceMethodNames.push_back(
1054 MakeConstantString((*iter)->getSelector().getAsString()));
1055 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1056 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001057 }
1058 // Collect information about class methods:
1059 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1060 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001061 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1062 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001063 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001064 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1065 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001066 std::string TypeStr;
1067 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001068 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1069 ClassMethodNames.push_back(
1070 MakeConstantString((*iter)->getSelector().getAsString()));
1071 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1072 } else {
1073 OptionalClassMethodNames.push_back(
1074 MakeConstantString((*iter)->getSelector().getAsString()));
1075 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1076 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001077 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001078
1079 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1080 llvm::Constant *InstanceMethodList =
1081 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1082 llvm::Constant *ClassMethodList =
1083 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001084 llvm::Constant *OptionalInstanceMethodList =
1085 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1086 OptionalInstanceMethodTypes);
1087 llvm::Constant *OptionalClassMethodList =
1088 GenerateProtocolMethodList(OptionalClassMethodNames,
1089 OptionalClassMethodTypes);
1090
1091 // Property metadata: name, attributes, isSynthesized, setter name, setter
1092 // types, getter name, getter types.
1093 // The isSynthesized value is always set to 0 in a protocol. It exists to
1094 // simplify the runtime library by allowing it to use the same data
1095 // structures for protocol metadata everywhere.
1096 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1097 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1098 PtrToInt8Ty, NULL);
1099 std::vector<llvm::Constant*> Properties;
1100 std::vector<llvm::Constant*> OptionalProperties;
1101
1102 // Add all of the property methods need adding to the method list and to the
1103 // property metadata list.
1104 for (ObjCContainerDecl::prop_iterator
1105 iter = PD->prop_begin(), endIter = PD->prop_end();
1106 iter != endIter ; iter++) {
1107 std::vector<llvm::Constant*> Fields;
1108 ObjCPropertyDecl *property = (*iter);
1109
1110 Fields.push_back(MakeConstantString(property->getNameAsString()));
1111 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1112 property->getPropertyAttributes()));
1113 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1114 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1115 std::string TypeStr;
1116 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1117 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1118 InstanceMethodTypes.push_back(TypeEncoding);
1119 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1120 Fields.push_back(TypeEncoding);
1121 } else {
1122 Fields.push_back(NULLPtr);
1123 Fields.push_back(NULLPtr);
1124 }
1125 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1126 std::string TypeStr;
1127 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1128 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1129 InstanceMethodTypes.push_back(TypeEncoding);
1130 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1131 Fields.push_back(TypeEncoding);
1132 } else {
1133 Fields.push_back(NULLPtr);
1134 Fields.push_back(NULLPtr);
1135 }
1136 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1137 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1138 } else {
1139 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1140 }
1141 }
1142 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1143 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1144 llvm::Constant* PropertyListInitFields[] =
1145 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1146
1147 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001148 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001149 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1150 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1151 PropertyListInit, ".objc_property_list");
1152
1153 llvm::Constant *OptionalPropertyArray =
1154 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1155 OptionalProperties.size()) , OptionalProperties);
1156 llvm::Constant* OptionalPropertyListInitFields[] = {
1157 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1158 OptionalPropertyArray };
1159
1160 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001161 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001162 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1163 OptionalPropertyListInit->getType(), false,
1164 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1165 ".objc_property_list");
1166
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001167 // Protocols are objects containing lists of the methods implemented and
1168 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001169 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001170 PtrToInt8Ty,
1171 ProtocolList->getType(),
1172 InstanceMethodList->getType(),
1173 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001174 OptionalInstanceMethodList->getType(),
1175 OptionalClassMethodList->getType(),
1176 PropertyList->getType(),
1177 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001178 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001179 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001180 // The isa pointer must be set to a magic number so the runtime knows it's
1181 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001182 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1183 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +00001184 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001185 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001186 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1187 Elements.push_back(ProtocolList);
1188 Elements.push_back(InstanceMethodList);
1189 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001190 Elements.push_back(OptionalInstanceMethodList);
1191 Elements.push_back(OptionalClassMethodList);
1192 Elements.push_back(PropertyList);
1193 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001194 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001195 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001196 ".objc_protocol"), IdTy);
1197}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001198void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1199 // Collect information about instance methods
1200 llvm::SmallVector<Selector, 1> MethodSels;
1201 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1202
1203 std::vector<llvm::Constant*> Elements;
1204 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1205 const std::string CategoryName = "AnotherHack";
1206 Elements.push_back(MakeConstantString(CategoryName));
1207 Elements.push_back(MakeConstantString(ClassName));
1208 // Instance method list
1209 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1210 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1211 // Class method list
1212 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1213 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1214 // Protocol list
1215 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1216 ExistingProtocols.size());
1217 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1218 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1219 LongTy,//FIXME: Should be size_t
1220 ProtocolArrayTy,
1221 NULL);
1222 std::vector<llvm::Constant*> ProtocolElements;
1223 for (llvm::StringMapIterator<llvm::Constant*> iter =
1224 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1225 iter != endIter ; iter++) {
1226 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1227 PtrTy);
1228 ProtocolElements.push_back(Ptr);
1229 }
1230 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1231 ProtocolElements);
1232 ProtocolElements.clear();
1233 ProtocolElements.push_back(NULLPtr);
1234 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1235 ExistingProtocols.size()));
1236 ProtocolElements.push_back(ProtocolArray);
1237 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1238 ProtocolElements, ".objc_protocol_list"), PtrTy));
1239 Categories.push_back(llvm::ConstantExpr::getBitCast(
1240 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1241 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1242}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001243
Daniel Dunbar92992502008-08-15 22:20:32 +00001244void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001245 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1246 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001247 // Collect information about instance methods
1248 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1249 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001250 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001251 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001252 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001253 InstanceMethodSels.push_back((*iter)->getSelector());
1254 std::string TypeStr;
1255 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001256 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001257 }
1258
1259 // Collect information about class methods
1260 llvm::SmallVector<Selector, 16> ClassMethodSels;
1261 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001262 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001263 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001264 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001265 ClassMethodSels.push_back((*iter)->getSelector());
1266 std::string TypeStr;
1267 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001268 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001269 }
1270
1271 // Collect the names of referenced protocols
1272 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001273 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1274 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001275 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1276 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001277 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001278
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001279 std::vector<llvm::Constant*> Elements;
1280 Elements.push_back(MakeConstantString(CategoryName));
1281 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001282 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001283 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001284 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001285 false), PtrTy));
1286 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001287 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001288 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001289 PtrTy));
1290 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001291 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001292 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001293 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001294 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001295 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001296}
Daniel Dunbar92992502008-08-15 22:20:32 +00001297
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001298llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1299 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1300 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1301 ASTContext &Context = CGM.getContext();
1302 //
1303 // Property metadata: name, attributes, isSynthesized, setter name, setter
1304 // types, getter name, getter types.
1305 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1306 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1307 PtrToInt8Ty, NULL);
1308 std::vector<llvm::Constant*> Properties;
1309
1310
1311 // Add all of the property methods need adding to the method list and to the
1312 // property metadata list.
1313 for (ObjCImplDecl::propimpl_iterator
1314 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1315 iter != endIter ; iter++) {
1316 std::vector<llvm::Constant*> Fields;
1317 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001318 ObjCPropertyImplDecl *propertyImpl = *iter;
1319 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1320 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001321
1322 Fields.push_back(MakeConstantString(property->getNameAsString()));
1323 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1324 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001325 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001326 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001327 std::string TypeStr;
1328 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1329 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001330 if (isSynthesized) {
1331 InstanceMethodTypes.push_back(TypeEncoding);
1332 InstanceMethodSels.push_back(getter->getSelector());
1333 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001334 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1335 Fields.push_back(TypeEncoding);
1336 } else {
1337 Fields.push_back(NULLPtr);
1338 Fields.push_back(NULLPtr);
1339 }
1340 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001341 std::string TypeStr;
1342 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1343 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001344 if (isSynthesized) {
1345 InstanceMethodTypes.push_back(TypeEncoding);
1346 InstanceMethodSels.push_back(setter->getSelector());
1347 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001348 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1349 Fields.push_back(TypeEncoding);
1350 } else {
1351 Fields.push_back(NULLPtr);
1352 Fields.push_back(NULLPtr);
1353 }
1354 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1355 }
1356 llvm::ArrayType *PropertyArrayTy =
1357 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1358 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1359 Properties);
1360 llvm::Constant* PropertyListInitFields[] =
1361 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1362
1363 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001364 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001365 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1366 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1367 ".objc_property_list");
1368}
1369
Daniel Dunbar92992502008-08-15 22:20:32 +00001370void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1371 ASTContext &Context = CGM.getContext();
1372
1373 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001374 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001375 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001376 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001377 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001378 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001379 EmitClassRef(SuperClassName);
1380 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001381
1382 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001383 ObjCInterfaceDecl *ClassDecl =
1384 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001385 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001386 // Emit the symbol that is used to generate linker errors if this class is
1387 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001388 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001390 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001391 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001392 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001393 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001394 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001395 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Daniel Dunbar12119b92009-05-03 10:46:44 +00001398 // Get the size of instances.
1399 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar92992502008-08-15 22:20:32 +00001400
1401 // Collect information about instance variables.
1402 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1403 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1404 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001405
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001406 std::vector<llvm::Constant*> IvarOffsetValues;
1407
Mike Stump11289f42009-09-09 15:08:12 +00001408 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001409 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1410 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1411 // class}. The runtime will then set this to the correct value on load.
1412 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1413 instanceSize = 0 - (instanceSize - superInstanceSize);
1414 }
David Chisnall18cf7372010-04-19 00:45:34 +00001415
1416 // Collect declared and synthesized ivars.
1417 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1418 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1419
1420 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1421 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001422 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001423 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001424 // Get the type encoding for this ivar
1425 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001426 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001427 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001428 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001429 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001430 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001431 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001432 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001433 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001434 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001435 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001436 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1437 false, llvm::GlobalValue::ExternalLinkage,
1438 llvm::ConstantInt::get(IntTy, BaseOffset),
1439 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001440 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001441 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001442 llvm::Constant *IvarOffsetArrayInit =
1443 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1444 IvarOffsetValues.size()), IvarOffsetValues);
1445 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1446 IvarOffsetArrayInit->getType(), false,
1447 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1448 ".ivar.offsets");
Daniel Dunbar92992502008-08-15 22:20:32 +00001449
1450 // Collect information about instance methods
1451 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1452 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001453 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001454 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001455 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001456 InstanceMethodSels.push_back((*iter)->getSelector());
1457 std::string TypeStr;
1458 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001459 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001460 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001461
1462 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1463 InstanceMethodTypes);
1464
Daniel Dunbar92992502008-08-15 22:20:32 +00001465
1466 // Collect information about class methods
1467 llvm::SmallVector<Selector, 16> ClassMethodSels;
1468 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001469 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001470 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001471 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001472 ClassMethodSels.push_back((*iter)->getSelector());
1473 std::string TypeStr;
1474 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001475 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001476 }
1477 // Collect the names of referenced protocols
1478 llvm::SmallVector<std::string, 16> Protocols;
1479 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1480 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1481 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001482 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001483
1484
1485
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001486 // Get the superclass pointer.
1487 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001488 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001489 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1490 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001491 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001492 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001493 // Empty vector used to construct empty method lists
1494 llvm::SmallVector<llvm::Constant*, 1> empty;
1495 // Generate the method and instance variable lists
1496 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001497 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001498 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001499 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001500 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1501 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001502 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001503 // we emit a symbol containing the offset for each ivar in the class. This
1504 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1505 // for the legacy ABI, without causing problems. The converse is also
1506 // possible, but causes all ivar accesses to be fragile.
1507 int i = 0;
1508 // Offset pointer for getting at the correct field in the ivar list when
1509 // setting up the alias. These are: The base address for the global, the
1510 // ivar array (second field), the ivar in this list (set for each ivar), and
1511 // the offset (third field in ivar structure)
1512 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1513 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001514 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001515 llvm::ConstantInt::get(IndexTy, 2) };
1516
1517 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1518 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1519 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1520 +(*iter)->getNameAsString();
1521 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++);
1522 // Get the correct ivar field
1523 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1524 IvarList, offsetPointerIndexes, 4);
1525 // Get the existing alias, if one exists.
1526 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1527 if (offset) {
1528 offset->setInitializer(offsetValue);
1529 // If this is the real definition, change its linkage type so that
1530 // different modules will use this one, rather than their private
1531 // copy.
1532 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1533 } else {
1534 // Add a new alias if there isn't one already.
1535 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1536 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1537 }
1538 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001539 //Generate metaclass for class methods
1540 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001541 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001542 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001543
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001544 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001545 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001546 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001547 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001548 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001549 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1550 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001551
1552 // Resolve the class aliases, if they exist.
1553 if (ClassPtrAlias) {
1554 ClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001555 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001556 ClassPtrAlias = 0;
1557 }
1558 if (MetaClassPtrAlias) {
1559 MetaClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001560 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001561 MetaClassPtrAlias = 0;
1562 }
1563
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001564 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001565 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001566 Classes.push_back(ClassStruct);
1567}
1568
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001569
Mike Stump11289f42009-09-09 15:08:12 +00001570llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001571 // Only emit an ObjC load function if no Objective-C stuff has been called
1572 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1573 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov3b6dd582008-06-01 15:14:46 +00001574 UntypedSelectors.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001575 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001576
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001577 // Add all referenced protocols to a category.
1578 GenerateProtocolHolderCategory();
1579
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001580 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1581 SelectorTy->getElementType());
1582 const llvm::Type *SelStructPtrTy = SelectorTy;
1583 bool isSelOpaque = false;
1584 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001585 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1586 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001587 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001588 isSelOpaque = true;
1589 }
1590
Eli Friedman412c6682008-06-01 16:00:02 +00001591 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001592 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001593 TheModule.addTypeName(".objc_id", IdTy);
1594 TheModule.addTypeName(".objc_imp", IMPTy);
1595
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001596 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001597 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001598 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001599 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001600 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001601 ConstantStrings.size() + 1);
1602 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001603
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001604 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1605 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall5778fce2009-08-31 16:41:57 +00001606 Elements.push_back(MakeConstantString(StringClass,
1607 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001608 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001609 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001610 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001611 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001612 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001613 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001614 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001615 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001616 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001617 Elements.clear();
1618 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001619 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001620 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001621 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001622 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001623 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001624 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001625 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001626 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001627 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001628 llvm::Type::getInt16Ty(VMContext),
1629 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001630 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001631
1632 Elements.clear();
1633 // Pointer to an array of selectors used in this module.
1634 std::vector<llvm::Constant*> Selectors;
1635 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1636 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1637 iter != iterEnd ; ++iter) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001638 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnall29979822009-09-14 19:04:10 +00001639 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner63dd3372008-06-26 04:10:42 +00001640 ".objc_sel_types"));
Owen Anderson0e0189d2009-07-27 22:29:56 +00001641 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001642 Elements.clear();
1643 }
1644 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1645 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner63dd3372008-06-26 04:10:42 +00001646 iter != iterEnd; ++iter) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001647 Elements.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001648 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001649 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001650 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001651 Elements.clear();
1652 }
1653 Elements.push_back(NULLPtr);
1654 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001655 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001656 Elements.clear();
1657 // Number of static selectors
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001658 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001659 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001660 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001661 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00001662 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001663 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001664
1665 // Now that all of the static selectors exist, create pointers to them.
1666 int index = 0;
1667 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1668 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1669 iter != iterEnd; ++iter) {
1670 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001671 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar45858d22010-02-03 20:11:42 +00001672 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall0a24fd32010-05-08 20:58:05 +00001673 true, llvm::GlobalValue::LinkOnceAnyLinkage,
Daniel Dunbar45858d22010-02-03 20:11:42 +00001674 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
David Chisnall0a24fd32010-05-08 20:58:05 +00001675 ".objc_sel_ptr"+iter->first.first+"."+MangleSelectorTypes(iter->first.second));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001676 // If selectors are defined as an opaque type, cast the pointer to this
1677 // type.
1678 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001679 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1680 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001681 }
David Chisnall0a24fd32010-05-08 20:58:05 +00001682 (*iter).second->replaceAllUsesWith(SelPtr);
1683 (*iter).second->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001684 }
1685 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1686 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1687 iter != iterEnd; iter++) {
1688 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001689 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall0a24fd32010-05-08 20:58:05 +00001690 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
1691 true, llvm::GlobalValue::LinkOnceAnyLinkage,
1692 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1693 ".objc_sel_ptr"+iter->getKey());
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001694 // If selectors are defined as an opaque type, cast the pointer to this
1695 // type.
1696 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001697 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1698 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001699 }
David Chisnall0a24fd32010-05-08 20:58:05 +00001700 (*iter).second->replaceAllUsesWith(SelPtr);
1701 (*iter).second->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001702 }
1703 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00001704 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001705 Classes.size()));
1706 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00001707 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001708 Categories.size()));
1709 // Create an array of classes, then categories, then static object instances
1710 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1711 // NULL-terminated list of static object instances (mainly constant strings)
1712 Classes.push_back(Statics);
1713 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00001714 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001715 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00001716 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001717 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1718
1719 // The symbol table is contained in a module which has some version-checking
1720 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00001721 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001722 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001723 Elements.clear();
1724 // Runtime version used for compatibility checking.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001725 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump11289f42009-09-09 15:08:12 +00001726 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001727 NonFragileRuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001728 } else {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001729 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001730 }
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00001731 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00001732 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001733 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00001734 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001735 //FIXME: Should be the path to the file where this module was declared
1736 Elements.push_back(NULLPtr);
1737 Elements.push_back(SymTab);
1738 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1739
1740 // Create the load function calling the runtime entry point with the module
1741 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001742 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00001743 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001744 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1745 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00001746 llvm::BasicBlock *EntryBB =
1747 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00001748 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001749 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001750
1751 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001752 llvm::PointerType::getUnqual(ModuleTy));
1753 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00001754 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001755 Builder.CreateCall(Register, Module);
1756 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001757
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001758 return LoadFunction;
1759}
Daniel Dunbar92992502008-08-15 22:20:32 +00001760
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00001761llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00001762 const ObjCContainerDecl *CD) {
1763 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00001764 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattnere4b95692008-11-24 03:33:13 +00001765 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall12ae54d2010-03-20 19:53:29 +00001766 std::string ClassName = CD->getName();
Chris Lattnere4b95692008-11-24 03:33:13 +00001767 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorffca3a22009-01-09 17:18:27 +00001768 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00001769
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001770 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00001771 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001772 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001773 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1774 MethodName, isClassMethod);
1775
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001776 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00001777 = llvm::Function::Create(MethodTy,
1778 llvm::GlobalValue::InternalLinkage,
1779 FunctionName,
1780 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00001781 return Method;
1782}
1783
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001784llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001785 std::vector<const llvm::Type*> Params;
1786 const llvm::Type *BoolTy =
1787 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1788 Params.push_back(IdTy);
1789 Params.push_back(SelectorTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001790 Params.push_back(IntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001791 Params.push_back(BoolTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001792 // void objc_getProperty (id, SEL, int, bool)
Mike Stump11289f42009-09-09 15:08:12 +00001793 const llvm::FunctionType *FTy =
1794 llvm::FunctionType::get(IdTy, Params, false);
1795 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1796 "objc_getProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001797}
1798
1799llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001800 std::vector<const llvm::Type*> Params;
1801 const llvm::Type *BoolTy =
1802 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1803 Params.push_back(IdTy);
1804 Params.push_back(SelectorTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001805 Params.push_back(IntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001806 Params.push_back(IdTy);
1807 Params.push_back(BoolTy);
1808 Params.push_back(BoolTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001809 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump11289f42009-09-09 15:08:12 +00001810 const llvm::FunctionType *FTy =
1811 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1812 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1813 "objc_setProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001814}
1815
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001816// FIXME. Implement this.
1817llvm::Function *CGObjCGNU::GetCopyStructFunction() {
1818 return 0;
1819}
1820
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001821llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1822 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1823 ASTContext &Ctx = CGM.getContext();
1824 // void objc_enumerationMutation (id)
John McCall2da83a32010-02-26 00:48:12 +00001825 llvm::SmallVector<CanQualType,1> Params;
David Chisnall9f57c292009-08-17 16:35:33 +00001826 Params.push_back(ASTIdTy);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001827 const llvm::FunctionType *FTy =
John McCallab26cfa2010-02-05 21:31:56 +00001828 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001829 FunctionType::ExtInfo()), false);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001830 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001831}
1832
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00001833void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1834 const Stmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001835 // Pointer to the personality function
1836 llvm::Constant *Personality =
Owen Anderson41a75022009-08-13 21:57:51 +00001837 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(VMContext),
Chris Lattner3dd1b4b2009-07-01 04:13:52 +00001838 true),
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001839 "__gnu_objc_personality_v0");
Owen Andersonade90fd2009-07-29 18:54:39 +00001840 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001841 std::vector<const llvm::Type*> Params;
1842 Params.push_back(PtrTy);
1843 llvm::Value *RethrowFn =
Owen Anderson41a75022009-08-13 21:57:51 +00001844 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
David Chisnall9a2073c2010-01-06 18:02:59 +00001845 Params, false), "_Unwind_Resume");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001846
1847 bool isTry = isa<ObjCAtTryStmt>(S);
1848 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1849 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1850 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Chris Lattner9fea9442009-05-11 18:16:28 +00001851 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001852 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1853 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1854 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1855
David Chisnall3a509cd2009-12-24 02:26:34 +00001856 // @synchronized()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001857 if (!isTry) {
Chris Lattner9fea9442009-05-11 18:16:28 +00001858 std::vector<const llvm::Type*> Args(1, IdTy);
1859 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001860 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00001861 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
Mike Stump11289f42009-09-09 15:08:12 +00001862 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00001863 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1864 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1865 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001866 }
1867
Chris Lattner9fea9442009-05-11 18:16:28 +00001868
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001869 // Push an EH context entry, used for handling rethrows and jumps
1870 // through finally.
1871 CGF.PushCleanupBlock(FinallyBlock);
1872
1873 // Emit the statements in the @try {} block
1874 CGF.setInvokeDest(TryHandler);
1875
1876 CGF.EmitBlock(TryBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001877 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001878 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1879
1880 // Jump to @finally if there is no exception
1881 CGF.EmitBranchThroughCleanup(FinallyEnd);
1882
1883 // Emit the handlers
1884 CGF.EmitBlock(TryHandler);
1885
Chris Lattner96afab52009-05-08 17:36:08 +00001886 // Get the correct versions of the exception handling intrinsics
Mike Stump11289f42009-09-09 15:08:12 +00001887 llvm::Value *llvm_eh_exception =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001888 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
Duncan Sandscef56992009-10-14 16:13:30 +00001889 llvm::Value *llvm_eh_selector =
1890 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
1891 llvm::Value *llvm_eh_typeid_for =
1892 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001893
1894 // Exception object
1895 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1896 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1897
1898 llvm::SmallVector<llvm::Value*, 8> ESelArgs;
Douglas Gregor46a572b2010-04-26 16:46:50 +00001899 llvm::SmallVector<std::pair<const VarDecl*, const Stmt*>, 8> Handlers;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001900
1901 ESelArgs.push_back(Exc);
1902 ESelArgs.push_back(Personality);
1903
1904 bool HasCatchAll = false;
1905 // Only @try blocks are allowed @catch blocks, but both can have @finally
1906 if (isTry) {
Douglas Gregor96c79492010-04-23 22:50:49 +00001907 if (cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
1908 const ObjCAtTryStmt &AtTry = cast<ObjCAtTryStmt>(S);
Chris Lattner9fea9442009-05-11 18:16:28 +00001909 CGF.setInvokeDest(CatchInCatch);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001910
Douglas Gregor96c79492010-04-23 22:50:49 +00001911 for (unsigned I = 0, N = AtTry.getNumCatchStmts(); I != N; ++I) {
1912 const ObjCAtCatchStmt *CatchStmt = AtTry.getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001913 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Mike Stumpdd93a192009-07-31 21:31:32 +00001914 Handlers.push_back(std::make_pair(CatchDecl,
1915 CatchStmt->getCatchBody()));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001916
1917 // @catch() and @catch(id) both catch any ObjC exception
Steve Naroff7cae42b2009-07-10 23:34:53 +00001918 if (!CatchDecl || CatchDecl->getType()->isObjCIdType()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001919 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1920 // Use i8* null here to signal this is a catch all, not a cleanup.
1921 ESelArgs.push_back(NULLPtr);
1922 HasCatchAll = true;
1923 // No further catches after this one will ever by reached
1924 break;
Mike Stump11289f42009-09-09 15:08:12 +00001925 }
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001926
1927 // All other types should be Objective-C interface pointer types.
Mike Stump11289f42009-09-09 15:08:12 +00001928 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00001929 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001930 assert(OPT && "Invalid @catch type.");
Mike Stump11289f42009-09-09 15:08:12 +00001931 const ObjCInterfaceType *IT =
John McCall9dd450b2009-09-21 23:43:11 +00001932 OPT->getPointeeType()->getAs<ObjCInterfaceType>();
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001933 assert(IT && "Invalid @catch type.");
Chris Lattner96afab52009-05-08 17:36:08 +00001934 llvm::Value *EHType =
1935 MakeConstantString(IT->getDecl()->getNameAsString());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001936 ESelArgs.push_back(EHType);
1937 }
1938 }
1939 }
1940
1941 // We use a cleanup unless there was already a catch all.
1942 if (!HasCatchAll) {
Owen Anderson41a75022009-08-13 21:57:51 +00001943 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001944 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1945 }
1946
1947 // Find which handler was matched.
Chris Lattner96afab52009-05-08 17:36:08 +00001948 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001949 ESelArgs.begin(), ESelArgs.end(), "selector");
1950
1951 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Douglas Gregor46a572b2010-04-26 16:46:50 +00001952 const VarDecl *CatchParam = Handlers[i].first;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001953 const Stmt *CatchBody = Handlers[i].second;
1954
1955 llvm::BasicBlock *Next = 0;
1956
1957 // The last handler always matches.
1958 if (i + 1 != e) {
1959 assert(CatchParam && "Only last handler can be a catch all.");
1960
1961 // Test whether this block matches the type for the selector and branch
1962 // to Match if it does, or to the next BB if it doesn't.
1963 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1964 Next = CGF.createBasicBlock("catch.next");
Chris Lattner96afab52009-05-08 17:36:08 +00001965 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001966 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1967 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1968 Next);
1969
1970 CGF.EmitBlock(Match);
1971 }
Mike Stump11289f42009-09-09 15:08:12 +00001972
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001973 if (CatchBody) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001974 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1975 CGF.ConvertType(CatchParam->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001977 // Bind the catch parameter if it exists.
1978 if (CatchParam) {
1979 // CatchParam is a ParmVarDecl because of the grammar
1980 // construction used to handle this, but for codegen purposes
1981 // we treat this as a local decl.
1982 CGF.EmitLocalBlockVarDecl(*CatchParam);
1983 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1984 }
1985
1986 CGF.ObjCEHValueStack.push_back(ExcObject);
1987 CGF.EmitStmt(CatchBody);
1988 CGF.ObjCEHValueStack.pop_back();
1989
1990 CGF.EmitBranchThroughCleanup(FinallyEnd);
1991
1992 if (Next)
1993 CGF.EmitBlock(Next);
1994 } else {
1995 assert(!Next && "catchup should be last handler.");
1996
1997 CGF.Builder.CreateStore(Exc, RethrowPtr);
1998 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1999 }
2000 }
Chris Lattner9fea9442009-05-11 18:16:28 +00002001 // The @finally block is a secondary landing pad for any exceptions thrown in
2002 // @catch() blocks
2003 CGF.EmitBlock(CatchInCatch);
2004 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
2005 ESelArgs.clear();
2006 ESelArgs.push_back(Exc);
2007 ESelArgs.push_back(Personality);
David Chisnall3a509cd2009-12-24 02:26:34 +00002008 // If there is a @catch or @finally clause in outside of this one then we
2009 // need to make sure that we catch and rethrow it.
2010 if (PrevLandingPad) {
2011 ESelArgs.push_back(NULLPtr);
2012 } else {
2013 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
2014 }
Chris Lattner9fea9442009-05-11 18:16:28 +00002015 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
2016 "selector");
2017 CGF.Builder.CreateCall(llvm_eh_typeid_for,
2018 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
2019 CGF.Builder.CreateStore(Exc, RethrowPtr);
2020 CGF.EmitBranchThroughCleanup(FinallyRethrow);
2021
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002022 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2023
2024 CGF.setInvokeDest(PrevLandingPad);
2025
2026 CGF.EmitBlock(FinallyBlock);
2027
Chris Lattner9fea9442009-05-11 18:16:28 +00002028
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002029 if (isTry) {
Mike Stump11289f42009-09-09 15:08:12 +00002030 if (const ObjCAtFinallyStmt* FinallyStmt =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002031 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2032 CGF.EmitStmt(FinallyStmt->getFinallyBody());
2033 } else {
Chris Lattner9fea9442009-05-11 18:16:28 +00002034 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002035 // @synchronized.
Chris Lattner9fea9442009-05-11 18:16:28 +00002036 std::vector<const llvm::Type*> Args(1, IdTy);
2037 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00002038 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00002039 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Mike Stump11289f42009-09-09 15:08:12 +00002040 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00002041 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2042 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
2043 CGF.Builder.CreateCall(SyncExit, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002044 }
2045
2046 if (Info.SwitchBlock)
2047 CGF.EmitBlock(Info.SwitchBlock);
2048 if (Info.EndBlock)
2049 CGF.EmitBlock(Info.EndBlock);
2050
2051 // Branch around the rethrow code.
2052 CGF.EmitBranch(FinallyEnd);
2053
2054 CGF.EmitBlock(FinallyRethrow);
David Chisnall3a509cd2009-12-24 02:26:34 +00002055
2056 llvm::Value *ExceptionObject = CGF.Builder.CreateLoad(RethrowPtr);
2057 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2058 if (!UnwindBB) {
2059 CGF.Builder.CreateCall(RethrowFn, ExceptionObject);
2060 // Exception always thrown, next instruction is never reached.
2061 CGF.Builder.CreateUnreachable();
2062 } else {
2063 // If there is a @catch block outside this scope, we invoke instead of
2064 // calling because we may return to this function. This is very slow, but
2065 // some people still do it. It would be nice to add an optimised path for
2066 // this.
2067 CGF.Builder.CreateInvoke(RethrowFn, UnwindBB, UnwindBB, &ExceptionObject,
2068 &ExceptionObject+1);
2069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002071 CGF.EmitBlock(FinallyEnd);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002072}
2073
2074void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002075 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002076 llvm::Value *ExceptionAsObject;
2077
2078 std::vector<const llvm::Type*> Args(1, IdTy);
2079 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00002080 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump11289f42009-09-09 15:08:12 +00002081 llvm::Value *ThrowFn =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002082 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002084 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2085 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002086 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002087 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002088 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002089 "Unexpected rethrow outside @catch block.");
2090 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2091 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002092 ExceptionAsObject =
2093 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002094
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002095 // Note: This may have to be an invoke, if we want to support constructs like:
2096 // @try {
2097 // @throw(obj);
2098 // }
2099 // @catch(id) ...
2100 //
2101 // This is effectively turning @throw into an incredibly-expensive goto, but
2102 // it may happen as a result of inlining followed by missed optimizations, or
2103 // as a result of stupidity.
2104 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2105 if (!UnwindBB) {
2106 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2107 CGF.Builder.CreateUnreachable();
2108 } else {
2109 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2110 &ExceptionAsObject+1);
2111 }
2112 // Clear the insertion point to indicate we are in unreachable code.
2113 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002114}
2115
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002116llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002117 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002118 CGBuilderTy B = CGF.Builder;
2119 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2120 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002121}
2122
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002123void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002124 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002125 CGBuilderTy B = CGF.Builder;
2126 src = EnforceType(B, src, IdTy);
2127 dst = EnforceType(B, dst, PtrToIdTy);
2128 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002129}
2130
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002131void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002132 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002133 CGBuilderTy B = CGF.Builder;
2134 src = EnforceType(B, src, IdTy);
2135 dst = EnforceType(B, dst, PtrToIdTy);
2136 B.CreateCall2(GlobalAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002137}
2138
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002139void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002140 llvm::Value *src, llvm::Value *dst,
2141 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002142 CGBuilderTy B = CGF.Builder;
2143 src = EnforceType(B, src, IdTy);
2144 dst = EnforceType(B, dst, PtrToIdTy);
2145 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002146}
2147
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002148void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002149 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002150 CGBuilderTy B = CGF.Builder;
2151 src = EnforceType(B, src, IdTy);
2152 dst = EnforceType(B, dst, PtrToIdTy);
2153 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002154}
2155
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002156void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002157 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002158 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +00002159 QualType Ty) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002160 CGBuilderTy B = CGF.Builder;
2161 DestPtr = EnforceType(B, DestPtr, IdTy);
2162 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2163
2164 std::pair<uint64_t, unsigned> TypeInfo = CGM.getContext().getTypeInfo(Ty);
2165 unsigned long size = TypeInfo.first/8;
2166 // FIXME: size_t
2167 llvm::Value *N = llvm::ConstantInt::get(LongTy, size);
2168
2169 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, N);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002170}
2171
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002172llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2173 const ObjCInterfaceDecl *ID,
2174 const ObjCIvarDecl *Ivar) {
2175 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2176 + '.' + Ivar->getNameAsString();
2177 // Emit the variable and initialize it with what we think the correct value
2178 // is. This allows code compiled with non-fragile ivars to work correctly
2179 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002180 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2181 if (!IvarOffsetPointer) {
David Chisnall44ec5552010-04-19 01:37:25 +00002182 uint64_t Offset;
2183 if (ObjCImplementationDecl *OID =
Dan Gohman145f3f12010-04-19 16:39:44 +00002184 CGM.getContext().getObjCImplementation(
2185 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002186 Offset = ComputeIvarBaseOffset(CGM, OID, Ivar);
2187 else
2188 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2189
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002190 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002191 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002192 // Don't emit the guess in non-PIC code because the linker will not be able
2193 // to replace it with the real version for a library. In non-PIC code you
2194 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002195 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002196 if (CGM.getLangOptions().PICLevel) {
2197 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2198 llvm::Type::getInt32Ty(VMContext), false,
2199 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2200 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2201 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2202 IvarOffsetGV, Name);
2203 } else {
2204 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002205 llvm::Type::getInt32PtrTy(VMContext), false,
2206 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002207 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002208 }
David Chisnall5778fce2009-08-31 16:41:57 +00002209 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002210}
2211
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002212LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2213 QualType ObjectTy,
2214 llvm::Value *BaseValue,
2215 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002216 unsigned CVRQualifiers) {
John McCall9dd450b2009-09-21 23:43:11 +00002217 const ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCInterfaceType>()->getDecl();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002218 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2219 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002220}
Mike Stumpdd93a192009-07-31 21:31:32 +00002221
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002222static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2223 const ObjCInterfaceDecl *OID,
2224 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002225 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002226 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002227 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2228 if (OIVD == Ivars[k])
2229 return OID;
2230 }
Mike Stump11289f42009-09-09 15:08:12 +00002231
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002232 // Otherwise check in the super class.
2233 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2234 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002235
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002236 return 0;
2237}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002238
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002239llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002240 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002241 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002242 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002243 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall5778fce2009-08-31 16:41:57 +00002244 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2245 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002246 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002247 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002248 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002249}
2250
Mike Stumpdd93a192009-07-31 21:31:32 +00002251CodeGen::CGObjCRuntime *
2252CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattner87ab27d2008-06-26 04:19:03 +00002253 return new CGObjCGNU(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002254}