blob: 4565fbfeb0efb67e1c0c7a33d6171a803ab3e88e [file] [log] [blame]
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnera0fd5ee2008-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 Korobeynikovcd5d08d2008-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 Lattnera0fd5ee2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner547907c2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbara04840b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
Chris Lattner547907c2008-06-26 04:19:03 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000021#include "clang/AST/Decl.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000022#include "clang/AST/DeclObjC.h"
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000023#include "llvm/Module.h"
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000024#include "llvm/ADT/SmallVector.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000025#include "llvm/ADT/StringMap.h"
Daniel Dunbarac93e472008-08-15 22:20:32 +000026#include "llvm/Support/Compiler.h"
27#include "llvm/Support/IRBuilder.h"
28#include "llvm/Target/TargetData.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include <map>
Chris Lattner547907c2008-06-26 04:19:03 +000030using namespace clang;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000031using llvm::dyn_cast;
32
33// The version of the runtime that this class targets. Must match the version
34// in the runtime.
35static const int RuntimeVersion = 8;
36static const int ProtocolVersion = 2;
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000037
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000038namespace {
Chris Lattner547907c2008-06-26 04:19:03 +000039class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000040private:
Chris Lattner547907c2008-06-26 04:19:03 +000041 CodeGen::CodeGenModule &CGM;
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000042 llvm::Module &TheModule;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000043 const llvm::StructType *SelStructTy;
Chris Lattnerb326b172008-03-30 23:03:07 +000044 const llvm::Type *SelectorTy;
45 const llvm::Type *PtrToInt8Ty;
46 const llvm::Type *IMPTy;
47 const llvm::Type *IdTy;
48 const llvm::Type *IntTy;
49 const llvm::Type *PtrTy;
50 const llvm::Type *LongTy;
51 const llvm::Type *PtrToIntTy;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000052 std::vector<llvm::Constant*> Classes;
53 std::vector<llvm::Constant*> Categories;
54 std::vector<llvm::Constant*> ConstantStrings;
55 llvm::Function *LoadFunction;
56 llvm::StringMap<llvm::Constant*> ExistingProtocols;
57 typedef std::pair<std::string, std::string> TypedSelector;
58 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
59 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
60 // Some zeros used for GEPs in lots of places.
61 llvm::Constant *Zeros[2];
62 llvm::Constant *NULLPtr;
63private:
64 llvm::Constant *GenerateIvarList(
65 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
66 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
67 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
68 llvm::Constant *GenerateMethodList(const std::string &ClassName,
69 const std::string &CategoryName,
Chris Lattner578279d2008-06-26 05:08:00 +000070 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000071 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
72 bool isClassMethodList);
73 llvm::Constant *GenerateProtocolList(
74 const llvm::SmallVectorImpl<std::string> &Protocols);
75 llvm::Constant *GenerateClassStructure(
76 llvm::Constant *MetaClass,
77 llvm::Constant *SuperClass,
78 unsigned info,
Chris Lattnerad9c3f32008-06-26 04:47:04 +000079 const char *Name,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000080 llvm::Constant *Version,
81 llvm::Constant *InstanceSize,
82 llvm::Constant *IVars,
83 llvm::Constant *Methods,
84 llvm::Constant *Protocols);
85 llvm::Constant *GenerateProtocolMethodList(
86 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
87 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
88 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
89 &Name="");
90 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
91 std::vector<llvm::Constant*> &V, const std::string &Name="");
92 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
93 std::vector<llvm::Constant*> &V, const std::string &Name="");
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000094public:
Chris Lattner547907c2008-06-26 04:19:03 +000095 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000096 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbara04840b2008-08-23 03:46:30 +000097 virtual CodeGen::RValue
98 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +000099 QualType ResultType,
100 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000101 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000102 bool IsClassMessage,
103 const CallArgList &CallArgs);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000104 virtual CodeGen::RValue
105 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000106 QualType ResultType,
107 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000108 const ObjCInterfaceDecl *Class,
109 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000110 bool IsClassMessage,
111 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000112 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
113 const ObjCInterfaceDecl *OID);
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000114 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
Chris Lattnerd71288e2008-06-26 04:37:12 +0000115
Daniel Dunbarac93e472008-08-15 22:20:32 +0000116 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
117 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
118 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000119 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000120 const ObjCProtocolDecl *PD);
121 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000122 virtual llvm::Function *ModuleInitFunction();
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000123};
124} // end anonymous namespace
125
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000126
127
128static std::string SymbolNameForClass(const std::string &ClassName) {
129 return ".objc_class_" + ClassName;
130}
131
132static std::string SymbolNameForMethod(const std::string &ClassName, const
133 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
134{
135 return "._objc_method_" + ClassName +"("+CategoryName+")"+
136 (isClassMethod ? "+" : "-") + MethodName;
137}
138
Chris Lattner547907c2008-06-26 04:19:03 +0000139CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
140 : CGM(cgm), TheModule(CGM.getModule()) {
141 IntTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
142 LongTy = CGM.getTypes().ConvertType(CGM.getContext().LongTy);
143
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000144 Zeros[0] = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
145 Zeros[1] = Zeros[0];
146 NULLPtr = llvm::ConstantPointerNull::get(
147 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattnerb326b172008-03-30 23:03:07 +0000148 // C string type. Used in lots of places.
149 PtrToInt8Ty =
150 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
151 // Get the selector Type.
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000152 SelStructTy = llvm::StructType::get(
Chris Lattnerb326b172008-03-30 23:03:07 +0000153 PtrToInt8Ty,
154 PtrToInt8Ty,
155 NULL);
156 SelectorTy = llvm::PointerType::getUnqual(SelStructTy);
157 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
158 PtrTy = PtrToInt8Ty;
159
160 // Object type
161 llvm::PATypeHolder OpaqueObjTy = llvm::OpaqueType::get();
162 llvm::Type *OpaqueIdTy = llvm::PointerType::getUnqual(OpaqueObjTy);
163 IdTy = llvm::StructType::get(OpaqueIdTy, NULL);
164 llvm::cast<llvm::OpaqueType>(OpaqueObjTy.get())->refineAbstractTypeTo(IdTy);
165 IdTy = llvm::cast<llvm::StructType>(OpaqueObjTy.get());
166 IdTy = llvm::PointerType::getUnqual(IdTy);
167
168 // IMP type
169 std::vector<const llvm::Type*> IMPArgs;
170 IMPArgs.push_back(IdTy);
171 IMPArgs.push_back(SelectorTy);
172 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000173}
174// This has to perform the lookup every time, since posing and related
175// techniques can modify the name -> class mapping.
Daniel Dunbar434627a2008-08-16 00:25:02 +0000176llvm::Value *CGObjCGNU::GetClass(llvm::IRBuilder<> &Builder,
177 const ObjCInterfaceDecl *OID) {
178 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getName());
179 ClassName = Builder.CreateStructGEP(ClassName, 0);
180
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000181 llvm::Constant *ClassLookupFn =
182 TheModule.getOrInsertFunction("objc_lookup_class", IdTy, PtrToInt8Ty,
183 NULL);
184 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattnerb326b172008-03-30 23:03:07 +0000185}
186
Chris Lattnerd71288e2008-06-26 04:37:12 +0000187/// GetSelector - Return the pointer to the unique'd string for this selector.
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000188llvm::Value *CGObjCGNU::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Chris Lattnerd71288e2008-06-26 04:37:12 +0000189 // FIXME: uniquing on the string is wasteful, unique on Sel instead!
190 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getName()];
191 if (US == 0)
192 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
193 llvm::GlobalValue::InternalLinkage,
194 ".objc_untyped_selector_alias",
195 NULL, &TheModule);
196
197 return Builder.CreateLoad(US);
198
199}
200
Chris Lattnera5b18882008-06-26 04:44:19 +0000201llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
202 const std::string &Name) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000203 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
204 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
205 llvm::GlobalValue::InternalLinkage,
206 ConstStr, Name, &TheModule);
207 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
208}
209llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
210 std::vector<llvm::Constant*> &V, const std::string &Name) {
211 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
212 return new llvm::GlobalVariable(Ty, false,
213 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
214}
215llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
216 std::vector<llvm::Constant*> &V, const std::string &Name) {
217 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
218 return new llvm::GlobalVariable(Ty, false,
219 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
220}
221
222/// Generate an NSConstantString object.
223//TODO: In case there are any crazy people still using the GNU runtime without
224//an OpenStep implementation, this should let them select their own class for
225//constant strings.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000226llvm::Constant *CGObjCGNU::GenerateConstantString(const std::string &Str) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000227 std::vector<llvm::Constant*> Ivars;
228 Ivars.push_back(NULLPtr);
Chris Lattnerbac12452008-06-21 21:44:18 +0000229 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000230 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000231 llvm::Constant *ObjCStr = MakeGlobal(
232 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
233 Ivars, ".objc_str");
234 ConstantStrings.push_back(
235 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
236 return ObjCStr;
237}
238
239///Generates a message send where the super is the receiver. This is a message
240///send to self with special delivery semantics indicating which class's method
241///should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000242CodeGen::RValue
243CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000244 QualType ResultType,
245 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000246 const ObjCInterfaceDecl *Class,
247 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000248 bool IsClassMessage,
249 const CallArgList &CallArgs) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000250 const ObjCInterfaceDecl *SuperClass = Class->getSuperClass();
Daniel Dunbardd851282008-08-30 05:35:15 +0000251 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(ResultType);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000252 // TODO: This should be cached, not looked up every time.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000253 llvm::Value *ReceiverClass = GetClass(CGF.Builder, SuperClass);
Daniel Dunbardd851282008-08-30 05:35:15 +0000254 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000255 std::vector<const llvm::Type*> impArgTypes;
256 impArgTypes.push_back(Receiver->getType());
Chris Lattnerb326b172008-03-30 23:03:07 +0000257 impArgTypes.push_back(SelectorTy);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000258
259 // Avoid an explicit cast on the IMP by getting a version that has the right
260 // return type.
261 llvm::FunctionType *impType = llvm::FunctionType::get(ReturnTy, impArgTypes,
262 true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000263 // Construct the structure used to look up the IMP
264 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
265 IdTy, NULL);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000266 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Eli Friedman2e630542008-06-13 23:01:12 +0000267 // FIXME: volatility
Daniel Dunbara04840b2008-08-23 03:46:30 +0000268 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
269 CGF.Builder.CreateStore(ReceiverClass, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000270
271 // Get the IMP
272 llvm::Constant *lookupFunction =
273 TheModule.getOrInsertFunction("objc_msg_lookup_super",
274 llvm::PointerType::getUnqual(impType),
275 llvm::PointerType::getUnqual(ObjCSuperTy),
276 SelectorTy, NULL);
277 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbara04840b2008-08-23 03:46:30 +0000278 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000279 lookupArgs+2);
280
281 // Call the method
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000282 CallArgList ActualArgs;
283 ActualArgs.push_back(std::make_pair(Receiver,
284 CGF.getContext().getObjCIdType()));
285 ActualArgs.push_back(std::make_pair(cmd,
286 CGF.getContext().getObjCSelType()));
287 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbardd851282008-08-30 05:35:15 +0000288 return CGF.EmitCall(imp, ResultType, ActualArgs);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000289}
290
291/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000292CodeGen::RValue
293CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000294 QualType ResultType,
295 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000296 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000297 bool IsClassMessage,
298 const CallArgList &CallArgs) {
Daniel Dunbardd851282008-08-30 05:35:15 +0000299 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(ResultType);
300 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000301
302 // Look up the method implementation.
303 std::vector<const llvm::Type*> impArgTypes;
304 const llvm::Type *RetTy;
305 //TODO: Revisit this when LLVM supports aggregate return types.
306 if (ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
307 RetTy = ReturnTy;
308 } else {
309 // For struct returns allocate the space in the caller and pass it up to
310 // the sender.
311 RetTy = llvm::Type::VoidTy;
312 impArgTypes.push_back(llvm::PointerType::getUnqual(ReturnTy));
313 }
314 impArgTypes.push_back(Receiver->getType());
315 impArgTypes.push_back(SelectorTy);
316
317 // Avoid an explicit cast on the IMP by getting a version that has the right
318 // return type.
319 llvm::FunctionType *impType = llvm::FunctionType::get(RetTy, impArgTypes,
320 true);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000321
322 llvm::Constant *lookupFunction =
323 TheModule.getOrInsertFunction("objc_msg_lookup",
Chris Lattnerb326b172008-03-30 23:03:07 +0000324 llvm::PointerType::getUnqual(impType),
325 Receiver->getType(), SelectorTy, NULL);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000326 llvm::Value *imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
Chris Lattner7db5e942008-05-06 00:56:42 +0000327
328 // Call the method.
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000329 CallArgList ActualArgs;
330 ActualArgs.push_back(std::make_pair(Receiver,
331 CGF.getContext().getObjCIdType()));
332 ActualArgs.push_back(std::make_pair(cmd,
333 CGF.getContext().getObjCSelType()));
334 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbardd851282008-08-30 05:35:15 +0000335 return CGF.EmitCall(imp, ResultType, ActualArgs);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000336}
337
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000338/// Generates a MethodList. Used in construction of a objc_class and
339/// objc_category structures.
340llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattner578279d2008-06-26 05:08:00 +0000341 const std::string &CategoryName,
342 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000343 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
344 bool isClassMethodList) {
345 // Get the method structure type.
346 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
347 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
348 PtrToInt8Ty, // Method types
349 llvm::PointerType::getUnqual(IMPTy), //Method pointer
350 NULL);
351 std::vector<llvm::Constant*> Methods;
352 std::vector<llvm::Constant*> Elements;
353 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
354 Elements.clear();
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000355 llvm::Constant *C = CGM.GetAddrOfConstantCString(MethodSels[i].getName());
Chris Lattner578279d2008-06-26 05:08:00 +0000356 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000357 Elements.push_back(
358 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
359 llvm::Constant *Method =
360 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner578279d2008-06-26 05:08:00 +0000361 MethodSels[i].getName(),
Chris Lattnere7581092008-06-26 04:05:20 +0000362 isClassMethodList));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000363 Method = llvm::ConstantExpr::getBitCast(Method,
364 llvm::PointerType::getUnqual(IMPTy));
365 Elements.push_back(Method);
366 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
367 }
368
369 // Array of method structures
370 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Chris Lattner578279d2008-06-26 05:08:00 +0000371 MethodSels.size());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000372 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000373 Methods);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000374
375 // Structure containing list pointer, array and array count
376 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
377 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
378 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
379 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
380 IntTy,
381 ObjCMethodArrayTy,
382 NULL);
383 // Refine next pointer type to concrete type
384 llvm::cast<llvm::OpaqueType>(
385 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
386 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
387
388 Methods.clear();
389 Methods.push_back(llvm::ConstantPointerNull::get(
390 llvm::PointerType::getUnqual(ObjCMethodListTy)));
391 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
392 MethodTypes.size()));
393 Methods.push_back(MethodArray);
394
395 // Create an instance of the structure
396 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
397}
398
399/// Generates an IvarList. Used in construction of a objc_class.
400llvm::Constant *CGObjCGNU::GenerateIvarList(
401 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
402 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
403 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
404 // Get the method structure type.
405 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
406 PtrToInt8Ty,
407 PtrToInt8Ty,
408 IntTy,
409 NULL);
410 std::vector<llvm::Constant*> Ivars;
411 std::vector<llvm::Constant*> Elements;
412 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
413 Elements.clear();
414 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
415 Zeros, 2));
416 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
417 Zeros, 2));
418 Elements.push_back(IvarOffsets[i]);
419 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
420 }
421
422 // Array of method structures
423 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
424 IvarNames.size());
425
426
427 Elements.clear();
428 Elements.push_back(llvm::ConstantInt::get(
429 llvm::cast<llvm::IntegerType>(IntTy), (int)IvarNames.size()));
430 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
431 // Structure containing array and array count
432 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
433 ObjCIvarArrayTy,
434 NULL);
435
436 // Create an instance of the structure
437 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
438}
439
440/// Generate a class structure
441llvm::Constant *CGObjCGNU::GenerateClassStructure(
442 llvm::Constant *MetaClass,
443 llvm::Constant *SuperClass,
444 unsigned info,
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000445 const char *Name,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000446 llvm::Constant *Version,
447 llvm::Constant *InstanceSize,
448 llvm::Constant *IVars,
449 llvm::Constant *Methods,
450 llvm::Constant *Protocols) {
451 // Set up the class structure
452 // Note: Several of these are char*s when they should be ids. This is
453 // because the runtime performs this translation on load.
454 llvm::StructType *ClassTy = llvm::StructType::get(
455 PtrToInt8Ty, // class_pointer
456 PtrToInt8Ty, // super_class
457 PtrToInt8Ty, // name
458 LongTy, // version
459 LongTy, // info
460 LongTy, // instance_size
461 IVars->getType(), // ivars
462 Methods->getType(), // methods
463 // These are all filled in by the runtime, so we pretend
464 PtrTy, // dtable
465 PtrTy, // subclass_list
466 PtrTy, // sibling_class
467 PtrTy, // protocols
468 PtrTy, // gc_object_type
469 NULL);
470 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
471 llvm::Constant *NullP =
472 llvm::ConstantPointerNull::get(llvm::cast<llvm::PointerType>(PtrTy));
473 // Fill in the structure
474 std::vector<llvm::Constant*> Elements;
475 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
476 Elements.push_back(SuperClass);
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000477 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000478 Elements.push_back(Zero);
479 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
480 Elements.push_back(InstanceSize);
481 Elements.push_back(IVars);
482 Elements.push_back(Methods);
483 Elements.push_back(NullP);
484 Elements.push_back(NullP);
485 Elements.push_back(NullP);
486 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
487 Elements.push_back(NullP);
488 // Create an instance of the structure
Chris Lattner4d018542008-07-21 06:31:05 +0000489 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000490}
491
492llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
493 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
494 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
495 // Get the method structure type.
496 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
497 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
498 PtrToInt8Ty,
499 NULL);
500 std::vector<llvm::Constant*> Methods;
501 std::vector<llvm::Constant*> Elements;
502 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
503 Elements.clear();
504 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
505 Zeros, 2));
506 Elements.push_back(
507 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
508 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
509 }
510 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
511 MethodNames.size());
512 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
513 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
514 IntTy, ObjCMethodArrayTy, NULL);
515 Methods.clear();
516 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
517 Methods.push_back(Array);
518 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
519}
520// Create the protocol list structure used in classes, categories and so on
521llvm::Constant *CGObjCGNU::GenerateProtocolList(
522 const llvm::SmallVectorImpl<std::string> &Protocols) {
523 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
524 Protocols.size());
525 llvm::StructType *ProtocolListTy = llvm::StructType::get(
526 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
527 LongTy,//FIXME: Should be size_t
528 ProtocolArrayTy,
529 NULL);
530 std::vector<llvm::Constant*> Elements;
531 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
532 iter != endIter ; iter++) {
533 llvm::Constant *Ptr =
534 llvm::ConstantExpr::getBitCast(ExistingProtocols[*iter], PtrToInt8Ty);
535 Elements.push_back(Ptr);
536 }
537 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
538 Elements);
539 Elements.clear();
540 Elements.push_back(NULLPtr);
541 Elements.push_back(llvm::ConstantInt::get(
542 llvm::cast<llvm::IntegerType>(LongTy), Protocols.size()));
543 Elements.push_back(ProtocolArray);
544 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
545}
546
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000547llvm::Value *CGObjCGNU::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
548 const ObjCProtocolDecl *PD) {
549 return ExistingProtocols[PD->getName()];
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000550}
551
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000552void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
553 ASTContext &Context = CGM.getContext();
554 const char *ProtocolName = PD->getName();
555 llvm::SmallVector<std::string, 16> Protocols;
556 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
557 E = PD->protocol_end(); PI != E; ++PI)
558 Protocols.push_back((*PI)->getName());
559 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
560 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
561 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
562 E = PD->instmeth_end(); iter != E; iter++) {
563 std::string TypeStr;
564 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
565 InstanceMethodNames.push_back(
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000566 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
567 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000568 }
569 // Collect information about class methods:
570 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
571 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
572 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
573 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
574 std::string TypeStr;
575 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
576 ClassMethodNames.push_back(
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000577 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
578 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000579 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000580
581 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
582 llvm::Constant *InstanceMethodList =
583 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
584 llvm::Constant *ClassMethodList =
585 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
586 // Protocols are objects containing lists of the methods implemented and
587 // protocols adopted.
588 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
589 PtrToInt8Ty,
590 ProtocolList->getType(),
591 InstanceMethodList->getType(),
592 ClassMethodList->getType(),
593 NULL);
594 std::vector<llvm::Constant*> Elements;
595 // The isa pointer must be set to a magic number so the runtime knows it's
596 // the correct layout.
597 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
598 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
599 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
600 Elements.push_back(ProtocolList);
601 Elements.push_back(InstanceMethodList);
602 Elements.push_back(ClassMethodList);
603 ExistingProtocols[ProtocolName] =
604 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
605 ".objc_protocol"), IdTy);
606}
607
Daniel Dunbarac93e472008-08-15 22:20:32 +0000608void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
609 const char *ClassName = OCD->getClassInterface()->getName();
610 const char *CategoryName = OCD->getName();
611 // Collect information about instance methods
612 llvm::SmallVector<Selector, 16> InstanceMethodSels;
613 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
614 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
615 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
616 InstanceMethodSels.push_back((*iter)->getSelector());
617 std::string TypeStr;
618 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
619 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
620 }
621
622 // Collect information about class methods
623 llvm::SmallVector<Selector, 16> ClassMethodSels;
624 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
625 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
626 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
627 ClassMethodSels.push_back((*iter)->getSelector());
628 std::string TypeStr;
629 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
630 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
631 }
632
633 // Collect the names of referenced protocols
634 llvm::SmallVector<std::string, 16> Protocols;
635 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
636 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
637 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
638 E = Protos.end(); I != E; ++I)
639 Protocols.push_back((*I)->getName());
640
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000641 std::vector<llvm::Constant*> Elements;
642 Elements.push_back(MakeConstantString(CategoryName));
643 Elements.push_back(MakeConstantString(ClassName));
644 // Instance method list
645 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattner578279d2008-06-26 05:08:00 +0000646 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000647 false), PtrTy));
648 // Class method list
649 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattner578279d2008-06-26 05:08:00 +0000650 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000651 PtrTy));
652 // Protocol list
653 Elements.push_back(llvm::ConstantExpr::getBitCast(
654 GenerateProtocolList(Protocols), PtrTy));
655 Categories.push_back(llvm::ConstantExpr::getBitCast(
656 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
657 PtrTy, PtrTy, NULL), Elements), PtrTy));
658}
Daniel Dunbarac93e472008-08-15 22:20:32 +0000659
660void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
661 ASTContext &Context = CGM.getContext();
662
663 // Get the superclass name.
664 const ObjCInterfaceDecl * SuperClassDecl =
665 OID->getClassInterface()->getSuperClass();
666 const char * SuperClassName = NULL;
667 if (SuperClassDecl) {
668 SuperClassName = SuperClassDecl->getName();
669 }
670
671 // Get the class name
672 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
673 const char * ClassName = ClassDecl->getName();
674
675 // Get the size of instances. For runtimes that support late-bound instances
676 // this should probably be something different (size just of instance
677 // varaibles in this class, not superclasses?).
678 int instanceSize = 0;
679 const llvm::Type *ObjTy = 0;
680 if (!LateBoundIVars()) {
681 ObjTy = CGM.getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
682 instanceSize = CGM.getTargetData().getABITypeSize(ObjTy);
683 } else {
684 // This is required by newer ObjC runtimes.
685 assert(0 && "Late-bound instance variables not yet supported");
686 }
687
688 // Collect information about instance variables.
689 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
690 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
691 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
692 const llvm::StructLayout *Layout =
693 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(ObjTy));
694 ObjTy = llvm::PointerType::getUnqual(ObjTy);
695 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
696 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
697 // Store the name
698 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)->getName()));
699 // Get the type encoding for this ivar
700 std::string TypeStr;
701 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
702 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
703 EncodingRecordTypes);
704 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
705 // Get the offset
706 int offset =
707 (int)Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(*iter));
708 IvarOffsets.push_back(
709 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
710 }
711
712 // Collect information about instance methods
713 llvm::SmallVector<Selector, 16> InstanceMethodSels;
714 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
715 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
716 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
717 InstanceMethodSels.push_back((*iter)->getSelector());
718 std::string TypeStr;
719 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
720 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
721 }
722
723 // Collect information about class methods
724 llvm::SmallVector<Selector, 16> ClassMethodSels;
725 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
726 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
727 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
728 ClassMethodSels.push_back((*iter)->getSelector());
729 std::string TypeStr;
730 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
731 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
732 }
733 // Collect the names of referenced protocols
734 llvm::SmallVector<std::string, 16> Protocols;
735 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
736 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
737 E = Protos.end(); I != E; ++I)
738 Protocols.push_back((*I)->getName());
739
740
741
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000742 // Get the superclass pointer.
743 llvm::Constant *SuperClass;
744 if (SuperClassName) {
745 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
746 } else {
747 SuperClass = llvm::ConstantPointerNull::get(
748 llvm::cast<llvm::PointerType>(PtrToInt8Ty));
749 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000750 // Empty vector used to construct empty method lists
751 llvm::SmallVector<llvm::Constant*, 1> empty;
752 // Generate the method and instance variable lists
753 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattner578279d2008-06-26 05:08:00 +0000754 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000755 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattner578279d2008-06-26 05:08:00 +0000756 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000757 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
758 IvarOffsets);
759 //Generate metaclass for class methods
760 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner4d018542008-07-21 06:31:05 +0000761 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000762 empty, empty, empty), ClassMethodList, NULLPtr);
763 // Generate the class structure
764 llvm::Constant *ClassStruct = GenerateClassStructure(MetaClassStruct,
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000765 SuperClass, 0x1L, ClassName, 0,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000766 llvm::ConstantInt::get(llvm::Type::Int32Ty, instanceSize), IvarList,
767 MethodList, GenerateProtocolList(Protocols));
768 // Add class structure to list to be added to the symtab later
769 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
770 Classes.push_back(ClassStruct);
771}
772
773llvm::Function *CGObjCGNU::ModuleInitFunction() {
774 // Only emit an ObjC load function if no Objective-C stuff has been called
775 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
776 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikovb41e4972008-06-01 15:14:46 +0000777 UntypedSelectors.empty())
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000778 return NULL;
Eli Friedman7719bc82008-06-01 16:00:02 +0000779
780 // Name the ObjC types to make the IR a bit easier to read
781 TheModule.addTypeName(".objc_selector", SelectorTy);
782 TheModule.addTypeName(".objc_id", IdTy);
783 TheModule.addTypeName(".objc_imp", IMPTy);
784
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000785 std::vector<llvm::Constant*> Elements;
786 // Generate statics list:
787 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
788 ConstantStrings.size() + 1);
789 ConstantStrings.push_back(NULLPtr);
790 Elements.push_back(MakeConstantString("NSConstantString",
791 ".objc_static_class_name"));
792 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, ConstantStrings));
793 llvm::StructType *StaticsListTy =
794 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Chris Lattneref843042008-06-26 04:10:42 +0000795 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000796 llvm::Constant *Statics =
797 MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Chris Lattner60eaae82008-06-24 17:01:28 +0000798 llvm::ArrayType *StaticsListArrayTy =
Chris Lattneref843042008-06-26 04:10:42 +0000799 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner60eaae82008-06-24 17:01:28 +0000800 Elements.clear();
801 Elements.push_back(Statics);
Chris Lattneref843042008-06-26 04:10:42 +0000802 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner60eaae82008-06-24 17:01:28 +0000803 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000804 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
805 // Array of classes, categories, and constant objects
806 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
807 Classes.size() + Categories.size() + 2);
Chris Lattneref843042008-06-26 04:10:42 +0000808 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelectorTy,
809 llvm::Type::Int16Ty,
810 llvm::Type::Int16Ty,
811 ClassListTy, NULL);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000812
813 Elements.clear();
814 // Pointer to an array of selectors used in this module.
815 std::vector<llvm::Constant*> Selectors;
816 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
817 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
818 iter != iterEnd ; ++iter) {
Chris Lattneref843042008-06-26 04:10:42 +0000819 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
820 Elements.push_back(MakeConstantString(iter->first.second,
821 ".objc_sel_types"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000822 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
823 Elements.clear();
824 }
825 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
826 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattneref843042008-06-26 04:10:42 +0000827 iter != iterEnd; ++iter) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000828 Elements.push_back(
Chris Lattneref843042008-06-26 04:10:42 +0000829 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000830 Elements.push_back(NULLPtr);
831 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
832 Elements.clear();
833 }
834 Elements.push_back(NULLPtr);
835 Elements.push_back(NULLPtr);
836 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
837 Elements.clear();
838 // Number of static selectors
839 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
840 llvm::Constant *SelectorList = MakeGlobal(
841 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
842 ".objc_selector_list");
843 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, SelectorTy));
844
845 // Now that all of the static selectors exist, create pointers to them.
846 int index = 0;
847 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
848 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
849 iter != iterEnd; ++iter) {
850 llvm::Constant *Idxs[] = {Zeros[0],
851 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
852 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
853 llvm::GlobalValue::InternalLinkage,
854 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
855 ".objc_sel_ptr", &TheModule);
856 (*iter).second->setAliasee(SelPtr);
857 }
858 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
859 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
860 iter != iterEnd; iter++) {
861 llvm::Constant *Idxs[] = {Zeros[0],
862 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
863 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
864 llvm::GlobalValue::InternalLinkage,
865 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
866 ".objc_sel_ptr", &TheModule);
867 (*iter).second->setAliasee(SelPtr);
868 }
869 // Number of classes defined.
870 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
871 Classes.size()));
872 // Number of categories defined
873 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
874 Categories.size()));
875 // Create an array of classes, then categories, then static object instances
876 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
877 // NULL-terminated list of static object instances (mainly constant strings)
878 Classes.push_back(Statics);
879 Classes.push_back(NULLPtr);
880 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
881 Elements.push_back(ClassList);
882 // Construct the symbol table
883 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
884
885 // The symbol table is contained in a module which has some version-checking
886 // constants
887 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
888 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
889 Elements.clear();
890 // Runtime version used for compatibility checking.
891 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
892 //FIXME: Should be sizeof(ModuleTy)
893 Elements.push_back(llvm::ConstantInt::get(LongTy, 16));
894 //FIXME: Should be the path to the file where this module was declared
895 Elements.push_back(NULLPtr);
896 Elements.push_back(SymTab);
897 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
898
899 // Create the load function calling the runtime entry point with the module
900 // structure
901 std::vector<const llvm::Type*> VoidArgs;
902 llvm::Function * LoadFunction = llvm::Function::Create(
903 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
904 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
905 &TheModule);
906 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000907 llvm::IRBuilder<> Builder;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000908 Builder.SetInsertPoint(EntryBB);
909 llvm::Value *Register = TheModule.getOrInsertFunction("__objc_exec_class",
910 llvm::Type::VoidTy, llvm::PointerType::getUnqual(ModuleTy), NULL);
911 Builder.CreateCall(Register, Module);
912 Builder.CreateRetVoid();
913 return LoadFunction;
914}
Daniel Dunbarac93e472008-08-15 22:20:32 +0000915
916llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD) {
917 const llvm::Type *ReturnTy =
918 CGM.getTypes().ConvertReturnType(OMD->getResultType());
919 const ObjCCategoryImplDecl *OCD =
920 dyn_cast<ObjCCategoryImplDecl>(OMD->getMethodContext());
921 const std::string &CategoryName = OCD ? OCD->getName() : "";
922 const llvm::Type *SelfTy = llvm::PointerType::getUnqual(llvm::Type::Int32Ty);
923 const std::string &ClassName = OMD->getClassInterface()->getName();
924 const std::string &MethodName = OMD->getSelector().getName();
925 unsigned ArgC = OMD->param_size();
926 bool isClassMethod = !OMD->isInstance();
927 bool isVarArg = OMD->isVariadic();
928
929 llvm::SmallVector<const llvm::Type *, 16> ArgTy;
930 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
931 const llvm::Type *Ty =
932 CGM.getTypes().ConvertType(OMD->getParamDecl(i)->getType());
933 if (Ty->isFirstClassType())
934 ArgTy.push_back(Ty);
935 else
936 ArgTy.push_back(llvm::PointerType::getUnqual(Ty));
937 }
938
Chris Lattnerb326b172008-03-30 23:03:07 +0000939 std::vector<const llvm::Type*> Args;
Chris Lattner6ee20e32008-06-24 17:04:18 +0000940 if (!ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000941 Args.push_back(llvm::PointerType::getUnqual(ReturnTy));
942 ReturnTy = llvm::Type::VoidTy;
943 }
Chris Lattnerb326b172008-03-30 23:03:07 +0000944 Args.push_back(SelfTy);
945 Args.push_back(SelectorTy);
Daniel Dunbarac93e472008-08-15 22:20:32 +0000946 Args.insert(Args.end(), ArgTy.begin(), ArgTy.begin()+ArgC);
Chris Lattnerb326b172008-03-30 23:03:07 +0000947
948 llvm::FunctionType *MethodTy = llvm::FunctionType::get(ReturnTy,
949 Args,
950 isVarArg);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000951 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
952 MethodName, isClassMethod);
953
Gabor Greif815e2c12008-04-06 20:42:52 +0000954 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattnerb326b172008-03-30 23:03:07 +0000955 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000956 FunctionName,
Chris Lattnerb326b172008-03-30 23:03:07 +0000957 &TheModule);
Chris Lattnerb326b172008-03-30 23:03:07 +0000958 return Method;
959}
960
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000961CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattner547907c2008-06-26 04:19:03 +0000962 return new CGObjCGNU(CGM);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000963}