blob: 864c73f543f1a66536ae0a97a637dcd433089fe7 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000021
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnalle1d2584d2011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000038
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000039#include <map>
David Chisnalld7972f52011-03-23 16:36:54 +000040#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000041
42
Chris Lattner87ab27d2008-06-26 04:19:03 +000043using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000044using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000045using llvm::dyn_cast;
46
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048namespace {
David Chisnalld7972f52011-03-23 16:36:54 +000049/**
50 * Class that lazily initialises the runtime function. Avoids inserting the
51 * types and the function declaration into a module if they're not used, and
52 * avoids constructing the type more than once if it's used more than once.
53 */
54class LazyRuntimeFunction {
55 CodeGenModule *CGM;
56 std::vector<const llvm::Type*> ArgTys;
57 const char *FunctionName;
58 llvm::Function *Function;
59 public:
60 /**
61 * Constructor leaves this class uninitialized, because it is intended to
62 * be used as a field in another class and not all of the types that are
63 * used as arguments will necessarily be available at construction time.
64 */
65 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
66
67 /**
68 * Initialises the lazy function with the name, return type, and the types
69 * of the arguments.
70 */
71 END_WITH_NULL
72 void init(CodeGenModule *Mod, const char *name,
73 const llvm::Type *RetTy, ...) {
74 CGM =Mod;
75 FunctionName = name;
76 Function = 0;
77 va_list Args;
78 va_start(Args, RetTy);
79 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
80 ArgTys.push_back(ArgTy);
81 va_end(Args);
82 // Push the return type on at the end so we can pop it off easily
83 ArgTys.push_back(RetTy);
84 }
85 /**
86 * Overloaded cast operator, allows the class to be implicitly cast to an
87 * LLVM constant.
88 */
89 operator llvm::Function*() {
90 if (!Function) {
91 assert(0 != CGM && "Using an uninitialized LazyRuntimeFunction!");
92 const llvm::Type *RetTy = ArgTys.back();
93 ArgTys.pop_back();
94 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
95 Function =
96 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
97 ArgTys.resize(0);
98 }
99 return Function;
100 }
101};
102
103
104/**
105 * GNU Objective-C runtime code generation. This class implements the parts of
106 * Objective-C support that are specific to the GNU family of runtimes (GCC and
107 * GNUstep).
108 */
109class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000110protected:
David Chisnalld7972f52011-03-23 16:36:54 +0000111 CodeGenModule &CGM;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000112 llvm::Module &TheModule;
David Chisnall76803412011-03-23 22:52:06 +0000113 const llvm::StructType *ObjCSuperTy;
114 const llvm::PointerType *PtrToObjCSuperTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000115 const llvm::PointerType *SelectorTy;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000116 const llvm::IntegerType *Int8Ty;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000117 const llvm::PointerType *PtrToInt8Ty;
David Chisnall76803412011-03-23 22:52:06 +0000118 const llvm::PointerType *IMPTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000119 const llvm::PointerType *IdTy;
David Chisnall5bb4efd2010-02-03 15:59:02 +0000120 const llvm::PointerType *PtrToIdTy;
John McCall2da83a32010-02-26 00:48:12 +0000121 CanQualType ASTIdTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000122 const llvm::IntegerType *IntTy;
123 const llvm::PointerType *PtrTy;
124 const llvm::IntegerType *LongTy;
David Chisnall168b80f2010-12-26 22:13:16 +0000125 const llvm::IntegerType *SizeTy;
126 const llvm::IntegerType *PtrDiffTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000127 const llvm::PointerType *PtrToIntTy;
David Chisnall168b80f2010-12-26 22:13:16 +0000128 const llvm::Type *BoolTy;
David Chisnall76803412011-03-23 22:52:06 +0000129 /// Metadata kind used to tie method lookups to message sends.
130 unsigned msgSendMDKind;
131 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
132
133 &Name="");
134 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
135 prefix);
136 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
137 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
138 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
139 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
140 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
141 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
142 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
143 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
144 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
145 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
146 if (V->getType() == Ty) return V;
147 return B.CreateBitCast(V, Ty);
148 }
149 // Some zeros used for GEPs in lots of places.
150 llvm::Constant *Zeros[2];
151 llvm::Constant *NULLPtr;
152 llvm::LLVMContext &VMContext;
153private:
Daniel Dunbar566421c2009-05-04 15:31:17 +0000154 llvm::GlobalAlias *ClassPtrAlias;
155 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000156 std::vector<llvm::Constant*> Classes;
157 std::vector<llvm::Constant*> Categories;
158 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall358e7512010-01-27 12:49:23 +0000159 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000160 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnalld7972f52011-03-23 16:36:54 +0000161 /**
162 * For each variant of a selector, we store the type encoding and a
163 * placeholder value. For an untyped selector, the type will be the empty
164 * string. Selector references are all done via the module's selector table,
165 * so we create an alias as a placeholder and then replace it with the real
166 * value later.
167 */
168 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
169 /**
170 * A map from selectors to selector types. This allows us to emit all
171 * selectors of the same name and type together.
172 */
173 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
174 SelectorMap;
175 SelectorMap SelectorTable;
176
David Chisnall5bb4efd2010-02-03 15:59:02 +0000177 // Selectors that we don't emit in GC mode
178 Selector RetainSel, ReleaseSel, AutoreleaseSel;
179 // Functions used for GC.
David Chisnalld7972f52011-03-23 16:36:54 +0000180 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
181 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000182
183 LazyRuntimeFunction ExceptionThrowFn;
184 LazyRuntimeFunction SyncEnterFn;
185 LazyRuntimeFunction SyncExitFn;
186
187 LazyRuntimeFunction EnumerationMutationFn;
188 LazyRuntimeFunction GetPropertyFn;
189 LazyRuntimeFunction SetPropertyFn;
190 LazyRuntimeFunction GetStructPropertyFn;
191 LazyRuntimeFunction SetStructPropertyFn;
192
193 // The version of the runtime that this class targets. Must match the version
194 // in the runtime.
195 const int RuntimeVersion;
196 // The version of the protocol class. Used to differentiate between ObjC1
197 // and ObjC2 protocols.
198 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000199private:
200 llvm::Constant *GenerateIvarList(
201 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
202 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
203 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnalld7972f52011-03-23 16:36:54 +0000204 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
205 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000206 const llvm::SmallVectorImpl<Selector> &MethodSels,
207 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000208 bool isClassMethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000209 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000210 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
211 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
212 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000213 llvm::Constant *GenerateProtocolList(
214 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000215 // To ensure that all protocols are seen by the runtime, we add a category on
216 // a class defined in the runtime, declaring no methods, but adopting the
217 // protocols.
218 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000219 llvm::Constant *GenerateClassStructure(
220 llvm::Constant *MetaClass,
221 llvm::Constant *SuperClass,
222 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000223 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000224 llvm::Constant *Version,
225 llvm::Constant *InstanceSize,
226 llvm::Constant *IVars,
227 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000228 llvm::Constant *Protocols,
229 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000230 llvm::Constant *Properties,
231 bool isMeta=false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000232 llvm::Constant *GenerateProtocolMethodList(
233 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
234 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000235 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
236 const std::string &TypeEncoding, bool lval);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000237 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
238 const ObjCIvarDecl *Ivar);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000239 void EmitClassRef(const std::string &className);
David Chisnalld7972f52011-03-23 16:36:54 +0000240 void EmitObjCXXTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S);
David Chisnall76803412011-03-23 22:52:06 +0000241protected:
242 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
243 llvm::Value *&Receiver,
244 llvm::Value *cmd,
245 llvm::MDNode *node) = 0;
246 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
247 llvm::Value *ObjCSuper,
248 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000249public:
David Chisnalld7972f52011-03-23 16:36:54 +0000250 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
251 unsigned protocolClassVersion);
252
David Chisnall481e3a82010-01-23 02:40:42 +0000253 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000254
255 virtual RValue
256 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000257 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000258 QualType ResultType,
259 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000260 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000261 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000262 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000263 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000264 virtual RValue
265 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000266 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000267 QualType ResultType,
268 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000269 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000270 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000271 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000272 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000273 const CallArgList &CallArgs,
274 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000275 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000276 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000277 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
278 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000279 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
280 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000281 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000282
283 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000284 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000285 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
286 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000287 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000288 const ObjCProtocolDecl *PD);
289 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000290 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000291 virtual llvm::Function *GetPropertyGetFunction();
292 virtual llvm::Function *GetPropertySetFunction();
David Chisnall168b80f2010-12-26 22:13:16 +0000293 virtual llvm::Function *GetSetStructFunction();
294 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000295 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000296
David Chisnalld7972f52011-03-23 16:36:54 +0000297 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000298 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000299 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000300 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000301 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000302 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000303 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000304 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000305 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000306 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000307 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000308 llvm::Value *src, llvm::Value *dest,
309 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000310 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000311 llvm::Value *src, llvm::Value *dest,
312 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000313 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000314 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000315 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000316 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000317 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000318 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000319 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000320 QualType ObjectTy,
321 llvm::Value *BaseValue,
322 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000323 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000324 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000325 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000326 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000327 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000328 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000329 return NULLPtr;
330 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000331};
David Chisnalld7972f52011-03-23 16:36:54 +0000332/**
333 * Class representing the legacy GCC Objective-C ABI. This is the default when
334 * -fobjc-nonfragile-abi is not specified.
335 *
336 * The GCC ABI target actually generates code that is approximately compatible
337 * with the new GNUstep runtime ABI, but refrains from using any features that
338 * would not work with the GCC runtime. For example, clang always generates
339 * the extended form of the class structure, and the extra fields are simply
340 * ignored by GCC libobjc.
341 */
342class CGObjCGCC : public CGObjCGNU {
David Chisnall76803412011-03-23 22:52:06 +0000343 /**
344 * The GCC ABI message lookup function. Returns an IMP pointing to the
345 * method implementation for this message.
346 */
347 LazyRuntimeFunction MsgLookupFn;
348 /**
349 * The GCC ABI superclass message lookup function. Takes a pointer to a
350 * structure describing the receiver and the class, and a selector as
351 * arguments. Returns the IMP for the corresponding method.
352 */
353 LazyRuntimeFunction MsgLookupSuperFn;
354protected:
355 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
356 llvm::Value *&Receiver,
357 llvm::Value *cmd,
358 llvm::MDNode *node) {
359 CGBuilderTy &Builder = CGF.Builder;
360 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
361 EnforceType(Builder, Receiver, IdTy),
362 EnforceType(Builder, cmd, SelectorTy));
363 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
364 return imp;
365 }
366 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
367 llvm::Value *ObjCSuper,
368 llvm::Value *cmd) {
369 CGBuilderTy &Builder = CGF.Builder;
370 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
371 PtrToObjCSuperTy), cmd};
372 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
373 }
David Chisnalld7972f52011-03-23 16:36:54 +0000374 public:
David Chisnall76803412011-03-23 22:52:06 +0000375 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
376 // IMP objc_msg_lookup(id, SEL);
377 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
378 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
379 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
380 PtrToObjCSuperTy, SelectorTy, NULL);
381 }
David Chisnalld7972f52011-03-23 16:36:54 +0000382};
383/**
384 * Class used when targeting the new GNUstep runtime ABI.
385 */
386class CGObjCGNUstep : public CGObjCGNU {
David Chisnall76803412011-03-23 22:52:06 +0000387 /**
388 * The slot lookup function. Returns a pointer to a cacheable structure
389 * that contains (among other things) the IMP.
390 */
391 LazyRuntimeFunction SlotLookupFn;
392 /**
393 * The GNUstep ABI superclass message lookup function. Takes a pointer to
394 * a structure describing the receiver and the class, and a selector as
395 * arguments. Returns the slot for the corresponding method. Superclass
396 * message lookup rarely changes, so this is a good caching opportunity.
397 */
398 LazyRuntimeFunction SlotLookupSuperFn;
399 /**
400 * Type of an slot structure pointer. This is returned by the various
401 * lookup functions.
402 */
403 llvm::Type *SlotTy;
404 protected:
405 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
406 llvm::Value *&Receiver,
407 llvm::Value *cmd,
408 llvm::MDNode *node) {
409 CGBuilderTy &Builder = CGF.Builder;
410 llvm::Function *LookupFn = SlotLookupFn;
411
412 // Store the receiver on the stack so that we can reload it later
413 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
414 Builder.CreateStore(Receiver, ReceiverPtr);
415
416 llvm::Value *self;
417
418 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
419 self = CGF.LoadObjCSelf();
420 } else {
421 self = llvm::ConstantPointerNull::get(IdTy);
422 }
423
424 // The lookup function is guaranteed not to capture the receiver pointer.
425 LookupFn->setDoesNotCapture(1);
426
427 llvm::CallInst *slot =
428 Builder.CreateCall3(LookupFn,
429 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
430 EnforceType(Builder, cmd, SelectorTy),
431 EnforceType(Builder, self, IdTy));
432 slot->setOnlyReadsMemory();
433 slot->setMetadata(msgSendMDKind, node);
434
435 // Load the imp from the slot
436 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
437
438 // The lookup function may have changed the receiver, so make sure we use
439 // the new one.
440 Receiver = Builder.CreateLoad(ReceiverPtr, true);
441 return imp;
442 }
443 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
444 llvm::Value *ObjCSuper,
445 llvm::Value *cmd) {
446 CGBuilderTy &Builder = CGF.Builder;
447 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
448
449 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
450 lookupArgs+2);
451 slot->setOnlyReadsMemory();
452
453 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
454 }
David Chisnalld7972f52011-03-23 16:36:54 +0000455 public:
David Chisnall76803412011-03-23 22:52:06 +0000456 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
457 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
458 PtrTy, PtrTy, IntTy, IMPTy, NULL);
459 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
460 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
461 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
462 SelectorTy, IdTy, NULL);
463 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
464 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
465 PtrToObjCSuperTy, SelectorTy, NULL);
466 }
David Chisnalld7972f52011-03-23 16:36:54 +0000467};
468
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000469} // end anonymous namespace
470
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000471
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000472/// Emits a reference to a dummy variable which is emitted with each class.
473/// This ensures that a linker error will be generated when trying to link
474/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000475void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000476 std::string symbolRef = "__objc_class_ref_" + className;
477 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000478 if (TheModule.getGlobalVariable(symbolRef))
479 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000480 std::string symbolName = "__objc_class_name_" + className;
481 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
482 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000483 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
484 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000485 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000486 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000487 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000488}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000489
David Chisnalld7972f52011-03-23 16:36:54 +0000490static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
491 const llvm::StringRef &CategoryName, const Selector MethodName,
492 bool isClassMethod) {
493 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000494 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
495 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000496 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
497 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000498}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000499
David Chisnalld7972f52011-03-23 16:36:54 +0000500CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
501 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000502 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
503 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
504 ProtocolVersion(protocolClassVersion) {
David Chisnalld7972f52011-03-23 16:36:54 +0000505
David Chisnall01aa4672010-04-28 19:33:36 +0000506
507 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
508
David Chisnalld7972f52011-03-23 16:36:54 +0000509 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000510 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000511 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000512 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000513 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000514 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000515 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000516 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000517 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000518 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000519
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000520 Int8Ty = llvm::Type::getInt8Ty(VMContext);
521 // C string type. Used in lots of places.
522 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
523
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000524 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000525 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000526 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000527 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000528 QualType selTy = CGM.getContext().getObjCSelType();
529 if (QualType() == selTy) {
530 SelectorTy = PtrToInt8Ty;
531 } else {
532 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
533 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000534
Owen Anderson9793f0e2009-07-29 22:16:19 +0000535 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000536 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattner4bd55962008-03-30 23:03:07 +0000538 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000539 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000540 if (QualType() == ASTIdTy) {
541 IdTy = PtrToInt8Ty;
542 } else {
543 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
544 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000545 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000546
David Chisnall76803412011-03-23 22:52:06 +0000547 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
548 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
549
David Chisnalld7972f52011-03-23 16:36:54 +0000550 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
551
552 // void objc_exception_throw(id);
553 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
554 // int objc_sync_enter(id);
555 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
556 // int objc_sync_exit(id);
557 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
558
559 // void objc_enumerationMutation (id)
560 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
561 IdTy, NULL);
562
563 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
564 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
565 PtrDiffTy, BoolTy, NULL);
566 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
567 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
568 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
569 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
570 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
571 PtrDiffTy, BoolTy, BoolTy, NULL);
572 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
573 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
574 PtrDiffTy, BoolTy, BoolTy, NULL);
575
Chris Lattner4bd55962008-03-30 23:03:07 +0000576 // IMP type
577 std::vector<const llvm::Type*> IMPArgs;
578 IMPArgs.push_back(IdTy);
579 IMPArgs.push_back(SelectorTy);
David Chisnall76803412011-03-23 22:52:06 +0000580 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
581 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000582
583 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
584 // Get selectors needed in GC mode
585 RetainSel = GetNullarySelector("retain", CGM.getContext());
586 ReleaseSel = GetNullarySelector("release", CGM.getContext());
587 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
588
589 // Get functions needed in GC mode
590
591 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000592 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
593 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000594 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000595 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
596 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000597 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000598 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
599 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000600 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000601 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000602 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000603 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000604 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000605 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
606 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000607 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000608}
Mike Stumpdd93a192009-07-31 21:31:32 +0000609
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000610// This has to perform the lookup every time, since posing and related
611// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000612llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000613 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000614 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000615 // With the incompatible ABI, this will need to be replaced with a direct
616 // reference to the class symbol. For the compatible nonfragile ABI we are
617 // still performing this lookup at run time but emitting the symbol for the
618 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000619 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000620 ClassName = Builder.CreateStructGEP(ClassName, 0);
621
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000622 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000623 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000624 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000625 Params,
626 true),
627 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000628 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000629}
630
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000631llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000632 const std::string &TypeEncoding, bool lval) {
633
634 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
635 llvm::GlobalAlias *SelValue = 0;
636
637
638 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
639 e = Types.end() ; i!=e ; i++) {
640 if (i->first == TypeEncoding) {
641 SelValue = i->second;
642 break;
643 }
644 }
645 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000646 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000647 llvm::GlobalValue::PrivateLinkage,
648 ".objc_selector_"+Sel.getAsString(), NULL,
649 &TheModule);
650 Types.push_back(TypedSelector(TypeEncoding, SelValue));
651 }
652
David Chisnall76803412011-03-23 22:52:06 +0000653 if (lval) {
654 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
655 Builder.CreateStore(SelValue, tmp);
656 return tmp;
657 }
658 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000659}
660
661llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
662 bool lval) {
663 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000664}
665
Daniel Dunbar45858d22010-02-03 20:11:42 +0000666llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000667 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000668 std::string SelTypes;
669 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000670 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000671}
672
John McCall2ca705e2010-07-24 00:37:23 +0000673llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalle1d2584d2011-03-20 21:35:39 +0000674 // For Objective-C++, we want to provide the ability to catch both C++ and
675 // Objective-C objects in the same function.
676
677 // There's a particular fixed type info for 'id'.
678 if (T->isObjCIdType() ||
679 T->isObjCQualifiedIdType()) {
680 llvm::Constant *IDEHType =
681 CGM.getModule().getGlobalVariable("__objc_id_type_info");
682 if (!IDEHType)
683 IDEHType =
684 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
685 false,
686 llvm::GlobalValue::ExternalLinkage,
687 0, "__objc_id_type_info");
688 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
689 }
690
691 const ObjCObjectPointerType *PT =
692 T->getAs<ObjCObjectPointerType>();
693 assert(PT && "Invalid @catch type.");
694 const ObjCInterfaceType *IT = PT->getInterfaceType();
695 assert(IT && "Invalid @catch type.");
696 std::string className = IT->getDecl()->getIdentifier()->getName();
697
698 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
699
700 // Return the existing typeinfo if it exists
701 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
702 if (typeinfo) return typeinfo;
703
704 // Otherwise create it.
705
706 // vtable for gnustep::libobjc::__objc_class_type_info
707 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
708 // platform's name mangling.
709 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
710 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
711 if (!Vtable) {
712 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
713 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
714 }
715 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
716 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
717 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
718
719 llvm::Constant *typeName =
720 ExportUniqueString(className, "__objc_eh_typename_");
721
722 std::vector<llvm::Constant*> fields;
723 fields.push_back(Vtable);
724 fields.push_back(typeName);
725 llvm::Constant *TI =
726 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
727 NULL), fields, "__objc_eh_typeinfo_" + className,
728 llvm::GlobalValue::LinkOnceODRLinkage);
729 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000730}
731
Chris Lattnerd9b98862008-06-26 04:44:19 +0000732llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
733 const std::string &Name) {
David Chisnall5778fce2009-08-31 16:41:57 +0000734 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Andersonade90fd2009-07-29 18:54:39 +0000735 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000736}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000737llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
738 const std::string prefix) {
739 std::string name = prefix + Str;
740 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
741 if (!ConstStr) {
742 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
743 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
744 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
745 }
746 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
747}
Mike Stumpdd93a192009-07-31 21:31:32 +0000748
David Chisnalld7972f52011-03-23 16:36:54 +0000749llvm::GlobalVariable *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000750 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000751 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson0e0189d2009-07-27 22:29:56 +0000752 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000753 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall82f755c2010-11-09 11:21:43 +0000754 linkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000755}
Mike Stumpdd93a192009-07-31 21:31:32 +0000756
David Chisnalld7972f52011-03-23 16:36:54 +0000757llvm::GlobalVariable *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000758 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000759 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson47034e12009-07-28 18:33:04 +0000760 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000761 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall82f755c2010-11-09 11:21:43 +0000762 linkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000763}
David Chisnalld7972f52011-03-23 16:36:54 +0000764llvm::GlobalVariable *CGObjCGNU::MakeGlobalArray(const llvm::Type *Ty,
765 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
766 llvm::GlobalValue::LinkageTypes linkage) {
767 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
768 return MakeGlobal(ArrayTy, V, Name, linkage);
769}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000770/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000771llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000772
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000773 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000774
David Chisnall358e7512010-01-27 12:49:23 +0000775 // Look for an existing one
776 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
777 if (old != ObjCStrings.end())
778 return old->getValue();
779
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000780 std::vector<llvm::Constant*> Ivars;
781 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000782 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000783 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000784 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000785 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000786 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000787 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
788 ObjCStrings[Str] = ObjCStr;
789 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000790 return ObjCStr;
791}
792
793///Generates a message send where the super is the receiver. This is a message
794///send to self with special delivery semantics indicating which class's method
795///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000796RValue
797CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000798 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000799 QualType ResultType,
800 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000801 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000802 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000803 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000804 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000805 const CallArgList &CallArgs,
806 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000807 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
808 if (Sel == RetainSel || Sel == AutoreleaseSel) {
809 return RValue::get(Receiver);
810 }
811 if (Sel == ReleaseSel) {
812 return RValue::get(0);
813 }
814 }
David Chisnallea529a42010-05-01 12:37:16 +0000815
816 CGBuilderTy &Builder = CGF.Builder;
817 llvm::Value *cmd = GetSelector(Builder, Sel);
818
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000819
820 CallArgList ActualArgs;
821
822 ActualArgs.push_back(
David Chisnall76803412011-03-23 22:52:06 +0000823 std::make_pair(RValue::get(EnforceType(Builder, Receiver, IdTy)),
David Chisnall9f57c292009-08-17 16:35:33 +0000824 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000825 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
826 CGF.getContext().getObjCSelType()));
827 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
828
829 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000830 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000831 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000832
Daniel Dunbar566421c2009-05-04 15:31:17 +0000833 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000834 if (isCategoryImpl) {
835 llvm::Constant *classLookupFunction = 0;
836 std::vector<const llvm::Type*> Params;
837 Params.push_back(PtrTy);
838 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000839 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000840 IdTy, Params, true), "objc_get_meta_class");
841 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000842 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000843 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000844 }
David Chisnallea529a42010-05-01 12:37:16 +0000845 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000846 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000847 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000848 // Set up global aliases for the metaclass or class pointer if they do not
849 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000850 // pointers to the class and metaclass structure created for the runtime
851 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000852 // super_class pointer from either the class or metaclass structure.
853 if (IsClassMessage) {
854 if (!MetaClassPtrAlias) {
855 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
856 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
857 Class->getNameAsString(), NULL, &TheModule);
858 }
859 ReceiverClass = MetaClassPtrAlias;
860 } else {
861 if (!ClassPtrAlias) {
862 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
863 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
864 Class->getNameAsString(), NULL, &TheModule);
865 }
866 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000867 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000868 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000869 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +0000870 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000871 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000872 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000873 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000874 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +0000875 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000876 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000877 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000878 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
879 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +0000880 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000881
David Chisnallea529a42010-05-01 12:37:16 +0000882 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
883 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000884
David Chisnall76803412011-03-23 22:52:06 +0000885 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
886 const llvm::FunctionType *impType =
887 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
888
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000889 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +0000890 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
891 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000892
David Chisnall9eecafa2010-05-01 11:15:56 +0000893 llvm::Value *impMD[] = {
894 llvm::MDString::get(VMContext, Sel.getAsString()),
895 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
896 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
897 };
898 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
899
David Chisnallff5f88c2010-05-02 13:41:58 +0000900 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +0000901 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000902 0, &call);
903 call->setMetadata(msgSendMDKind, node);
904 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000905}
906
Mike Stump11289f42009-09-09 15:08:12 +0000907/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +0000908RValue
909CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000910 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000911 QualType ResultType,
912 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000913 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000914 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000915 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000916 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +0000917 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000918 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
919 if (Sel == RetainSel || Sel == AutoreleaseSel) {
920 return RValue::get(Receiver);
921 }
922 if (Sel == ReleaseSel) {
923 return RValue::get(0);
924 }
925 }
David Chisnall75afda62010-04-27 15:08:48 +0000926
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000927 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +0000928
929 // If the return type is something that goes in an integer register, the
930 // runtime will handle 0 returns. For other cases, we fill in the 0 value
931 // ourselves.
932 //
933 // The language spec says the result of this kind of message send is
934 // undefined, but lots of people seem to have forgotten to read that
935 // paragraph and insist on sending messages to nil that have structure
936 // returns. With GCC, this generates a random return value (whatever happens
937 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +0000938 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
939 // the stack.
940 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
941 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +0000942
943 llvm::BasicBlock *startBB = 0;
944 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +0000945 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +0000946
947 if (!isPointerSizedReturn) {
948 startBB = Builder.GetInsertBlock();
949 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +0000950 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +0000951
952 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
953 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +0000954 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +0000955 CGF.EmitBlock(messageBB);
956 }
957
David Chisnall9f57c292009-08-17 16:35:33 +0000958 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000959 llvm::Value *cmd;
960 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000961 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000962 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000963 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +0000964 cmd = EnforceType(Builder, cmd, SelectorTy);
965 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000966
David Chisnall76803412011-03-23 22:52:06 +0000967 llvm::Value *impMD[] = {
968 llvm::MDString::get(VMContext, Sel.getAsString()),
969 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
970 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
971 };
972 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
973
974 // Get the IMP to call
975 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
976
977 CallArgList ActualArgs;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000978 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000979 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000980 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
981 CGF.getContext().getObjCSelType()));
982 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
983
984 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000985 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000986 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000987 const llvm::FunctionType *impType =
988 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +0000989 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +0000990
991
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000992 // For sender-aware dispatch, we pass the sender as the third argument to a
993 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000994 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +0000995 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +0000996 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000997 0, &call);
998 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +0000999
David Chisnall29cefd12010-05-20 13:45:48 +00001000
David Chisnall75afda62010-04-27 15:08:48 +00001001 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001002 messageBB = CGF.Builder.GetInsertBlock();
1003 CGF.Builder.CreateBr(continueBB);
1004 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001005 if (msgRet.isScalar()) {
1006 llvm::Value *v = msgRet.getScalarVal();
1007 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
1008 phi->addIncoming(v, messageBB);
1009 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1010 msgRet = RValue::get(phi);
1011 } else if (msgRet.isAggregate()) {
1012 llvm::Value *v = msgRet.getAggregateAddr();
1013 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
1014 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001015 llvm::AllocaInst *NullVal =
1016 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001017 CGF.InitTempAlloca(NullVal,
1018 llvm::Constant::getNullValue(RetTy->getElementType()));
1019 phi->addIncoming(v, messageBB);
1020 phi->addIncoming(NullVal, startBB);
1021 msgRet = RValue::getAggregate(phi);
1022 } else /* isComplex() */ {
1023 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1024 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
1025 phi->addIncoming(v.first, messageBB);
1026 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1027 startBB);
1028 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
1029 phi2->addIncoming(v.second, messageBB);
1030 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1031 startBB);
1032 msgRet = RValue::getComplex(phi, phi2);
1033 }
1034 }
1035 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001036}
1037
Mike Stump11289f42009-09-09 15:08:12 +00001038/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001039/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +00001040llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1041 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +00001042 const llvm::SmallVectorImpl<Selector> &MethodSels,
1043 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001044 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001045 if (MethodSels.empty())
1046 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001047 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001048 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001049 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1050 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001051 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001052 NULL);
1053 std::vector<llvm::Constant*> Methods;
1054 std::vector<llvm::Constant*> Elements;
1055 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1056 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001057 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001058 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001059 MethodSels[i],
1060 isClassMethodList));
1061 assert(Method && "Can't generate metadata for method that doesn't exist");
1062 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1063 Elements.push_back(C);
1064 Elements.push_back(MethodTypes[i]);
1065 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001066 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001067 Elements.push_back(Method);
1068 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001069 }
1070
1071 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001072 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001073 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001074 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001075 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001076
1077 // Structure containing list pointer, array and array count
1078 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001079 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001080 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001081 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001082 NextPtrTy,
1083 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001084 ObjCMethodArrayTy,
1085 NULL);
1086 // Refine next pointer type to concrete type
1087 llvm::cast<llvm::OpaqueType>(
1088 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1089 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1090
1091 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001092 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001093 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001094 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001095 MethodTypes.size()));
1096 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001097
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001098 // Create an instance of the structure
1099 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1100}
1101
1102/// Generates an IvarList. Used in construction of a objc_class.
1103llvm::Constant *CGObjCGNU::GenerateIvarList(
1104 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1105 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1106 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001107 if (IvarNames.size() == 0)
1108 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001109 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001110 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001111 PtrToInt8Ty,
1112 PtrToInt8Ty,
1113 IntTy,
1114 NULL);
1115 std::vector<llvm::Constant*> Ivars;
1116 std::vector<llvm::Constant*> Elements;
1117 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1118 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001119 Elements.push_back(IvarNames[i]);
1120 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001121 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001122 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001123 }
1124
1125 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001126 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001127 IvarNames.size());
1128
Mike Stump11289f42009-09-09 15:08:12 +00001129
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001130 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001131 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001132 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001133 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001134 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001135 ObjCIvarArrayTy,
1136 NULL);
1137
1138 // Create an instance of the structure
1139 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1140}
1141
1142/// Generate a class structure
1143llvm::Constant *CGObjCGNU::GenerateClassStructure(
1144 llvm::Constant *MetaClass,
1145 llvm::Constant *SuperClass,
1146 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001147 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001148 llvm::Constant *Version,
1149 llvm::Constant *InstanceSize,
1150 llvm::Constant *IVars,
1151 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001152 llvm::Constant *Protocols,
1153 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001154 llvm::Constant *Properties,
1155 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001156 // Set up the class structure
1157 // Note: Several of these are char*s when they should be ids. This is
1158 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001159 //
1160 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1161 // anyway; the classes will still work with the GNU runtime, they will just
1162 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001163 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001164 PtrToInt8Ty, // class_pointer
1165 PtrToInt8Ty, // super_class
1166 PtrToInt8Ty, // name
1167 LongTy, // version
1168 LongTy, // info
1169 LongTy, // instance_size
1170 IVars->getType(), // ivars
1171 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001172 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001173 PtrTy, // dtable
1174 PtrTy, // subclass_list
1175 PtrTy, // sibling_class
1176 PtrTy, // protocols
1177 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001178 // New ABI:
1179 LongTy, // abi_version
1180 IvarOffsets->getType(), // ivar_offsets
1181 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001182 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001183 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001184 // Fill in the structure
1185 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001186 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001187 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001188 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001189 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001190 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001191 if (isMeta) {
1192 llvm::TargetData td(&TheModule);
1193 Elements.push_back(llvm::ConstantInt::get(LongTy,
1194 td.getTypeSizeInBits(ClassTy)/8));
1195 } else
1196 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001197 Elements.push_back(IVars);
1198 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001199 Elements.push_back(NULLPtr);
1200 Elements.push_back(NULLPtr);
1201 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001202 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001203 Elements.push_back(NULLPtr);
1204 Elements.push_back(Zero);
1205 Elements.push_back(IvarOffsets);
1206 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001207 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001208 // This is now an externally visible symbol, so that we can speed up class
1209 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001210 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1211 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001212}
1213
1214llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1215 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1216 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001217 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001218 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001219 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1220 PtrToInt8Ty,
1221 NULL);
1222 std::vector<llvm::Constant*> Methods;
1223 std::vector<llvm::Constant*> Elements;
1224 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1225 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001226 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001227 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001228 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001229 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001230 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001231 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001232 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001233 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001234 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001235 IntTy, ObjCMethodArrayTy, NULL);
1236 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001237 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001238 Methods.push_back(Array);
1239 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1240}
Mike Stumpdd93a192009-07-31 21:31:32 +00001241
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001242// Create the protocol list structure used in classes, categories and so on
1243llvm::Constant *CGObjCGNU::GenerateProtocolList(
1244 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001245 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001246 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001247 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001248 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001249 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001250 ProtocolArrayTy,
1251 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001252 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001253 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1254 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001255 llvm::Constant *protocol = 0;
1256 llvm::StringMap<llvm::Constant*>::iterator value =
1257 ExistingProtocols.find(*iter);
1258 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001259 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001260 } else {
1261 protocol = value->getValue();
1262 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001263 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001264 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001265 Elements.push_back(Ptr);
1266 }
Owen Anderson47034e12009-07-28 18:33:04 +00001267 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001268 Elements);
1269 Elements.clear();
1270 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001271 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001272 Elements.push_back(ProtocolArray);
1273 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1274}
1275
Mike Stump11289f42009-09-09 15:08:12 +00001276llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001277 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001278 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001279 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001280 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001281 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001282}
1283
1284llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1285 const std::string &ProtocolName) {
1286 llvm::SmallVector<std::string, 0> EmptyStringVector;
1287 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1288
1289 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001290 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001291 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1292 // Protocols are objects containing lists of the methods implemented and
1293 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001294 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001295 PtrToInt8Ty,
1296 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001297 MethodList->getType(),
1298 MethodList->getType(),
1299 MethodList->getType(),
1300 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001301 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001302 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001303 // The isa pointer must be set to a magic number so the runtime knows it's
1304 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001305 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001306 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1307 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001308 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1309 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001310 Elements.push_back(MethodList);
1311 Elements.push_back(MethodList);
1312 Elements.push_back(MethodList);
1313 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001314 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001315}
1316
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001317void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1318 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001319 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001320 llvm::SmallVector<std::string, 16> Protocols;
1321 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1322 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001323 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001324 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1325 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001326 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1327 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001328 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1329 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001330 std::string TypeStr;
1331 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001332 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1333 InstanceMethodNames.push_back(
1334 MakeConstantString((*iter)->getSelector().getAsString()));
1335 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1336 } else {
1337 OptionalInstanceMethodNames.push_back(
1338 MakeConstantString((*iter)->getSelector().getAsString()));
1339 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1340 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001341 }
1342 // Collect information about class methods:
1343 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1344 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001345 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1346 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001347 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001348 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1349 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001350 std::string TypeStr;
1351 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001352 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1353 ClassMethodNames.push_back(
1354 MakeConstantString((*iter)->getSelector().getAsString()));
1355 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1356 } else {
1357 OptionalClassMethodNames.push_back(
1358 MakeConstantString((*iter)->getSelector().getAsString()));
1359 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1360 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001361 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001362
1363 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1364 llvm::Constant *InstanceMethodList =
1365 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1366 llvm::Constant *ClassMethodList =
1367 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001368 llvm::Constant *OptionalInstanceMethodList =
1369 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1370 OptionalInstanceMethodTypes);
1371 llvm::Constant *OptionalClassMethodList =
1372 GenerateProtocolMethodList(OptionalClassMethodNames,
1373 OptionalClassMethodTypes);
1374
1375 // Property metadata: name, attributes, isSynthesized, setter name, setter
1376 // types, getter name, getter types.
1377 // The isSynthesized value is always set to 0 in a protocol. It exists to
1378 // simplify the runtime library by allowing it to use the same data
1379 // structures for protocol metadata everywhere.
1380 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1381 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1382 PtrToInt8Ty, NULL);
1383 std::vector<llvm::Constant*> Properties;
1384 std::vector<llvm::Constant*> OptionalProperties;
1385
1386 // Add all of the property methods need adding to the method list and to the
1387 // property metadata list.
1388 for (ObjCContainerDecl::prop_iterator
1389 iter = PD->prop_begin(), endIter = PD->prop_end();
1390 iter != endIter ; iter++) {
1391 std::vector<llvm::Constant*> Fields;
1392 ObjCPropertyDecl *property = (*iter);
1393
1394 Fields.push_back(MakeConstantString(property->getNameAsString()));
1395 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1396 property->getPropertyAttributes()));
1397 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1398 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1399 std::string TypeStr;
1400 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1401 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1402 InstanceMethodTypes.push_back(TypeEncoding);
1403 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1404 Fields.push_back(TypeEncoding);
1405 } else {
1406 Fields.push_back(NULLPtr);
1407 Fields.push_back(NULLPtr);
1408 }
1409 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1410 std::string TypeStr;
1411 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1412 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1413 InstanceMethodTypes.push_back(TypeEncoding);
1414 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1415 Fields.push_back(TypeEncoding);
1416 } else {
1417 Fields.push_back(NULLPtr);
1418 Fields.push_back(NULLPtr);
1419 }
1420 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1421 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1422 } else {
1423 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1424 }
1425 }
1426 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1427 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1428 llvm::Constant* PropertyListInitFields[] =
1429 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1430
1431 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001432 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001433 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1434 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1435 PropertyListInit, ".objc_property_list");
1436
1437 llvm::Constant *OptionalPropertyArray =
1438 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1439 OptionalProperties.size()) , OptionalProperties);
1440 llvm::Constant* OptionalPropertyListInitFields[] = {
1441 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1442 OptionalPropertyArray };
1443
1444 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001445 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001446 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1447 OptionalPropertyListInit->getType(), false,
1448 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1449 ".objc_property_list");
1450
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001451 // Protocols are objects containing lists of the methods implemented and
1452 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001453 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001454 PtrToInt8Ty,
1455 ProtocolList->getType(),
1456 InstanceMethodList->getType(),
1457 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001458 OptionalInstanceMethodList->getType(),
1459 OptionalClassMethodList->getType(),
1460 PropertyList->getType(),
1461 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001462 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001463 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001464 // The isa pointer must be set to a magic number so the runtime knows it's
1465 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001466 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001467 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1468 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001469 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1470 Elements.push_back(ProtocolList);
1471 Elements.push_back(InstanceMethodList);
1472 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001473 Elements.push_back(OptionalInstanceMethodList);
1474 Elements.push_back(OptionalClassMethodList);
1475 Elements.push_back(PropertyList);
1476 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001477 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001478 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001479 ".objc_protocol"), IdTy);
1480}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001481void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1482 // Collect information about instance methods
1483 llvm::SmallVector<Selector, 1> MethodSels;
1484 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1485
1486 std::vector<llvm::Constant*> Elements;
1487 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1488 const std::string CategoryName = "AnotherHack";
1489 Elements.push_back(MakeConstantString(CategoryName));
1490 Elements.push_back(MakeConstantString(ClassName));
1491 // Instance method list
1492 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1493 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1494 // Class method list
1495 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1496 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1497 // Protocol list
1498 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1499 ExistingProtocols.size());
1500 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1501 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001502 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001503 ProtocolArrayTy,
1504 NULL);
1505 std::vector<llvm::Constant*> ProtocolElements;
1506 for (llvm::StringMapIterator<llvm::Constant*> iter =
1507 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1508 iter != endIter ; iter++) {
1509 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1510 PtrTy);
1511 ProtocolElements.push_back(Ptr);
1512 }
1513 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1514 ProtocolElements);
1515 ProtocolElements.clear();
1516 ProtocolElements.push_back(NULLPtr);
1517 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1518 ExistingProtocols.size()));
1519 ProtocolElements.push_back(ProtocolArray);
1520 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1521 ProtocolElements, ".objc_protocol_list"), PtrTy));
1522 Categories.push_back(llvm::ConstantExpr::getBitCast(
1523 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1524 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1525}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001526
Daniel Dunbar92992502008-08-15 22:20:32 +00001527void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001528 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1529 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001530 // Collect information about instance methods
1531 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1532 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001533 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001534 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001535 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001536 InstanceMethodSels.push_back((*iter)->getSelector());
1537 std::string TypeStr;
1538 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001539 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001540 }
1541
1542 // Collect information about class methods
1543 llvm::SmallVector<Selector, 16> ClassMethodSels;
1544 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001545 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001546 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001547 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001548 ClassMethodSels.push_back((*iter)->getSelector());
1549 std::string TypeStr;
1550 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001551 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001552 }
1553
1554 // Collect the names of referenced protocols
1555 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001556 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1557 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001558 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1559 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001560 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001561
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001562 std::vector<llvm::Constant*> Elements;
1563 Elements.push_back(MakeConstantString(CategoryName));
1564 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001565 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001566 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001567 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001568 false), PtrTy));
1569 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001570 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001571 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001572 PtrTy));
1573 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001574 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001575 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001576 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001577 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001578 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001579}
Daniel Dunbar92992502008-08-15 22:20:32 +00001580
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001581llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1582 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1583 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1584 ASTContext &Context = CGM.getContext();
1585 //
1586 // Property metadata: name, attributes, isSynthesized, setter name, setter
1587 // types, getter name, getter types.
1588 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1589 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1590 PtrToInt8Ty, NULL);
1591 std::vector<llvm::Constant*> Properties;
1592
1593
1594 // Add all of the property methods need adding to the method list and to the
1595 // property metadata list.
1596 for (ObjCImplDecl::propimpl_iterator
1597 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1598 iter != endIter ; iter++) {
1599 std::vector<llvm::Constant*> Fields;
1600 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001601 ObjCPropertyImplDecl *propertyImpl = *iter;
1602 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1603 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001604
1605 Fields.push_back(MakeConstantString(property->getNameAsString()));
1606 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1607 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001608 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001609 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001610 std::string TypeStr;
1611 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1612 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001613 if (isSynthesized) {
1614 InstanceMethodTypes.push_back(TypeEncoding);
1615 InstanceMethodSels.push_back(getter->getSelector());
1616 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001617 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1618 Fields.push_back(TypeEncoding);
1619 } else {
1620 Fields.push_back(NULLPtr);
1621 Fields.push_back(NULLPtr);
1622 }
1623 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001624 std::string TypeStr;
1625 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1626 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001627 if (isSynthesized) {
1628 InstanceMethodTypes.push_back(TypeEncoding);
1629 InstanceMethodSels.push_back(setter->getSelector());
1630 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001631 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1632 Fields.push_back(TypeEncoding);
1633 } else {
1634 Fields.push_back(NULLPtr);
1635 Fields.push_back(NULLPtr);
1636 }
1637 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1638 }
1639 llvm::ArrayType *PropertyArrayTy =
1640 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1641 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1642 Properties);
1643 llvm::Constant* PropertyListInitFields[] =
1644 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1645
1646 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001647 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001648 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1649 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1650 ".objc_property_list");
1651}
1652
Daniel Dunbar92992502008-08-15 22:20:32 +00001653void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1654 ASTContext &Context = CGM.getContext();
1655
1656 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001657 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001658 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001659 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001660 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001661 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001662 EmitClassRef(SuperClassName);
1663 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001664
1665 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001666 ObjCInterfaceDecl *ClassDecl =
1667 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001668 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001669 // Emit the symbol that is used to generate linker errors if this class is
1670 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001671 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001672 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001673 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001674 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001675 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001676 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001677 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001678 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001679 }
Mike Stump11289f42009-09-09 15:08:12 +00001680
Daniel Dunbar12119b92009-05-03 10:46:44 +00001681 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001682 int instanceSize =
1683 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001684
1685 // Collect information about instance variables.
1686 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1687 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1688 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001689
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001690 std::vector<llvm::Constant*> IvarOffsetValues;
1691
Mike Stump11289f42009-09-09 15:08:12 +00001692 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001693 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001694 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1695 // class}. The runtime will then set this to the correct value on load.
1696 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1697 instanceSize = 0 - (instanceSize - superInstanceSize);
1698 }
David Chisnall18cf7372010-04-19 00:45:34 +00001699
1700 // Collect declared and synthesized ivars.
1701 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1702 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1703
1704 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1705 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001706 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001707 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001708 // Get the type encoding for this ivar
1709 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001710 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001711 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001712 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001713 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001714 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001715 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001716 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001717 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001718 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001719 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001720 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1721 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00001722 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001723 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001724 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001725 }
David Chisnalld7972f52011-03-23 16:36:54 +00001726 llvm::GlobalVariable *IvarOffsetArray =
1727 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1728
Daniel Dunbar92992502008-08-15 22:20:32 +00001729
1730 // Collect information about instance methods
1731 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1732 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001733 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001734 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001735 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001736 InstanceMethodSels.push_back((*iter)->getSelector());
1737 std::string TypeStr;
1738 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001739 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001740 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001741
1742 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1743 InstanceMethodTypes);
1744
Daniel Dunbar92992502008-08-15 22:20:32 +00001745
1746 // Collect information about class methods
1747 llvm::SmallVector<Selector, 16> ClassMethodSels;
1748 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001749 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001750 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001751 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001752 ClassMethodSels.push_back((*iter)->getSelector());
1753 std::string TypeStr;
1754 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001755 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001756 }
1757 // Collect the names of referenced protocols
1758 llvm::SmallVector<std::string, 16> Protocols;
1759 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1760 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1761 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001762 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001763
1764
1765
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001766 // Get the superclass pointer.
1767 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001768 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001769 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1770 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001771 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001772 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001773 // Empty vector used to construct empty method lists
1774 llvm::SmallVector<llvm::Constant*, 1> empty;
1775 // Generate the method and instance variable lists
1776 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001777 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001778 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001779 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001780 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1781 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001782 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001783 // we emit a symbol containing the offset for each ivar in the class. This
1784 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1785 // for the legacy ABI, without causing problems. The converse is also
1786 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001787
David Chisnall5778fce2009-08-31 16:41:57 +00001788 // Offset pointer for getting at the correct field in the ivar list when
1789 // setting up the alias. These are: The base address for the global, the
1790 // ivar array (second field), the ivar in this list (set for each ivar), and
1791 // the offset (third field in ivar structure)
1792 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1793 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001794 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001795 llvm::ConstantInt::get(IndexTy, 2) };
1796
David Chisnalle8431a72010-11-03 16:12:44 +00001797
1798 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1799 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00001800 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001801 + IVD->getNameAsString();
1802 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00001803 // Get the correct ivar field
1804 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1805 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00001806 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001807 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1808 if (offset) {
1809 offset->setInitializer(offsetValue);
1810 // If this is the real definition, change its linkage type so that
1811 // different modules will use this one, rather than their private
1812 // copy.
1813 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1814 } else {
1815 // Add a new alias if there isn't one already.
1816 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1817 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1818 }
1819 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001820 //Generate metaclass for class methods
1821 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001822 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001823 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001824
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001825 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001826 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001827 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001828 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001829 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001830 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1831 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001832
1833 // Resolve the class aliases, if they exist.
1834 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001835 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001836 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001837 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001838 ClassPtrAlias = 0;
1839 }
1840 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001841 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001842 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001843 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001844 MetaClassPtrAlias = 0;
1845 }
1846
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001847 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001848 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001849 Classes.push_back(ClassStruct);
1850}
1851
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001852
Mike Stump11289f42009-09-09 15:08:12 +00001853llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001854 // Only emit an ObjC load function if no Objective-C stuff has been called
1855 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00001856 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001857 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001858
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001859 // Add all referenced protocols to a category.
1860 GenerateProtocolHolderCategory();
1861
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001862 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1863 SelectorTy->getElementType());
1864 const llvm::Type *SelStructPtrTy = SelectorTy;
1865 bool isSelOpaque = false;
1866 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001867 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1868 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001869 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001870 isSelOpaque = true;
1871 }
1872
Eli Friedman412c6682008-06-01 16:00:02 +00001873 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001874 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001875 TheModule.addTypeName(".objc_id", IdTy);
1876 TheModule.addTypeName(".objc_imp", IMPTy);
1877
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001878 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001879 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001880 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001881 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001882 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001883 ConstantStrings.size() + 1);
1884 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001885
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001886 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00001887
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001888 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00001889
David Chisnall5778fce2009-08-31 16:41:57 +00001890 Elements.push_back(MakeConstantString(StringClass,
1891 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001892 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001893 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001894 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001895 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001896 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001897 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001898 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001899 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001900 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001901 Elements.clear();
1902 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001903 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001904 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001905 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001906 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001907 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001908 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001909 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001910 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001911 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001912 llvm::Type::getInt16Ty(VMContext),
1913 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001914 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001915
1916 Elements.clear();
1917 // Pointer to an array of selectors used in this module.
1918 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00001919 std::vector<llvm::GlobalAlias*> SelectorAliases;
1920 for (SelectorMap::iterator iter = SelectorTable.begin(),
1921 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
1922
1923 std::string SelNameStr = iter->first.getAsString();
1924 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
1925
1926 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
1927 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1928 e = Types.end() ; i!=e ; i++) {
1929
1930 llvm::Constant *SelectorTypeEncoding = NULLPtr;
1931 if (!i->first.empty())
1932 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
1933
1934 Elements.push_back(SelName);
1935 Elements.push_back(SelectorTypeEncoding);
1936 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1937 Elements.clear();
1938
1939 // Store the selector alias for later replacement
1940 SelectorAliases.push_back(i->second);
1941 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001942 }
David Chisnalld7972f52011-03-23 16:36:54 +00001943 unsigned SelectorCount = Selectors.size();
1944 // NULL-terminate the selector list. This should not actually be required,
1945 // because the selector list has a length field. Unfortunately, the GCC
1946 // runtime decides to ignore the length field and expects a NULL terminator,
1947 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001948 Elements.push_back(NULLPtr);
1949 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001950 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001951 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001952
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001953 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00001954 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
1955 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001956 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00001957 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001958 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001959
1960 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00001961 for (unsigned int i=0 ; i<SelectorCount ; i++) {
1962
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001963 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00001964 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
1965 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00001966 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
1967 Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001968 // If selectors are defined as an opaque type, cast the pointer to this
1969 // type.
David Chisnall76803412011-03-23 22:52:06 +00001970 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001971 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
1972 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001973 }
David Chisnalld7972f52011-03-23 16:36:54 +00001974
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001975 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00001976 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001977 Classes.size()));
1978 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00001979 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001980 Categories.size()));
1981 // Create an array of classes, then categories, then static object instances
1982 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1983 // NULL-terminated list of static object instances (mainly constant strings)
1984 Classes.push_back(Statics);
1985 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00001986 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001987 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00001988 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001989 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1990
1991 // The symbol table is contained in a module which has some version-checking
1992 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00001993 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001994 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001995 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001996 // Runtime version, used for ABI compatibility checking.
1997 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00001998 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00001999 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002000 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00002001 td.getTypeSizeInBits(ModuleTy)/8));
David Chisnalld7972f52011-03-23 16:36:54 +00002002
2003 // The path to the source file where this module was declared
2004 SourceManager &SM = CGM.getContext().getSourceManager();
2005 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2006 std::string path =
2007 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2008 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2009
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002010 Elements.push_back(SymTab);
2011 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2012
2013 // Create the load function calling the runtime entry point with the module
2014 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002015 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002016 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002017 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2018 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002019 llvm::BasicBlock *EntryBB =
2020 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002021 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002022 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002023
2024 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002025 llvm::PointerType::getUnqual(ModuleTy));
2026 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00002027 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002028 Builder.CreateCall(Register, Module);
2029 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002030
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002031 return LoadFunction;
2032}
Daniel Dunbar92992502008-08-15 22:20:32 +00002033
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002034llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002035 const ObjCContainerDecl *CD) {
2036 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002037 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00002038 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2039 llvm::StringRef ClassName = CD->getName();
2040 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002041 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002042
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002043 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00002044 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002045 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002046 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2047 MethodName, isClassMethod);
2048
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002049 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002050 = llvm::Function::Create(MethodTy,
2051 llvm::GlobalValue::InternalLinkage,
2052 FunctionName,
2053 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002054 return Method;
2055}
2056
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002057llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002058 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002059}
2060
2061llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002062 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002063}
2064
David Chisnall168b80f2010-12-26 22:13:16 +00002065llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002066 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002067}
2068llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002069 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002070}
2071
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002072llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002073 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002074}
2075
John McCallc20acd32010-07-21 00:41:47 +00002076namespace {
John McCallcda666c2010-07-21 07:22:38 +00002077 struct CallSyncExit : EHScopeStack::Cleanup {
John McCallc20acd32010-07-21 00:41:47 +00002078 llvm::Value *SyncExitFn;
2079 llvm::Value *SyncArg;
2080 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
2081 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
2082
2083 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
2084 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
2085 }
2086 };
2087}
2088
David Chisnalld7972f52011-03-23 16:36:54 +00002089void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002090 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00002091 // Evaluate the lock operand. This should dominate the cleanup.
2092 llvm::Value *SyncArg =
2093 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002094
John McCallbd309292010-07-06 01:34:17 +00002095 // Acquire the lock.
John McCallbd309292010-07-06 01:34:17 +00002096 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002097 CGF.Builder.CreateCall(SyncEnterFn, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002098
John McCallbd309292010-07-06 01:34:17 +00002099 // Register an all-paths cleanup to release the lock.
David Chisnalld7972f52011-03-23 16:36:54 +00002100 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExitFn,
2101 SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002102
John McCallbd309292010-07-06 01:34:17 +00002103 // Emit the body of the statement.
2104 CGF.EmitStmt(S.getSynchBody());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002105
John McCallbd309292010-07-06 01:34:17 +00002106 // Pop the lock-release cleanup.
2107 CGF.PopCleanupBlock();
2108}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002109
John McCallbd309292010-07-06 01:34:17 +00002110namespace {
2111 struct CatchHandler {
2112 const VarDecl *Variable;
2113 const Stmt *Body;
2114 llvm::BasicBlock *Block;
2115 llvm::Value *TypeInfo;
2116 };
David Chisnalle1d2584d2011-03-20 21:35:39 +00002117
2118 struct CallObjCEndCatch : EHScopeStack::Cleanup {
2119 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
2120 MightThrow(MightThrow), Fn(Fn) {}
2121 bool MightThrow;
2122 llvm::Value *Fn;
2123
2124 void Emit(CodeGenFunction &CGF, bool IsForEH) {
2125 if (!MightThrow) {
2126 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
2127 return;
2128 }
2129
2130 CGF.EmitCallOrInvoke(Fn, 0, 0);
2131 }
2132 };
2133}
2134
David Chisnalld7972f52011-03-23 16:36:54 +00002135void CGObjCGNU::EmitObjCXXTryStmt(CodeGenFunction &CGF,
David Chisnalle1d2584d2011-03-20 21:35:39 +00002136 const ObjCAtTryStmt &S) {
2137 std::vector<const llvm::Type*> Args(1, PtrToInt8Ty);
2138 llvm::FunctionType *FTy = llvm::FunctionType::get(PtrToInt8Ty, Args, false);
2139 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2140
2141 llvm::Constant *beginCatchFn =
2142 CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
2143
2144 FTy = llvm::FunctionType::get(VoidTy, false);
2145 llvm::Constant *endCatchFn =
2146 CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
2147 FTy = llvm::FunctionType::get(VoidTy, Args, false);
2148 llvm::Constant *exceptionRethrowFn =
2149 CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
2150
2151 // Jump destination for falling out of catch bodies.
2152 CodeGenFunction::JumpDest Cont;
2153 if (S.getNumCatchStmts())
2154 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
2155
2156 CodeGenFunction::FinallyInfo FinallyInfo;
2157 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
2158 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(),
2159 beginCatchFn,
2160 endCatchFn,
2161 exceptionRethrowFn);
2162
2163 llvm::SmallVector<CatchHandler, 8> Handlers;
2164
2165 // Enter the catch, if there is one.
2166 if (S.getNumCatchStmts()) {
2167 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
2168 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
2169 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
2170
2171 Handlers.push_back(CatchHandler());
2172 CatchHandler &Handler = Handlers.back();
2173 Handler.Variable = CatchDecl;
2174 Handler.Body = CatchStmt->getCatchBody();
2175 Handler.Block = CGF.createBasicBlock("catch");
2176
2177 // @catch(...) always matches.
2178 if (!CatchDecl) {
2179 Handler.TypeInfo = 0; // catch-all
2180 // Don't consider any other catches.
2181 break;
2182 }
2183
2184 Handler.TypeInfo = GetEHType(CatchDecl->getType());
2185 }
2186
2187 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2188 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2189 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2190 }
2191
2192 // Emit the try body.
2193 CGF.EmitStmt(S.getTryBody());
2194
2195 // Leave the try.
2196 if (S.getNumCatchStmts())
2197 CGF.EHStack.popCatch();
2198
2199 // Remember where we were.
2200 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2201
2202 // Emit the handlers.
2203 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2204 CatchHandler &Handler = Handlers[I];
2205
2206 CGF.EmitBlock(Handler.Block);
2207 llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2208
2209 // Enter the catch.
2210 llvm::CallInst *Exn =
2211 CGF.Builder.CreateCall(beginCatchFn, RawExn,
2212 "exn.adjusted");
2213 Exn->setDoesNotThrow();
2214
2215 // Add a cleanup to leave the catch.
2216 bool EndCatchMightThrow = (Handler.Variable == 0);
2217 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
2218 EndCatchMightThrow,
2219 endCatchFn);
2220
2221 // Bind the catch parameter if it exists.
2222 if (const VarDecl *CatchParam = Handler.Variable) {
2223 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2224 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
2225
2226 CGF.EmitAutoVarDecl(*CatchParam);
2227 CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
2228 }
2229
2230 CGF.ObjCEHValueStack.push_back(Exn);
2231 CGF.EmitStmt(Handler.Body);
2232 CGF.ObjCEHValueStack.pop_back();
2233
2234 // Leave the earlier cleanup.
2235 CGF.PopCleanupBlock();
2236
2237 CGF.EmitBranchThroughCleanup(Cont);
2238 }
2239
2240 // Go back to the try-statement fallthrough.
2241 CGF.Builder.restoreIP(SavedIP);
2242
2243 // Pop out of the normal cleanup on the finally.
2244 if (S.getFinallyStmt())
2245 CGF.ExitFinallyBlock(FinallyInfo);
2246
2247 if (Cont.isValid())
2248 CGF.EmitBlock(Cont.getBlock());
John McCallbd309292010-07-06 01:34:17 +00002249}
David Chisnall3a509cd2009-12-24 02:26:34 +00002250
David Chisnalld7972f52011-03-23 16:36:54 +00002251void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002252 const ObjCAtTryStmt &S) {
2253 // Unlike the Apple non-fragile runtimes, which also uses
2254 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2255 // EH support isn't a veneer over C++ EH. Instead, exception
2256 // objects are created by __objc_exception_throw and destroyed by
2257 // the personality function; this avoids the need for bracketing
2258 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2259 // (or even _Unwind_DeleteException), but probably doesn't
2260 // interoperate very well with foreign exceptions.
2261
David Chisnalle1d2584d2011-03-20 21:35:39 +00002262 // In Objective-C++ mode, we actually emit something equivalent to the C++
2263 // exception handler.
2264 if (CGM.getLangOptions().CPlusPlus) {
2265 EmitObjCXXTryStmt(CGF, S);
2266 return;
2267 }
2268
John McCallbd309292010-07-06 01:34:17 +00002269 // Jump destination for falling out of catch bodies.
2270 CodeGenFunction::JumpDest Cont;
2271 if (S.getNumCatchStmts())
2272 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
2273
2274 // We handle @finally statements by pushing them as a cleanup
2275 // before entering the catch.
2276 CodeGenFunction::FinallyInfo FinallyInfo;
2277 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
John McCallbd309292010-07-06 01:34:17 +00002278 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
David Chisnalld7972f52011-03-23 16:36:54 +00002279 ExceptionThrowFn);
David Chisnall3a509cd2009-12-24 02:26:34 +00002280 }
Mike Stump11289f42009-09-09 15:08:12 +00002281
John McCallbd309292010-07-06 01:34:17 +00002282 llvm::SmallVector<CatchHandler, 8> Handlers;
2283
2284 // Enter the catch, if there is one.
2285 if (S.getNumCatchStmts()) {
2286 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
2287 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
2288 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
2289
2290 Handlers.push_back(CatchHandler());
2291 CatchHandler &Handler = Handlers.back();
2292 Handler.Variable = CatchDecl;
2293 Handler.Body = CatchStmt->getCatchBody();
2294 Handler.Block = CGF.createBasicBlock("catch");
2295
2296 // @catch() and @catch(id) both catch any ObjC exception.
2297 // Treat them as catch-alls.
John McCallbd309292010-07-06 01:34:17 +00002298 // really be catching foreign exceptions?
David Chisnall803adc12011-03-16 15:44:28 +00002299
2300 if (!CatchDecl) {
John McCallbd309292010-07-06 01:34:17 +00002301 Handler.TypeInfo = 0; // catch-all
John McCallbd309292010-07-06 01:34:17 +00002302 // Don't consider any other catches.
2303 break;
2304 }
David Chisnall803adc12011-03-16 15:44:28 +00002305 if (CatchDecl->getType()->isObjCIdType()
2306 || CatchDecl->getType()->isObjCQualifiedIdType()) {
2307 // With the old ABI, there was only one kind of catchall, which broke
2308 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2309 // a pointer indicating object catchalls, and NULL to indicate real
2310 // catchalls
2311 if (CGM.getLangOptions().ObjCNonFragileABI) {
2312 Handler.TypeInfo = MakeConstantString("@id");
2313 continue;
2314 } else {
2315 Handler.TypeInfo = 0; // catch-all
2316 // Don't consider any other catches.
2317 break;
2318 }
2319 }
John McCallbd309292010-07-06 01:34:17 +00002320
2321 // All other types should be Objective-C interface pointer types.
2322 const ObjCObjectPointerType *OPT =
2323 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
2324 assert(OPT && "Invalid @catch type.");
2325 const ObjCInterfaceDecl *IDecl =
2326 OPT->getObjectType()->getInterface();
2327 assert(IDecl && "Invalid @catch type.");
2328 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
2329 }
2330
2331 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2332 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2333 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2334 }
2335
2336 // Emit the try body.
2337 CGF.EmitStmt(S.getTryBody());
2338
2339 // Leave the try.
2340 if (S.getNumCatchStmts())
2341 CGF.EHStack.popCatch();
2342
2343 // Remember where we were.
2344 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2345
2346 // Emit the handlers.
2347 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2348 CatchHandler &Handler = Handlers[I];
2349 CGF.EmitBlock(Handler.Block);
2350
2351 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2352
2353 // Bind the catch parameter if it exists.
2354 if (const VarDecl *CatchParam = Handler.Variable) {
2355 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2356 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2357
John McCall1c9c3fd2010-10-15 04:57:14 +00002358 CGF.EmitAutoVarDecl(*CatchParam);
John McCallbd309292010-07-06 01:34:17 +00002359 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2360 }
2361
2362 CGF.ObjCEHValueStack.push_back(Exn);
2363 CGF.EmitStmt(Handler.Body);
2364 CGF.ObjCEHValueStack.pop_back();
2365
2366 CGF.EmitBranchThroughCleanup(Cont);
2367 }
2368
2369 // Go back to the try-statement fallthrough.
2370 CGF.Builder.restoreIP(SavedIP);
2371
2372 // Pop out of the finally.
2373 if (S.getFinallyStmt())
2374 CGF.ExitFinallyBlock(FinallyInfo);
2375
John McCallad5d61e2010-07-23 21:56:41 +00002376 if (Cont.isValid()) {
2377 if (Cont.getBlock()->use_empty())
2378 delete Cont.getBlock();
2379 else
2380 CGF.EmitBlock(Cont.getBlock());
John McCallbd309292010-07-06 01:34:17 +00002381 }
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002382}
2383
David Chisnalld7972f52011-03-23 16:36:54 +00002384void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002385 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002386 llvm::Value *ExceptionAsObject;
2387
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002388 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2389 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002390 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002391 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002392 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002393 "Unexpected rethrow outside @catch block.");
2394 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2395 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002396 ExceptionAsObject =
2397 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002399 // Note: This may have to be an invoke, if we want to support constructs like:
2400 // @try {
2401 // @throw(obj);
2402 // }
2403 // @catch(id) ...
2404 //
2405 // This is effectively turning @throw into an incredibly-expensive goto, but
2406 // it may happen as a result of inlining followed by missed optimizations, or
2407 // as a result of stupidity.
2408 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2409 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002410 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002411 CGF.Builder.CreateUnreachable();
2412 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002413 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002414 &ExceptionAsObject+1);
2415 }
2416 // Clear the insertion point to indicate we are in unreachable code.
2417 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002418}
2419
David Chisnalld7972f52011-03-23 16:36:54 +00002420llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002421 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002422 CGBuilderTy B = CGF.Builder;
2423 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2424 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002425}
2426
David Chisnalld7972f52011-03-23 16:36:54 +00002427void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002428 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002429 CGBuilderTy B = CGF.Builder;
2430 src = EnforceType(B, src, IdTy);
2431 dst = EnforceType(B, dst, PtrToIdTy);
2432 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002433}
2434
David Chisnalld7972f52011-03-23 16:36:54 +00002435void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002436 llvm::Value *src, llvm::Value *dst,
2437 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002438 CGBuilderTy B = CGF.Builder;
2439 src = EnforceType(B, src, IdTy);
2440 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002441 if (!threadlocal)
2442 B.CreateCall2(GlobalAssignFn, src, dst);
2443 else
2444 // FIXME. Add threadloca assign API
2445 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002446}
2447
David Chisnalld7972f52011-03-23 16:36:54 +00002448void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002449 llvm::Value *src, llvm::Value *dst,
2450 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002451 CGBuilderTy B = CGF.Builder;
2452 src = EnforceType(B, src, IdTy);
2453 dst = EnforceType(B, dst, PtrToIdTy);
2454 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002455}
2456
David Chisnalld7972f52011-03-23 16:36:54 +00002457void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002458 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002459 CGBuilderTy B = CGF.Builder;
2460 src = EnforceType(B, src, IdTy);
2461 dst = EnforceType(B, dst, PtrToIdTy);
2462 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002463}
2464
David Chisnalld7972f52011-03-23 16:36:54 +00002465void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002466 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002467 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002468 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002469 CGBuilderTy B = CGF.Builder;
2470 DestPtr = EnforceType(B, DestPtr, IdTy);
2471 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2472
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002473 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002474}
2475
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002476llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2477 const ObjCInterfaceDecl *ID,
2478 const ObjCIvarDecl *Ivar) {
2479 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2480 + '.' + Ivar->getNameAsString();
2481 // Emit the variable and initialize it with what we think the correct value
2482 // is. This allows code compiled with non-fragile ivars to work correctly
2483 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002484 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2485 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002486 // This will cause a run-time crash if we accidentally use it. A value of
2487 // 0 would seem more sensible, but will silently overwrite the isa pointer
2488 // causing a great deal of confusion.
2489 uint64_t Offset = -1;
2490 // We can't call ComputeIvarBaseOffset() here if we have the
2491 // implementation, because it will create an invalid ASTRecordLayout object
2492 // that we are then stuck with forever, so we only initialize the ivar
2493 // offset variable with a guess if we only have the interface. The
2494 // initializer will be reset later anyway, when we are generating the class
2495 // description.
2496 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002497 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002498 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2499
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002500 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002501 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002502 // Don't emit the guess in non-PIC code because the linker will not be able
2503 // to replace it with the real version for a library. In non-PIC code you
2504 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002505 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002506 if (CGM.getLangOptions().PICLevel) {
2507 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2508 llvm::Type::getInt32Ty(VMContext), false,
2509 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2510 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2511 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2512 IvarOffsetGV, Name);
2513 } else {
2514 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002515 llvm::Type::getInt32PtrTy(VMContext), false,
2516 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002517 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002518 }
David Chisnall5778fce2009-08-31 16:41:57 +00002519 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002520}
2521
David Chisnalld7972f52011-03-23 16:36:54 +00002522LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002523 QualType ObjectTy,
2524 llvm::Value *BaseValue,
2525 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002526 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002527 const ObjCInterfaceDecl *ID =
2528 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002529 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2530 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002531}
Mike Stumpdd93a192009-07-31 21:31:32 +00002532
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002533static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2534 const ObjCInterfaceDecl *OID,
2535 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002536 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002537 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002538 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2539 if (OIVD == Ivars[k])
2540 return OID;
2541 }
Mike Stump11289f42009-09-09 15:08:12 +00002542
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002543 // Otherwise check in the super class.
2544 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2545 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002546
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002547 return 0;
2548}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002549
David Chisnalld7972f52011-03-23 16:36:54 +00002550llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002551 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002552 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002553 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002554 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002555 return CGF.Builder.CreateZExtOrBitCast(
2556 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2557 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2558 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002559 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002560 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002561 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002562}
2563
David Chisnalld7972f52011-03-23 16:36:54 +00002564CGObjCRuntime *
2565clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2566 if (CGM.getLangOptions().ObjCNonFragileABI)
2567 return new CGObjCGNUstep(CGM);
2568 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002569}