blob: b7cfa6c8ac12b634172e4dd8f980fc567e8c6f86 [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;
David Chisnalle0b5b3a2010-05-09 01:01:43 +0000240 // Simple mangling to avoid breaking when we mix JIT / static code.
241 // Not part of the ABI, subject to change without notice.
David Chisnall0a24fd32010-05-08 20:58:05 +0000242 std::replace(Mangled.begin(), Mangled.end(), '@', '_');
David Chisnalle0b5b3a2010-05-09 01:01:43 +0000243 std::replace(Mangled.begin(), Mangled.end(), ':', 'J');
244 std::replace(Mangled.begin(), Mangled.end(), '*', 'e');
245 std::replace(Mangled.begin(), Mangled.end(), '#', 'E');
246 std::replace(Mangled.begin(), Mangled.end(), ':', 'j');
247 std::replace(Mangled.begin(), Mangled.end(), '(', 'g');
248 std::replace(Mangled.begin(), Mangled.end(), ')', 'G');
249 std::replace(Mangled.begin(), Mangled.end(), '[', 'h');
250 std::replace(Mangled.begin(), Mangled.end(), ']', 'H');
David Chisnall0a24fd32010-05-08 20:58:05 +0000251 return Mangled;
252}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000253
Chris Lattner87ab27d2008-06-26 04:19:03 +0000254CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar566421c2009-05-04 15:31:17 +0000255 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Anderson170229f2009-07-14 23:10:40 +0000256 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnall01aa4672010-04-28 19:33:36 +0000257
258 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
259
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000260 IntTy = cast<llvm::IntegerType>(
261 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
262 LongTy = cast<llvm::IntegerType>(
263 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Mike Stump11289f42009-09-09 15:08:12 +0000264
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000265 Int8Ty = llvm::Type::getInt8Ty(VMContext);
266 // C string type. Used in lots of places.
267 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
268
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000269 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000270 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000271 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000272 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000273 QualType selTy = CGM.getContext().getObjCSelType();
274 if (QualType() == selTy) {
275 SelectorTy = PtrToInt8Ty;
276 } else {
277 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
278 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000279
Owen Anderson9793f0e2009-07-29 22:16:19 +0000280 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000281 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattner4bd55962008-03-30 23:03:07 +0000283 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000284 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000285 if (QualType() == ASTIdTy) {
286 IdTy = PtrToInt8Ty;
287 } else {
288 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
289 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000290 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner4bd55962008-03-30 23:03:07 +0000292 // IMP type
293 std::vector<const llvm::Type*> IMPArgs;
294 IMPArgs.push_back(IdTy);
295 IMPArgs.push_back(SelectorTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000296 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000297
298 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
299 // Get selectors needed in GC mode
300 RetainSel = GetNullarySelector("retain", CGM.getContext());
301 ReleaseSel = GetNullarySelector("release", CGM.getContext());
302 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
303
304 // Get functions needed in GC mode
305
306 // id objc_assign_ivar(id, id, ptrdiff_t);
307 std::vector<const llvm::Type*> Args(1, IdTy);
308 Args.push_back(PtrToIdTy);
309 // FIXME: ptrdiff_t
310 Args.push_back(LongTy);
311 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
312 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
313 // id objc_assign_strongCast (id, id*)
314 Args.pop_back();
315 FTy = llvm::FunctionType::get(IdTy, Args, false);
316 StrongCastAssignFn =
317 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
318 // id objc_assign_global(id, id*);
319 FTy = llvm::FunctionType::get(IdTy, Args, false);
320 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
321 // id objc_assign_weak(id, id*);
322 FTy = llvm::FunctionType::get(IdTy, Args, false);
323 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
324 // id objc_read_weak(id*);
325 Args.clear();
326 Args.push_back(PtrToIdTy);
327 FTy = llvm::FunctionType::get(IdTy, Args, false);
328 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
329 // void *objc_memmove_collectable(void*, void *, size_t);
330 Args.clear();
331 Args.push_back(PtrToInt8Ty);
332 Args.push_back(PtrToInt8Ty);
333 // FIXME: size_t
334 Args.push_back(LongTy);
335 FTy = llvm::FunctionType::get(IdTy, Args, false);
336 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
337 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000338}
Mike Stumpdd93a192009-07-31 21:31:32 +0000339
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000340// This has to perform the lookup every time, since posing and related
341// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000342llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000343 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000344 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000345 // With the incompatible ABI, this will need to be replaced with a direct
346 // reference to the class symbol. For the compatible nonfragile ABI we are
347 // still performing this lookup at run time but emitting the symbol for the
348 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000349 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000350 ClassName = Builder.CreateStructGEP(ClassName, 0);
351
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000352 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000353 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000354 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000355 Params,
356 true),
357 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000358 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000359}
360
Daniel Dunbar45858d22010-02-03 20:11:42 +0000361llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Chris Lattnere4b95692008-11-24 03:33:13 +0000362 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner6d522c02008-06-26 04:37:12 +0000363 if (US == 0)
Daniel Dunbar45858d22010-02-03 20:11:42 +0000364 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall9f57c292009-08-17 16:35:33 +0000365 llvm::GlobalValue::PrivateLinkage,
366 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner6d522c02008-06-26 04:37:12 +0000367 NULL, &TheModule);
Mike Stump11289f42009-09-09 15:08:12 +0000368
Daniel Dunbar45858d22010-02-03 20:11:42 +0000369 return Builder.CreateLoad(US);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000370}
371
Daniel Dunbar45858d22010-02-03 20:11:42 +0000372llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000373 *Method) {
374
375 std::string SelName = Method->getSelector().getAsString();
376 std::string SelTypes;
377 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
378 // Typed selectors
379 TypedSelector Selector = TypedSelector(SelName,
380 SelTypes);
381
382 // If it's already cached, return it.
Mike Stumpdd93a192009-07-31 21:31:32 +0000383 if (TypedSelectors[Selector]) {
Daniel Dunbar45858d22010-02-03 20:11:42 +0000384 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000385 }
386
387 // If it isn't, cache it.
388 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar45858d22010-02-03 20:11:42 +0000389 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall9f57c292009-08-17 16:35:33 +0000390 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000391 NULL, &TheModule);
392 TypedSelectors[Selector] = Sel;
393
Daniel Dunbar45858d22010-02-03 20:11:42 +0000394 return Builder.CreateLoad(Sel);
Chris Lattner6d522c02008-06-26 04:37:12 +0000395}
396
Chris Lattnerd9b98862008-06-26 04:44:19 +0000397llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
398 const std::string &Name) {
David Chisnall5778fce2009-08-31 16:41:57 +0000399 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Andersonade90fd2009-07-29 18:54:39 +0000400 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000401}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000402llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
403 const std::string prefix) {
404 std::string name = prefix + Str;
405 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
406 if (!ConstStr) {
407 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
408 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
409 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
410 }
411 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
412}
Mike Stumpdd93a192009-07-31 21:31:32 +0000413
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000414llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000415 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000416 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson0e0189d2009-07-27 22:29:56 +0000417 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000418 return new llvm::GlobalVariable(TheModule, Ty, false,
419 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000420}
Mike Stumpdd93a192009-07-31 21:31:32 +0000421
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000422llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000423 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000424 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson47034e12009-07-28 18:33:04 +0000425 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000426 return new llvm::GlobalVariable(TheModule, Ty, false,
Mike Stumpdd93a192009-07-31 21:31:32 +0000427 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000428}
429
430/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000431llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000432
David Chisnall481e3a82010-01-23 02:40:42 +0000433 std::string Str(SL->getStrData(), SL->getByteLength());
434
David Chisnall358e7512010-01-27 12:49:23 +0000435 // Look for an existing one
436 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
437 if (old != ObjCStrings.end())
438 return old->getValue();
439
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000440 std::vector<llvm::Constant*> Ivars;
441 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000442 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000443 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000444 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000445 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000446 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000447 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
448 ObjCStrings[Str] = ObjCStr;
449 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000450 return ObjCStr;
451}
452
453///Generates a message send where the super is the receiver. This is a message
454///send to self with special delivery semantics indicating which class's method
455///should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000456CodeGen::RValue
457CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000458 QualType ResultType,
459 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000460 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000461 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000462 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000463 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000464 const CallArgList &CallArgs,
465 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000466 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
467 if (Sel == RetainSel || Sel == AutoreleaseSel) {
468 return RValue::get(Receiver);
469 }
470 if (Sel == ReleaseSel) {
471 return RValue::get(0);
472 }
473 }
David Chisnallea529a42010-05-01 12:37:16 +0000474
475 CGBuilderTy &Builder = CGF.Builder;
476 llvm::Value *cmd = GetSelector(Builder, Sel);
477
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000478
479 CallArgList ActualArgs;
480
481 ActualArgs.push_back(
David Chisnallea529a42010-05-01 12:37:16 +0000482 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall9f57c292009-08-17 16:35:33 +0000483 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000484 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
485 CGF.getContext().getObjCSelType()));
486 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
487
488 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000489 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000490 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000491 const llvm::FunctionType *impType =
492 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000493
Daniel Dunbar566421c2009-05-04 15:31:17 +0000494 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000495 if (isCategoryImpl) {
496 llvm::Constant *classLookupFunction = 0;
497 std::vector<const llvm::Type*> Params;
498 Params.push_back(PtrTy);
499 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000500 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000501 IdTy, Params, true), "objc_get_meta_class");
502 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000503 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000504 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000505 }
David Chisnallea529a42010-05-01 12:37:16 +0000506 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000507 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000508 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000509 // Set up global aliases for the metaclass or class pointer if they do not
510 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000511 // pointers to the class and metaclass structure created for the runtime
512 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000513 // super_class pointer from either the class or metaclass structure.
514 if (IsClassMessage) {
515 if (!MetaClassPtrAlias) {
516 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
517 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
518 Class->getNameAsString(), NULL, &TheModule);
519 }
520 ReceiverClass = MetaClassPtrAlias;
521 } else {
522 if (!ClassPtrAlias) {
523 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
524 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
525 Class->getNameAsString(), NULL, &TheModule);
526 }
527 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000528 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000529 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000530 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +0000531 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000532 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000533 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000534 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000535 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +0000536 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000537 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000538 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000539 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
540 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +0000541 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000542
David Chisnallea529a42010-05-01 12:37:16 +0000543 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
544 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000545
546 // Get the IMP
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000547 std::vector<const llvm::Type*> Params;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000548 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000549 Params.push_back(SelectorTy);
David Chisnallea529a42010-05-01 12:37:16 +0000550
551 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
552 llvm::Value *imp;
553
554 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
555 // The lookup function returns a slot, which can be safely cached.
556 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
557 IntTy, llvm::PointerType::getUnqual(impType), NULL);
558
559 llvm::Constant *lookupFunction =
560 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
561 llvm::PointerType::getUnqual(SlotTy), Params, true),
562 "objc_slot_lookup_super");
563
564 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
565 lookupArgs+2);
566 slot->setOnlyReadsMemory();
567
568 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
569 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000570 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000571 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
572 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000573 "objc_msg_lookup_super");
David Chisnallea529a42010-05-01 12:37:16 +0000574 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
575 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000576
David Chisnall9eecafa2010-05-01 11:15:56 +0000577 llvm::Value *impMD[] = {
578 llvm::MDString::get(VMContext, Sel.getAsString()),
579 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
580 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
581 };
582 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
583
David Chisnallff5f88c2010-05-02 13:41:58 +0000584 llvm::Instruction *call;
585 RValue msgRet = CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs,
586 0, &call);
587 call->setMetadata(msgSendMDKind, node);
588 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000589}
590
Mike Stump11289f42009-09-09 15:08:12 +0000591/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000592CodeGen::RValue
593CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000594 QualType ResultType,
595 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000596 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000597 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000598 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000599 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +0000600 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000601 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
602 if (Sel == RetainSel || Sel == AutoreleaseSel) {
603 return RValue::get(Receiver);
604 }
605 if (Sel == ReleaseSel) {
606 return RValue::get(0);
607 }
608 }
David Chisnall75afda62010-04-27 15:08:48 +0000609
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000610 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +0000611
612 // If the return type is something that goes in an integer register, the
613 // runtime will handle 0 returns. For other cases, we fill in the 0 value
614 // ourselves.
615 //
616 // The language spec says the result of this kind of message send is
617 // undefined, but lots of people seem to have forgotten to read that
618 // paragraph and insist on sending messages to nil that have structure
619 // returns. With GCC, this generates a random return value (whatever happens
620 // to be on the stack / in those registers at the time) on most platforms,
621 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
622 bool isPointerSizedReturn = false;
David Chisnalle6d00732010-04-27 20:33:30 +0000623 if (ResultType->isAnyPointerType() || ResultType->isIntegralType() ||
624 ResultType->isVoidType())
David Chisnall75afda62010-04-27 15:08:48 +0000625 isPointerSizedReturn = true;
626
627 llvm::BasicBlock *startBB = 0;
628 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +0000629 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +0000630
631 if (!isPointerSizedReturn) {
632 startBB = Builder.GetInsertBlock();
633 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +0000634 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +0000635
636 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
637 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +0000638 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +0000639 CGF.EmitBlock(messageBB);
640 }
641
David Chisnall9f57c292009-08-17 16:35:33 +0000642 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000643 llvm::Value *cmd;
644 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000645 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000646 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000647 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000648 CallArgList ActualArgs;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000649
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000650 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000651 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000652 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000653 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
654 CGF.getContext().getObjCSelType()));
655 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
656
657 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000658 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000659 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000660 const llvm::FunctionType *impType =
661 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000662
David Chisnallc0cf4222010-05-01 12:56:56 +0000663 llvm::Value *impMD[] = {
664 llvm::MDString::get(VMContext, Sel.getAsString()),
665 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
666 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
667 };
668 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
669
670
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000671 llvm::Value *imp;
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000672 // For sender-aware dispatch, we pass the sender as the third argument to a
673 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000674 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
675 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
676
677 std::vector<const llvm::Type*> Params;
678 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
679 Builder.CreateStore(Receiver, ReceiverPtr);
680 Params.push_back(ReceiverPtr->getType());
681 Params.push_back(SelectorTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000682 llvm::Value *self;
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000683
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000684 if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
685 self = CGF.LoadObjCSelf();
686 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +0000687 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000688 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000689
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000690 Params.push_back(self->getType());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000691
692 // The lookup function returns a slot, which can be safely cached.
693 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
694 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000695 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000696 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000697 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000698 "objc_msg_lookup_sender");
699
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000700 // The lookup function is guaranteed not to capture the receiver pointer.
701 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
702 LookupFn->setDoesNotCapture(1);
703 }
704
David Chisnalld6a6af62010-04-30 13:36:12 +0000705 llvm::CallInst *slot =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000706 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnalld6a6af62010-04-30 13:36:12 +0000707 slot->setOnlyReadsMemory();
David Chisnallc0cf4222010-05-01 12:56:56 +0000708 slot->setMetadata(msgSendMDKind, node);
David Chisnalld6a6af62010-04-30 13:36:12 +0000709
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000710 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnall01aa4672010-04-28 19:33:36 +0000711
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000712 // The lookup function may have changed the receiver, so make sure we use
713 // the new one.
714 ActualArgs[0] =
715 std::make_pair(RValue::get(Builder.CreateLoad(ReceiverPtr)), ASTIdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000716 } else {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000717 std::vector<const llvm::Type*> Params;
718 Params.push_back(Receiver->getType());
719 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000720 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000721 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
722 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000723 "objc_msg_lookup");
724
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000725 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnallc0cf4222010-05-01 12:56:56 +0000726 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000727 }
David Chisnallff5f88c2010-05-02 13:41:58 +0000728 llvm::Instruction *call;
David Chisnall9eecafa2010-05-01 11:15:56 +0000729 RValue msgRet = CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000730 0, &call);
731 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +0000732
David Chisnall29cefd12010-05-20 13:45:48 +0000733
David Chisnall75afda62010-04-27 15:08:48 +0000734 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +0000735 messageBB = CGF.Builder.GetInsertBlock();
736 CGF.Builder.CreateBr(continueBB);
737 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +0000738 if (msgRet.isScalar()) {
739 llvm::Value *v = msgRet.getScalarVal();
740 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
741 phi->addIncoming(v, messageBB);
742 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
743 msgRet = RValue::get(phi);
744 } else if (msgRet.isAggregate()) {
745 llvm::Value *v = msgRet.getAggregateAddr();
746 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
747 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +0000748 llvm::AllocaInst *NullVal =
749 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +0000750 CGF.InitTempAlloca(NullVal,
751 llvm::Constant::getNullValue(RetTy->getElementType()));
752 phi->addIncoming(v, messageBB);
753 phi->addIncoming(NullVal, startBB);
754 msgRet = RValue::getAggregate(phi);
755 } else /* isComplex() */ {
756 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
757 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
758 phi->addIncoming(v.first, messageBB);
759 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
760 startBB);
761 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
762 phi2->addIncoming(v.second, messageBB);
763 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
764 startBB);
765 msgRet = RValue::getComplex(phi, phi2);
766 }
767 }
768 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000769}
770
Mike Stump11289f42009-09-09 15:08:12 +0000771/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000772/// objc_category structures.
773llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump11289f42009-09-09 15:08:12 +0000774 const std::string &CategoryName,
775 const llvm::SmallVectorImpl<Selector> &MethodSels,
776 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000777 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +0000778 if (MethodSels.empty())
779 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000780 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000781 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000782 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
783 PtrToInt8Ty, // Method types
Owen Anderson9793f0e2009-07-29 22:16:19 +0000784 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000785 NULL);
786 std::vector<llvm::Constant*> Methods;
787 std::vector<llvm::Constant*> Elements;
788 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
789 Elements.clear();
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000790 if (llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000791 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnere4b95692008-11-24 03:33:13 +0000792 MethodSels[i].getAsString(),
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000793 isClassMethodList))) {
David Chisnall5778fce2009-08-31 16:41:57 +0000794 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
795 Elements.push_back(C);
796 Elements.push_back(MethodTypes[i]);
Owen Andersonade90fd2009-07-29 18:54:39 +0000797 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000798 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000799 Elements.push_back(Method);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000800 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000801 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000802 }
803
804 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000805 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000806 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000807 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +0000808 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000809
810 // Structure containing list pointer, array and array count
811 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +0000812 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000813 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +0000814 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +0000815 NextPtrTy,
816 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000817 ObjCMethodArrayTy,
818 NULL);
819 // Refine next pointer type to concrete type
820 llvm::cast<llvm::OpaqueType>(
821 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
822 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
823
824 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +0000825 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +0000826 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +0000827 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000828 MethodTypes.size()));
829 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000831 // Create an instance of the structure
832 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
833}
834
835/// Generates an IvarList. Used in construction of a objc_class.
836llvm::Constant *CGObjCGNU::GenerateIvarList(
837 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
838 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
839 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +0000840 if (IvarNames.size() == 0)
841 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000842 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000843 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000844 PtrToInt8Ty,
845 PtrToInt8Ty,
846 IntTy,
847 NULL);
848 std::vector<llvm::Constant*> Ivars;
849 std::vector<llvm::Constant*> Elements;
850 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
851 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +0000852 Elements.push_back(IvarNames[i]);
853 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000854 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000855 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000856 }
857
858 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000859 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000860 IvarNames.size());
861
Mike Stump11289f42009-09-09 15:08:12 +0000862
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000863 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000864 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +0000865 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000866 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +0000867 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000868 ObjCIvarArrayTy,
869 NULL);
870
871 // Create an instance of the structure
872 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
873}
874
875/// Generate a class structure
876llvm::Constant *CGObjCGNU::GenerateClassStructure(
877 llvm::Constant *MetaClass,
878 llvm::Constant *SuperClass,
879 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000880 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000881 llvm::Constant *Version,
882 llvm::Constant *InstanceSize,
883 llvm::Constant *IVars,
884 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000885 llvm::Constant *Protocols,
886 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000887 llvm::Constant *Properties,
888 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000889 // Set up the class structure
890 // Note: Several of these are char*s when they should be ids. This is
891 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000892 //
893 // Fields marked New ABI are part of the GNUstep runtime. We emit them
894 // anyway; the classes will still work with the GNU runtime, they will just
895 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +0000896 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000897 PtrToInt8Ty, // class_pointer
898 PtrToInt8Ty, // super_class
899 PtrToInt8Ty, // name
900 LongTy, // version
901 LongTy, // info
902 LongTy, // instance_size
903 IVars->getType(), // ivars
904 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +0000905 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000906 PtrTy, // dtable
907 PtrTy, // subclass_list
908 PtrTy, // sibling_class
909 PtrTy, // protocols
910 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000911 // New ABI:
912 LongTy, // abi_version
913 IvarOffsets->getType(), // ivar_offsets
914 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000915 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000916 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000917 // Fill in the structure
918 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +0000919 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000920 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +0000921 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000922 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000923 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000924 Elements.push_back(InstanceSize);
925 Elements.push_back(IVars);
926 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000927 Elements.push_back(NULLPtr);
928 Elements.push_back(NULLPtr);
929 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +0000930 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000931 Elements.push_back(NULLPtr);
932 Elements.push_back(Zero);
933 Elements.push_back(IvarOffsets);
934 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000935 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +0000936 // This is now an externally visible symbol, so that we can speed up class
937 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +0000938 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
939 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000940}
941
942llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
943 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
944 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +0000945 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000946 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000947 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
948 PtrToInt8Ty,
949 NULL);
950 std::vector<llvm::Constant*> Methods;
951 std::vector<llvm::Constant*> Elements;
952 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
953 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000954 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +0000955 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000956 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000957 }
Owen Anderson9793f0e2009-07-29 22:16:19 +0000958 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000959 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000960 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +0000961 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +0000962 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000963 IntTy, ObjCMethodArrayTy, NULL);
964 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000965 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000966 Methods.push_back(Array);
967 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
968}
Mike Stumpdd93a192009-07-31 21:31:32 +0000969
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000970// Create the protocol list structure used in classes, categories and so on
971llvm::Constant *CGObjCGNU::GenerateProtocolList(
972 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000973 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000974 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +0000975 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000976 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
977 LongTy,//FIXME: Should be size_t
978 ProtocolArrayTy,
979 NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000980 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000981 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
982 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +0000983 llvm::Constant *protocol = 0;
984 llvm::StringMap<llvm::Constant*>::iterator value =
985 ExistingProtocols.find(*iter);
986 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000987 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +0000988 } else {
989 protocol = value->getValue();
990 }
Owen Andersonade90fd2009-07-29 18:54:39 +0000991 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +0000992 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000993 Elements.push_back(Ptr);
994 }
Owen Anderson47034e12009-07-28 18:33:04 +0000995 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000996 Elements);
997 Elements.clear();
998 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000999 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001000 Elements.push_back(ProtocolArray);
1001 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1002}
1003
Mike Stump11289f42009-09-09 15:08:12 +00001004llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001005 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001006 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001007 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001008 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001009 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001010}
1011
1012llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1013 const std::string &ProtocolName) {
1014 llvm::SmallVector<std::string, 0> EmptyStringVector;
1015 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1016
1017 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001018 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001019 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1020 // Protocols are objects containing lists of the methods implemented and
1021 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001022 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001023 PtrToInt8Ty,
1024 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001025 MethodList->getType(),
1026 MethodList->getType(),
1027 MethodList->getType(),
1028 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001029 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001030 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001031 // The isa pointer must be set to a magic number so the runtime knows it's
1032 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001033 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1034 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +00001035 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001036 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001037 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1038 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001039 Elements.push_back(MethodList);
1040 Elements.push_back(MethodList);
1041 Elements.push_back(MethodList);
1042 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001043 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001044}
1045
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001046void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1047 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001048 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001049 llvm::SmallVector<std::string, 16> Protocols;
1050 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1051 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001052 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001053 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1054 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001055 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1056 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001057 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1058 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001059 std::string TypeStr;
1060 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001061 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1062 InstanceMethodNames.push_back(
1063 MakeConstantString((*iter)->getSelector().getAsString()));
1064 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1065 } else {
1066 OptionalInstanceMethodNames.push_back(
1067 MakeConstantString((*iter)->getSelector().getAsString()));
1068 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1069 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001070 }
1071 // Collect information about class methods:
1072 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1073 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001074 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1075 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001076 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001077 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1078 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001079 std::string TypeStr;
1080 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001081 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1082 ClassMethodNames.push_back(
1083 MakeConstantString((*iter)->getSelector().getAsString()));
1084 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1085 } else {
1086 OptionalClassMethodNames.push_back(
1087 MakeConstantString((*iter)->getSelector().getAsString()));
1088 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1089 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001090 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001091
1092 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1093 llvm::Constant *InstanceMethodList =
1094 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1095 llvm::Constant *ClassMethodList =
1096 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001097 llvm::Constant *OptionalInstanceMethodList =
1098 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1099 OptionalInstanceMethodTypes);
1100 llvm::Constant *OptionalClassMethodList =
1101 GenerateProtocolMethodList(OptionalClassMethodNames,
1102 OptionalClassMethodTypes);
1103
1104 // Property metadata: name, attributes, isSynthesized, setter name, setter
1105 // types, getter name, getter types.
1106 // The isSynthesized value is always set to 0 in a protocol. It exists to
1107 // simplify the runtime library by allowing it to use the same data
1108 // structures for protocol metadata everywhere.
1109 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1110 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1111 PtrToInt8Ty, NULL);
1112 std::vector<llvm::Constant*> Properties;
1113 std::vector<llvm::Constant*> OptionalProperties;
1114
1115 // Add all of the property methods need adding to the method list and to the
1116 // property metadata list.
1117 for (ObjCContainerDecl::prop_iterator
1118 iter = PD->prop_begin(), endIter = PD->prop_end();
1119 iter != endIter ; iter++) {
1120 std::vector<llvm::Constant*> Fields;
1121 ObjCPropertyDecl *property = (*iter);
1122
1123 Fields.push_back(MakeConstantString(property->getNameAsString()));
1124 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1125 property->getPropertyAttributes()));
1126 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1127 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1128 std::string TypeStr;
1129 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1130 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1131 InstanceMethodTypes.push_back(TypeEncoding);
1132 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1133 Fields.push_back(TypeEncoding);
1134 } else {
1135 Fields.push_back(NULLPtr);
1136 Fields.push_back(NULLPtr);
1137 }
1138 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1139 std::string TypeStr;
1140 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1141 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1142 InstanceMethodTypes.push_back(TypeEncoding);
1143 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1144 Fields.push_back(TypeEncoding);
1145 } else {
1146 Fields.push_back(NULLPtr);
1147 Fields.push_back(NULLPtr);
1148 }
1149 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1150 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1151 } else {
1152 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1153 }
1154 }
1155 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1156 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1157 llvm::Constant* PropertyListInitFields[] =
1158 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1159
1160 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001161 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001162 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1163 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1164 PropertyListInit, ".objc_property_list");
1165
1166 llvm::Constant *OptionalPropertyArray =
1167 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1168 OptionalProperties.size()) , OptionalProperties);
1169 llvm::Constant* OptionalPropertyListInitFields[] = {
1170 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1171 OptionalPropertyArray };
1172
1173 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001174 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001175 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1176 OptionalPropertyListInit->getType(), false,
1177 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1178 ".objc_property_list");
1179
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001180 // Protocols are objects containing lists of the methods implemented and
1181 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001182 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001183 PtrToInt8Ty,
1184 ProtocolList->getType(),
1185 InstanceMethodList->getType(),
1186 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001187 OptionalInstanceMethodList->getType(),
1188 OptionalClassMethodList->getType(),
1189 PropertyList->getType(),
1190 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001191 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001192 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001193 // The isa pointer must be set to a magic number so the runtime knows it's
1194 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001195 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1196 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +00001197 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001198 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001199 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1200 Elements.push_back(ProtocolList);
1201 Elements.push_back(InstanceMethodList);
1202 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001203 Elements.push_back(OptionalInstanceMethodList);
1204 Elements.push_back(OptionalClassMethodList);
1205 Elements.push_back(PropertyList);
1206 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001207 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001208 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001209 ".objc_protocol"), IdTy);
1210}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001211void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1212 // Collect information about instance methods
1213 llvm::SmallVector<Selector, 1> MethodSels;
1214 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1215
1216 std::vector<llvm::Constant*> Elements;
1217 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1218 const std::string CategoryName = "AnotherHack";
1219 Elements.push_back(MakeConstantString(CategoryName));
1220 Elements.push_back(MakeConstantString(ClassName));
1221 // Instance method list
1222 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1223 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1224 // Class method list
1225 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1226 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1227 // Protocol list
1228 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1229 ExistingProtocols.size());
1230 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1231 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1232 LongTy,//FIXME: Should be size_t
1233 ProtocolArrayTy,
1234 NULL);
1235 std::vector<llvm::Constant*> ProtocolElements;
1236 for (llvm::StringMapIterator<llvm::Constant*> iter =
1237 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1238 iter != endIter ; iter++) {
1239 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1240 PtrTy);
1241 ProtocolElements.push_back(Ptr);
1242 }
1243 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1244 ProtocolElements);
1245 ProtocolElements.clear();
1246 ProtocolElements.push_back(NULLPtr);
1247 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1248 ExistingProtocols.size()));
1249 ProtocolElements.push_back(ProtocolArray);
1250 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1251 ProtocolElements, ".objc_protocol_list"), PtrTy));
1252 Categories.push_back(llvm::ConstantExpr::getBitCast(
1253 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1254 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1255}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001256
Daniel Dunbar92992502008-08-15 22:20:32 +00001257void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001258 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1259 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001260 // Collect information about instance methods
1261 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1262 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001263 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001264 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001265 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001266 InstanceMethodSels.push_back((*iter)->getSelector());
1267 std::string TypeStr;
1268 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001269 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001270 }
1271
1272 // Collect information about class methods
1273 llvm::SmallVector<Selector, 16> ClassMethodSels;
1274 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001275 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001276 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001277 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001278 ClassMethodSels.push_back((*iter)->getSelector());
1279 std::string TypeStr;
1280 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001281 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001282 }
1283
1284 // Collect the names of referenced protocols
1285 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001286 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1287 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001288 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1289 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001290 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001291
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001292 std::vector<llvm::Constant*> Elements;
1293 Elements.push_back(MakeConstantString(CategoryName));
1294 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001295 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001296 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001297 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001298 false), PtrTy));
1299 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001300 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001301 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001302 PtrTy));
1303 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001304 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001305 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001306 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001307 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001308 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001309}
Daniel Dunbar92992502008-08-15 22:20:32 +00001310
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001311llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1312 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1313 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1314 ASTContext &Context = CGM.getContext();
1315 //
1316 // Property metadata: name, attributes, isSynthesized, setter name, setter
1317 // types, getter name, getter types.
1318 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1319 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1320 PtrToInt8Ty, NULL);
1321 std::vector<llvm::Constant*> Properties;
1322
1323
1324 // Add all of the property methods need adding to the method list and to the
1325 // property metadata list.
1326 for (ObjCImplDecl::propimpl_iterator
1327 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1328 iter != endIter ; iter++) {
1329 std::vector<llvm::Constant*> Fields;
1330 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001331 ObjCPropertyImplDecl *propertyImpl = *iter;
1332 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1333 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001334
1335 Fields.push_back(MakeConstantString(property->getNameAsString()));
1336 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1337 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001338 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001339 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001340 std::string TypeStr;
1341 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1342 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001343 if (isSynthesized) {
1344 InstanceMethodTypes.push_back(TypeEncoding);
1345 InstanceMethodSels.push_back(getter->getSelector());
1346 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001347 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1348 Fields.push_back(TypeEncoding);
1349 } else {
1350 Fields.push_back(NULLPtr);
1351 Fields.push_back(NULLPtr);
1352 }
1353 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001354 std::string TypeStr;
1355 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1356 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001357 if (isSynthesized) {
1358 InstanceMethodTypes.push_back(TypeEncoding);
1359 InstanceMethodSels.push_back(setter->getSelector());
1360 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001361 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1362 Fields.push_back(TypeEncoding);
1363 } else {
1364 Fields.push_back(NULLPtr);
1365 Fields.push_back(NULLPtr);
1366 }
1367 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1368 }
1369 llvm::ArrayType *PropertyArrayTy =
1370 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1371 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1372 Properties);
1373 llvm::Constant* PropertyListInitFields[] =
1374 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1375
1376 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001377 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001378 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1379 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1380 ".objc_property_list");
1381}
1382
Daniel Dunbar92992502008-08-15 22:20:32 +00001383void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1384 ASTContext &Context = CGM.getContext();
1385
1386 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001387 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001388 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001389 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001390 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001391 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001392 EmitClassRef(SuperClassName);
1393 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001394
1395 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001396 ObjCInterfaceDecl *ClassDecl =
1397 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001398 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001399 // Emit the symbol that is used to generate linker errors if this class is
1400 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001401 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001402 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001403 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001404 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001405 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001406 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001407 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001408 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Daniel Dunbar12119b92009-05-03 10:46:44 +00001411 // Get the size of instances.
1412 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar92992502008-08-15 22:20:32 +00001413
1414 // Collect information about instance variables.
1415 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1416 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1417 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001418
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001419 std::vector<llvm::Constant*> IvarOffsetValues;
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001422 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1423 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1424 // class}. The runtime will then set this to the correct value on load.
1425 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1426 instanceSize = 0 - (instanceSize - superInstanceSize);
1427 }
David Chisnall18cf7372010-04-19 00:45:34 +00001428
1429 // Collect declared and synthesized ivars.
1430 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1431 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1432
1433 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1434 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001435 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001436 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001437 // Get the type encoding for this ivar
1438 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001439 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001440 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001441 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001442 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001443 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001444 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001445 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001446 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001447 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001448 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001449 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1450 false, llvm::GlobalValue::ExternalLinkage,
1451 llvm::ConstantInt::get(IntTy, BaseOffset),
1452 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001453 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001454 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001455 llvm::Constant *IvarOffsetArrayInit =
1456 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1457 IvarOffsetValues.size()), IvarOffsetValues);
1458 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1459 IvarOffsetArrayInit->getType(), false,
1460 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1461 ".ivar.offsets");
Daniel Dunbar92992502008-08-15 22:20:32 +00001462
1463 // Collect information about instance methods
1464 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1465 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001466 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001467 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001468 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001469 InstanceMethodSels.push_back((*iter)->getSelector());
1470 std::string TypeStr;
1471 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001472 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001473 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001474
1475 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1476 InstanceMethodTypes);
1477
Daniel Dunbar92992502008-08-15 22:20:32 +00001478
1479 // Collect information about class methods
1480 llvm::SmallVector<Selector, 16> ClassMethodSels;
1481 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001482 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001483 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001484 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001485 ClassMethodSels.push_back((*iter)->getSelector());
1486 std::string TypeStr;
1487 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001488 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001489 }
1490 // Collect the names of referenced protocols
1491 llvm::SmallVector<std::string, 16> Protocols;
1492 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1493 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1494 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001495 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001496
1497
1498
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001499 // Get the superclass pointer.
1500 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001501 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001502 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1503 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001504 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001505 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001506 // Empty vector used to construct empty method lists
1507 llvm::SmallVector<llvm::Constant*, 1> empty;
1508 // Generate the method and instance variable lists
1509 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001510 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001511 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001512 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001513 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1514 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001515 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001516 // we emit a symbol containing the offset for each ivar in the class. This
1517 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1518 // for the legacy ABI, without causing problems. The converse is also
1519 // possible, but causes all ivar accesses to be fragile.
1520 int i = 0;
1521 // Offset pointer for getting at the correct field in the ivar list when
1522 // setting up the alias. These are: The base address for the global, the
1523 // ivar array (second field), the ivar in this list (set for each ivar), and
1524 // the offset (third field in ivar structure)
1525 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1526 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001527 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001528 llvm::ConstantInt::get(IndexTy, 2) };
1529
1530 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1531 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1532 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1533 +(*iter)->getNameAsString();
1534 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++);
1535 // Get the correct ivar field
1536 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1537 IvarList, offsetPointerIndexes, 4);
1538 // Get the existing alias, if one exists.
1539 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1540 if (offset) {
1541 offset->setInitializer(offsetValue);
1542 // If this is the real definition, change its linkage type so that
1543 // different modules will use this one, rather than their private
1544 // copy.
1545 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1546 } else {
1547 // Add a new alias if there isn't one already.
1548 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1549 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1550 }
1551 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001552 //Generate metaclass for class methods
1553 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001554 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001555 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001556
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001557 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001558 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001559 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001560 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001561 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001562 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1563 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001564
1565 // Resolve the class aliases, if they exist.
1566 if (ClassPtrAlias) {
1567 ClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001568 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001569 ClassPtrAlias = 0;
1570 }
1571 if (MetaClassPtrAlias) {
1572 MetaClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001573 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001574 MetaClassPtrAlias = 0;
1575 }
1576
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001577 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001578 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001579 Classes.push_back(ClassStruct);
1580}
1581
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001582
Mike Stump11289f42009-09-09 15:08:12 +00001583llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001584 // Only emit an ObjC load function if no Objective-C stuff has been called
1585 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1586 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov3b6dd582008-06-01 15:14:46 +00001587 UntypedSelectors.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001588 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001589
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001590 // Add all referenced protocols to a category.
1591 GenerateProtocolHolderCategory();
1592
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001593 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1594 SelectorTy->getElementType());
1595 const llvm::Type *SelStructPtrTy = SelectorTy;
1596 bool isSelOpaque = false;
1597 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001598 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1599 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001600 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001601 isSelOpaque = true;
1602 }
1603
Eli Friedman412c6682008-06-01 16:00:02 +00001604 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001605 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001606 TheModule.addTypeName(".objc_id", IdTy);
1607 TheModule.addTypeName(".objc_imp", IMPTy);
1608
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001609 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001610 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001611 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001612 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001613 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001614 ConstantStrings.size() + 1);
1615 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001616
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001617 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1618 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall5778fce2009-08-31 16:41:57 +00001619 Elements.push_back(MakeConstantString(StringClass,
1620 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001621 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001622 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001623 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001624 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001625 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001626 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001627 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001628 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001629 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001630 Elements.clear();
1631 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001632 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001633 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001634 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001635 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001636 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001637 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001638 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001639 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001640 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001641 llvm::Type::getInt16Ty(VMContext),
1642 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001643 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001644
1645 Elements.clear();
1646 // Pointer to an array of selectors used in this module.
1647 std::vector<llvm::Constant*> Selectors;
1648 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1649 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1650 iter != iterEnd ; ++iter) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001651 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnall29979822009-09-14 19:04:10 +00001652 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner63dd3372008-06-26 04:10:42 +00001653 ".objc_sel_types"));
Owen Anderson0e0189d2009-07-27 22:29:56 +00001654 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001655 Elements.clear();
1656 }
1657 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1658 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner63dd3372008-06-26 04:10:42 +00001659 iter != iterEnd; ++iter) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001660 Elements.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001661 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001662 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001663 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001664 Elements.clear();
1665 }
1666 Elements.push_back(NULLPtr);
1667 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001668 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001669 Elements.clear();
1670 // Number of static selectors
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001671 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001672 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001673 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001674 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00001675 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001676 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001677
1678 // Now that all of the static selectors exist, create pointers to them.
1679 int index = 0;
1680 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1681 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1682 iter != iterEnd; ++iter) {
1683 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001684 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar45858d22010-02-03 20:11:42 +00001685 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnalle0b5b3a2010-05-09 01:01:43 +00001686 true, llvm::GlobalValue::LinkOnceODRLinkage,
1687 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1688 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1689 iter->first.second));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001690 // If selectors are defined as an opaque type, cast the pointer to this
1691 // type.
1692 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001693 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1694 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001695 }
David Chisnall0a24fd32010-05-08 20:58:05 +00001696 (*iter).second->replaceAllUsesWith(SelPtr);
1697 (*iter).second->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001698 }
1699 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1700 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1701 iter != iterEnd; iter++) {
1702 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001703 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall0a24fd32010-05-08 20:58:05 +00001704 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnalle0b5b3a2010-05-09 01:01:43 +00001705 true, llvm::GlobalValue::LinkOnceODRLinkage,
1706 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1707 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001708 // If selectors are defined as an opaque type, cast the pointer to this
1709 // type.
1710 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001711 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1712 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001713 }
David Chisnall0a24fd32010-05-08 20:58:05 +00001714 (*iter).second->replaceAllUsesWith(SelPtr);
1715 (*iter).second->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001716 }
1717 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00001718 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001719 Classes.size()));
1720 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00001721 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001722 Categories.size()));
1723 // Create an array of classes, then categories, then static object instances
1724 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1725 // NULL-terminated list of static object instances (mainly constant strings)
1726 Classes.push_back(Statics);
1727 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00001728 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001729 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00001730 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001731 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1732
1733 // The symbol table is contained in a module which has some version-checking
1734 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00001735 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001736 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001737 Elements.clear();
1738 // Runtime version used for compatibility checking.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001739 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump11289f42009-09-09 15:08:12 +00001740 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001741 NonFragileRuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001742 } else {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001743 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001744 }
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00001745 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00001746 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001747 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00001748 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001749 //FIXME: Should be the path to the file where this module was declared
1750 Elements.push_back(NULLPtr);
1751 Elements.push_back(SymTab);
1752 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1753
1754 // Create the load function calling the runtime entry point with the module
1755 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001756 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00001757 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001758 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1759 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00001760 llvm::BasicBlock *EntryBB =
1761 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00001762 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001763 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001764
1765 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001766 llvm::PointerType::getUnqual(ModuleTy));
1767 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00001768 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001769 Builder.CreateCall(Register, Module);
1770 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001771
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001772 return LoadFunction;
1773}
Daniel Dunbar92992502008-08-15 22:20:32 +00001774
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00001775llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00001776 const ObjCContainerDecl *CD) {
1777 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00001778 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattnere4b95692008-11-24 03:33:13 +00001779 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall12ae54d2010-03-20 19:53:29 +00001780 std::string ClassName = CD->getName();
Chris Lattnere4b95692008-11-24 03:33:13 +00001781 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorffca3a22009-01-09 17:18:27 +00001782 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00001783
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001784 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00001785 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001786 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001787 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1788 MethodName, isClassMethod);
1789
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001790 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00001791 = llvm::Function::Create(MethodTy,
1792 llvm::GlobalValue::InternalLinkage,
1793 FunctionName,
1794 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00001795 return Method;
1796}
1797
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001798llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001799 std::vector<const llvm::Type*> Params;
1800 const llvm::Type *BoolTy =
1801 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1802 Params.push_back(IdTy);
1803 Params.push_back(SelectorTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001804 Params.push_back(IntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001805 Params.push_back(BoolTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001806 // void objc_getProperty (id, SEL, int, bool)
Mike Stump11289f42009-09-09 15:08:12 +00001807 const llvm::FunctionType *FTy =
1808 llvm::FunctionType::get(IdTy, Params, false);
1809 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1810 "objc_getProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001811}
1812
1813llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001814 std::vector<const llvm::Type*> Params;
1815 const llvm::Type *BoolTy =
1816 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1817 Params.push_back(IdTy);
1818 Params.push_back(SelectorTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001819 Params.push_back(IntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001820 Params.push_back(IdTy);
1821 Params.push_back(BoolTy);
1822 Params.push_back(BoolTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001823 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump11289f42009-09-09 15:08:12 +00001824 const llvm::FunctionType *FTy =
1825 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1826 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1827 "objc_setProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001828}
1829
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001830// FIXME. Implement this.
1831llvm::Function *CGObjCGNU::GetCopyStructFunction() {
1832 return 0;
1833}
1834
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001835llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1836 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1837 ASTContext &Ctx = CGM.getContext();
1838 // void objc_enumerationMutation (id)
John McCall2da83a32010-02-26 00:48:12 +00001839 llvm::SmallVector<CanQualType,1> Params;
David Chisnall9f57c292009-08-17 16:35:33 +00001840 Params.push_back(ASTIdTy);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001841 const llvm::FunctionType *FTy =
John McCallab26cfa2010-02-05 21:31:56 +00001842 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001843 FunctionType::ExtInfo()), false);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001844 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001845}
1846
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00001847void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1848 const Stmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001849 // Pointer to the personality function
1850 llvm::Constant *Personality =
Owen Anderson41a75022009-08-13 21:57:51 +00001851 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(VMContext),
Chris Lattner3dd1b4b2009-07-01 04:13:52 +00001852 true),
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001853 "__gnu_objc_personality_v0");
Owen Andersonade90fd2009-07-29 18:54:39 +00001854 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001855 std::vector<const llvm::Type*> Params;
1856 Params.push_back(PtrTy);
1857 llvm::Value *RethrowFn =
Owen Anderson41a75022009-08-13 21:57:51 +00001858 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
David Chisnall9a2073c2010-01-06 18:02:59 +00001859 Params, false), "_Unwind_Resume");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001860
1861 bool isTry = isa<ObjCAtTryStmt>(S);
1862 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1863 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1864 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Chris Lattner9fea9442009-05-11 18:16:28 +00001865 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001866 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1867 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1868 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1869
David Chisnall3a509cd2009-12-24 02:26:34 +00001870 // @synchronized()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001871 if (!isTry) {
Chris Lattner9fea9442009-05-11 18:16:28 +00001872 std::vector<const llvm::Type*> Args(1, IdTy);
1873 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001874 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00001875 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
Mike Stump11289f42009-09-09 15:08:12 +00001876 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00001877 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1878 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1879 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001880 }
1881
Chris Lattner9fea9442009-05-11 18:16:28 +00001882
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001883 // Push an EH context entry, used for handling rethrows and jumps
1884 // through finally.
1885 CGF.PushCleanupBlock(FinallyBlock);
1886
1887 // Emit the statements in the @try {} block
1888 CGF.setInvokeDest(TryHandler);
1889
1890 CGF.EmitBlock(TryBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001891 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001892 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1893
1894 // Jump to @finally if there is no exception
1895 CGF.EmitBranchThroughCleanup(FinallyEnd);
1896
1897 // Emit the handlers
1898 CGF.EmitBlock(TryHandler);
1899
Chris Lattner96afab52009-05-08 17:36:08 +00001900 // Get the correct versions of the exception handling intrinsics
Mike Stump11289f42009-09-09 15:08:12 +00001901 llvm::Value *llvm_eh_exception =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001902 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
Duncan Sandscef56992009-10-14 16:13:30 +00001903 llvm::Value *llvm_eh_selector =
1904 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
1905 llvm::Value *llvm_eh_typeid_for =
1906 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001907
1908 // Exception object
1909 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1910 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1911
1912 llvm::SmallVector<llvm::Value*, 8> ESelArgs;
Douglas Gregor46a572b2010-04-26 16:46:50 +00001913 llvm::SmallVector<std::pair<const VarDecl*, const Stmt*>, 8> Handlers;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001914
1915 ESelArgs.push_back(Exc);
1916 ESelArgs.push_back(Personality);
1917
1918 bool HasCatchAll = false;
1919 // Only @try blocks are allowed @catch blocks, but both can have @finally
1920 if (isTry) {
Douglas Gregor96c79492010-04-23 22:50:49 +00001921 if (cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
1922 const ObjCAtTryStmt &AtTry = cast<ObjCAtTryStmt>(S);
Chris Lattner9fea9442009-05-11 18:16:28 +00001923 CGF.setInvokeDest(CatchInCatch);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001924
Douglas Gregor96c79492010-04-23 22:50:49 +00001925 for (unsigned I = 0, N = AtTry.getNumCatchStmts(); I != N; ++I) {
1926 const ObjCAtCatchStmt *CatchStmt = AtTry.getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001927 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Mike Stumpdd93a192009-07-31 21:31:32 +00001928 Handlers.push_back(std::make_pair(CatchDecl,
1929 CatchStmt->getCatchBody()));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001930
1931 // @catch() and @catch(id) both catch any ObjC exception
Steve Naroff7cae42b2009-07-10 23:34:53 +00001932 if (!CatchDecl || CatchDecl->getType()->isObjCIdType()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001933 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1934 // Use i8* null here to signal this is a catch all, not a cleanup.
1935 ESelArgs.push_back(NULLPtr);
1936 HasCatchAll = true;
1937 // No further catches after this one will ever by reached
1938 break;
Mike Stump11289f42009-09-09 15:08:12 +00001939 }
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001940
1941 // All other types should be Objective-C interface pointer types.
Mike Stump11289f42009-09-09 15:08:12 +00001942 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00001943 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001944 assert(OPT && "Invalid @catch type.");
John McCall96fa4842010-05-17 21:00:27 +00001945 const ObjCInterfaceDecl *IDecl =
1946 OPT->getObjectType()->getInterface();
1947 assert(IDecl && "Invalid @catch type.");
Chris Lattner96afab52009-05-08 17:36:08 +00001948 llvm::Value *EHType =
John McCall96fa4842010-05-17 21:00:27 +00001949 MakeConstantString(IDecl->getNameAsString());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001950 ESelArgs.push_back(EHType);
1951 }
1952 }
1953 }
1954
1955 // We use a cleanup unless there was already a catch all.
1956 if (!HasCatchAll) {
Owen Anderson41a75022009-08-13 21:57:51 +00001957 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001958 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1959 }
1960
1961 // Find which handler was matched.
Chris Lattner96afab52009-05-08 17:36:08 +00001962 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001963 ESelArgs.begin(), ESelArgs.end(), "selector");
1964
1965 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Douglas Gregor46a572b2010-04-26 16:46:50 +00001966 const VarDecl *CatchParam = Handlers[i].first;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001967 const Stmt *CatchBody = Handlers[i].second;
1968
1969 llvm::BasicBlock *Next = 0;
1970
1971 // The last handler always matches.
1972 if (i + 1 != e) {
1973 assert(CatchParam && "Only last handler can be a catch all.");
1974
1975 // Test whether this block matches the type for the selector and branch
1976 // to Match if it does, or to the next BB if it doesn't.
1977 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1978 Next = CGF.createBasicBlock("catch.next");
Chris Lattner96afab52009-05-08 17:36:08 +00001979 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001980 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1981 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1982 Next);
1983
1984 CGF.EmitBlock(Match);
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001987 if (CatchBody) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001988 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1989 CGF.ConvertType(CatchParam->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001990
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001991 // Bind the catch parameter if it exists.
1992 if (CatchParam) {
1993 // CatchParam is a ParmVarDecl because of the grammar
1994 // construction used to handle this, but for codegen purposes
1995 // we treat this as a local decl.
1996 CGF.EmitLocalBlockVarDecl(*CatchParam);
1997 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1998 }
1999
2000 CGF.ObjCEHValueStack.push_back(ExcObject);
2001 CGF.EmitStmt(CatchBody);
2002 CGF.ObjCEHValueStack.pop_back();
2003
2004 CGF.EmitBranchThroughCleanup(FinallyEnd);
2005
2006 if (Next)
2007 CGF.EmitBlock(Next);
2008 } else {
2009 assert(!Next && "catchup should be last handler.");
2010
2011 CGF.Builder.CreateStore(Exc, RethrowPtr);
2012 CGF.EmitBranchThroughCleanup(FinallyRethrow);
2013 }
2014 }
Chris Lattner9fea9442009-05-11 18:16:28 +00002015 // The @finally block is a secondary landing pad for any exceptions thrown in
2016 // @catch() blocks
2017 CGF.EmitBlock(CatchInCatch);
2018 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
2019 ESelArgs.clear();
2020 ESelArgs.push_back(Exc);
2021 ESelArgs.push_back(Personality);
David Chisnall3a509cd2009-12-24 02:26:34 +00002022 // If there is a @catch or @finally clause in outside of this one then we
2023 // need to make sure that we catch and rethrow it.
2024 if (PrevLandingPad) {
2025 ESelArgs.push_back(NULLPtr);
2026 } else {
2027 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
2028 }
Chris Lattner9fea9442009-05-11 18:16:28 +00002029 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
2030 "selector");
2031 CGF.Builder.CreateCall(llvm_eh_typeid_for,
2032 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
2033 CGF.Builder.CreateStore(Exc, RethrowPtr);
2034 CGF.EmitBranchThroughCleanup(FinallyRethrow);
2035
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002036 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2037
2038 CGF.setInvokeDest(PrevLandingPad);
2039
2040 CGF.EmitBlock(FinallyBlock);
2041
Chris Lattner9fea9442009-05-11 18:16:28 +00002042
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002043 if (isTry) {
Mike Stump11289f42009-09-09 15:08:12 +00002044 if (const ObjCAtFinallyStmt* FinallyStmt =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002045 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2046 CGF.EmitStmt(FinallyStmt->getFinallyBody());
2047 } else {
Chris Lattner9fea9442009-05-11 18:16:28 +00002048 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002049 // @synchronized.
Chris Lattner9fea9442009-05-11 18:16:28 +00002050 std::vector<const llvm::Type*> Args(1, IdTy);
2051 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00002052 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00002053 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Mike Stump11289f42009-09-09 15:08:12 +00002054 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00002055 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2056 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
2057 CGF.Builder.CreateCall(SyncExit, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002058 }
2059
2060 if (Info.SwitchBlock)
2061 CGF.EmitBlock(Info.SwitchBlock);
2062 if (Info.EndBlock)
2063 CGF.EmitBlock(Info.EndBlock);
2064
2065 // Branch around the rethrow code.
2066 CGF.EmitBranch(FinallyEnd);
2067
2068 CGF.EmitBlock(FinallyRethrow);
David Chisnall3a509cd2009-12-24 02:26:34 +00002069
2070 llvm::Value *ExceptionObject = CGF.Builder.CreateLoad(RethrowPtr);
2071 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2072 if (!UnwindBB) {
2073 CGF.Builder.CreateCall(RethrowFn, ExceptionObject);
2074 // Exception always thrown, next instruction is never reached.
2075 CGF.Builder.CreateUnreachable();
2076 } else {
2077 // If there is a @catch block outside this scope, we invoke instead of
2078 // calling because we may return to this function. This is very slow, but
2079 // some people still do it. It would be nice to add an optimised path for
2080 // this.
2081 CGF.Builder.CreateInvoke(RethrowFn, UnwindBB, UnwindBB, &ExceptionObject,
2082 &ExceptionObject+1);
2083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002085 CGF.EmitBlock(FinallyEnd);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002086}
2087
2088void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002089 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002090 llvm::Value *ExceptionAsObject;
2091
2092 std::vector<const llvm::Type*> Args(1, IdTy);
2093 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00002094 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump11289f42009-09-09 15:08:12 +00002095 llvm::Value *ThrowFn =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002096 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump11289f42009-09-09 15:08:12 +00002097
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002098 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2099 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002100 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002101 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002102 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002103 "Unexpected rethrow outside @catch block.");
2104 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2105 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002106 ExceptionAsObject =
2107 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002108
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002109 // Note: This may have to be an invoke, if we want to support constructs like:
2110 // @try {
2111 // @throw(obj);
2112 // }
2113 // @catch(id) ...
2114 //
2115 // This is effectively turning @throw into an incredibly-expensive goto, but
2116 // it may happen as a result of inlining followed by missed optimizations, or
2117 // as a result of stupidity.
2118 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2119 if (!UnwindBB) {
2120 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2121 CGF.Builder.CreateUnreachable();
2122 } else {
2123 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2124 &ExceptionAsObject+1);
2125 }
2126 // Clear the insertion point to indicate we are in unreachable code.
2127 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002128}
2129
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002130llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002131 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002132 CGBuilderTy B = CGF.Builder;
2133 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2134 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002135}
2136
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002137void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002138 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002139 CGBuilderTy B = CGF.Builder;
2140 src = EnforceType(B, src, IdTy);
2141 dst = EnforceType(B, dst, PtrToIdTy);
2142 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002143}
2144
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002145void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002146 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002147 CGBuilderTy B = CGF.Builder;
2148 src = EnforceType(B, src, IdTy);
2149 dst = EnforceType(B, dst, PtrToIdTy);
2150 B.CreateCall2(GlobalAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002151}
2152
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002153void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002154 llvm::Value *src, llvm::Value *dst,
2155 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002156 CGBuilderTy B = CGF.Builder;
2157 src = EnforceType(B, src, IdTy);
2158 dst = EnforceType(B, dst, PtrToIdTy);
2159 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002160}
2161
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002162void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002163 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002164 CGBuilderTy B = CGF.Builder;
2165 src = EnforceType(B, src, IdTy);
2166 dst = EnforceType(B, dst, PtrToIdTy);
2167 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002168}
2169
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002170void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002171 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002172 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +00002173 QualType Ty) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002174 CGBuilderTy B = CGF.Builder;
2175 DestPtr = EnforceType(B, DestPtr, IdTy);
2176 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2177
2178 std::pair<uint64_t, unsigned> TypeInfo = CGM.getContext().getTypeInfo(Ty);
2179 unsigned long size = TypeInfo.first/8;
2180 // FIXME: size_t
2181 llvm::Value *N = llvm::ConstantInt::get(LongTy, size);
2182
2183 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, N);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002184}
2185
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002186llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2187 const ObjCInterfaceDecl *ID,
2188 const ObjCIvarDecl *Ivar) {
2189 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2190 + '.' + Ivar->getNameAsString();
2191 // Emit the variable and initialize it with what we think the correct value
2192 // is. This allows code compiled with non-fragile ivars to work correctly
2193 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002194 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2195 if (!IvarOffsetPointer) {
David Chisnall44ec5552010-04-19 01:37:25 +00002196 uint64_t Offset;
2197 if (ObjCImplementationDecl *OID =
Dan Gohman145f3f12010-04-19 16:39:44 +00002198 CGM.getContext().getObjCImplementation(
2199 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002200 Offset = ComputeIvarBaseOffset(CGM, OID, Ivar);
2201 else
2202 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2203
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002204 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002205 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002206 // Don't emit the guess in non-PIC code because the linker will not be able
2207 // to replace it with the real version for a library. In non-PIC code you
2208 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002209 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002210 if (CGM.getLangOptions().PICLevel) {
2211 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2212 llvm::Type::getInt32Ty(VMContext), false,
2213 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2214 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2215 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2216 IvarOffsetGV, Name);
2217 } else {
2218 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002219 llvm::Type::getInt32PtrTy(VMContext), false,
2220 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002221 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002222 }
David Chisnall5778fce2009-08-31 16:41:57 +00002223 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002224}
2225
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002226LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2227 QualType ObjectTy,
2228 llvm::Value *BaseValue,
2229 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002230 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002231 const ObjCInterfaceDecl *ID =
2232 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002233 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2234 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002235}
Mike Stumpdd93a192009-07-31 21:31:32 +00002236
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002237static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2238 const ObjCInterfaceDecl *OID,
2239 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002240 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002241 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002242 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2243 if (OIVD == Ivars[k])
2244 return OID;
2245 }
Mike Stump11289f42009-09-09 15:08:12 +00002246
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002247 // Otherwise check in the super class.
2248 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2249 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002250
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002251 return 0;
2252}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002253
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002254llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002255 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002256 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002257 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002258 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall5778fce2009-08-31 16:41:57 +00002259 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2260 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002261 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002262 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002263 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002264}
2265
Mike Stumpdd93a192009-07-31 21:31:32 +00002266CodeGen::CGObjCRuntime *
2267CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattner87ab27d2008-06-26 04:19:03 +00002268 return new CGObjCGNU(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002269}