blob: e5a5d053314082ccf7853e1791d9352e945d5983 [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000021#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner0f984262008-03-01 08:50:34 +000023#include "llvm/Module.h"
Chris Lattner0f984262008-03-01 08:50:34 +000024#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000025#include "llvm/ADT/StringMap.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000026#include "llvm/Support/Compiler.h"
27#include "llvm/Support/IRBuilder.h"
28#include "llvm/Target/TargetData.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include <map>
Chris Lattnerdce14062008-06-26 04:19:03 +000030using namespace clang;
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000037
Chris Lattner0f984262008-03-01 08:50:34 +000038namespace {
Chris Lattnerdce14062008-06-26 04:19:03 +000039class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattner0f984262008-03-01 08:50:34 +000040private:
Chris Lattnerdce14062008-06-26 04:19:03 +000041 CodeGen::CodeGenModule &CGM;
Chris Lattner0f984262008-03-01 08:50:34 +000042 llvm::Module &TheModule;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000043 const llvm::StructType *SelStructTy;
Chris Lattner391d77a2008-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 Korobeynikov20ff3102008-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 Lattnera4210072008-06-26 05:08:00 +000070 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-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 Lattnerd002cc62008-06-26 04:47:04 +000079 const char *Name,
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000094public:
Chris Lattnerdce14062008-06-26 04:19:03 +000095 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000096 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000097 virtual CodeGen::RValue
98 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
99 const ObjCMessageExpr *E,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000100 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000101 bool IsClassMessage,
102 const CallArgList &CallArgs);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000103 virtual CodeGen::RValue
104 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
105 const ObjCMessageExpr *E,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000106 const ObjCInterfaceDecl *Class,
107 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000108 bool IsClassMessage,
109 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000110 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
111 const ObjCInterfaceDecl *OID);
Chris Lattner85e35682008-08-08 19:57:58 +0000112 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000113
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000114 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
115 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
116 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Chris Lattner85e35682008-08-08 19:57:58 +0000117 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000118 const ObjCProtocolDecl *PD);
119 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000120 virtual llvm::Function *ModuleInitFunction();
Chris Lattner0f984262008-03-01 08:50:34 +0000121};
122} // end anonymous namespace
123
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000124
125
126static std::string SymbolNameForClass(const std::string &ClassName) {
127 return ".objc_class_" + ClassName;
128}
129
130static std::string SymbolNameForMethod(const std::string &ClassName, const
131 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
132{
133 return "._objc_method_" + ClassName +"("+CategoryName+")"+
134 (isClassMethod ? "+" : "-") + MethodName;
135}
136
Chris Lattnerdce14062008-06-26 04:19:03 +0000137CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
138 : CGM(cgm), TheModule(CGM.getModule()) {
139 IntTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
140 LongTy = CGM.getTypes().ConvertType(CGM.getContext().LongTy);
141
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000142 Zeros[0] = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
143 Zeros[1] = Zeros[0];
144 NULLPtr = llvm::ConstantPointerNull::get(
145 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattner391d77a2008-03-30 23:03:07 +0000146 // C string type. Used in lots of places.
147 PtrToInt8Ty =
148 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
149 // Get the selector Type.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000150 SelStructTy = llvm::StructType::get(
Chris Lattner391d77a2008-03-30 23:03:07 +0000151 PtrToInt8Ty,
152 PtrToInt8Ty,
153 NULL);
154 SelectorTy = llvm::PointerType::getUnqual(SelStructTy);
155 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
156 PtrTy = PtrToInt8Ty;
157
158 // Object type
159 llvm::PATypeHolder OpaqueObjTy = llvm::OpaqueType::get();
160 llvm::Type *OpaqueIdTy = llvm::PointerType::getUnqual(OpaqueObjTy);
161 IdTy = llvm::StructType::get(OpaqueIdTy, NULL);
162 llvm::cast<llvm::OpaqueType>(OpaqueObjTy.get())->refineAbstractTypeTo(IdTy);
163 IdTy = llvm::cast<llvm::StructType>(OpaqueObjTy.get());
164 IdTy = llvm::PointerType::getUnqual(IdTy);
165
166 // IMP type
167 std::vector<const llvm::Type*> IMPArgs;
168 IMPArgs.push_back(IdTy);
169 IMPArgs.push_back(SelectorTy);
170 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000171}
172// This has to perform the lookup every time, since posing and related
173// techniques can modify the name -> class mapping.
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000174llvm::Value *CGObjCGNU::GetClass(llvm::IRBuilder<> &Builder,
175 const ObjCInterfaceDecl *OID) {
176 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getName());
177 ClassName = Builder.CreateStructGEP(ClassName, 0);
178
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000179 llvm::Constant *ClassLookupFn =
180 TheModule.getOrInsertFunction("objc_lookup_class", IdTy, PtrToInt8Ty,
181 NULL);
182 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000183}
184
Chris Lattner8e67b632008-06-26 04:37:12 +0000185/// GetSelector - Return the pointer to the unique'd string for this selector.
Chris Lattner85e35682008-08-08 19:57:58 +0000186llvm::Value *CGObjCGNU::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Chris Lattner8e67b632008-06-26 04:37:12 +0000187 // FIXME: uniquing on the string is wasteful, unique on Sel instead!
188 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getName()];
189 if (US == 0)
190 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
191 llvm::GlobalValue::InternalLinkage,
192 ".objc_untyped_selector_alias",
193 NULL, &TheModule);
194
195 return Builder.CreateLoad(US);
196
197}
198
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000199llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
200 const std::string &Name) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000201 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
202 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
203 llvm::GlobalValue::InternalLinkage,
204 ConstStr, Name, &TheModule);
205 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
206}
207llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
208 std::vector<llvm::Constant*> &V, const std::string &Name) {
209 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
210 return new llvm::GlobalVariable(Ty, false,
211 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
212}
213llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
214 std::vector<llvm::Constant*> &V, const std::string &Name) {
215 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
216 return new llvm::GlobalVariable(Ty, false,
217 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
218}
219
220/// Generate an NSConstantString object.
221//TODO: In case there are any crazy people still using the GNU runtime without
222//an OpenStep implementation, this should let them select their own class for
223//constant strings.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000224llvm::Constant *CGObjCGNU::GenerateConstantString(const std::string &Str) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000225 std::vector<llvm::Constant*> Ivars;
226 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000227 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000228 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000229 llvm::Constant *ObjCStr = MakeGlobal(
230 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
231 Ivars, ".objc_str");
232 ConstantStrings.push_back(
233 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
234 return ObjCStr;
235}
236
237///Generates a message send where the super is the receiver. This is a message
238///send to self with special delivery semantics indicating which class's method
239///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000240CodeGen::RValue
241CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
242 const ObjCMessageExpr *E,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000243 const ObjCInterfaceDecl *Class,
244 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000245 bool IsClassMessage,
246 const CallArgList &CallArgs) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000247 const ObjCInterfaceDecl *SuperClass = Class->getSuperClass();
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000248 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(E->getType());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000249 // TODO: This should be cached, not looked up every time.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000250 llvm::Value *ReceiverClass = GetClass(CGF.Builder, SuperClass);
251 llvm::Value *cmd = GetSelector(CGF.Builder, E->getSelector());
Chris Lattner0f984262008-03-01 08:50:34 +0000252 std::vector<const llvm::Type*> impArgTypes;
253 impArgTypes.push_back(Receiver->getType());
Chris Lattner391d77a2008-03-30 23:03:07 +0000254 impArgTypes.push_back(SelectorTy);
Chris Lattner0f984262008-03-01 08:50:34 +0000255
256 // Avoid an explicit cast on the IMP by getting a version that has the right
257 // return type.
258 llvm::FunctionType *impType = llvm::FunctionType::get(ReturnTy, impArgTypes,
259 true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000260 // Construct the structure used to look up the IMP
261 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
262 IdTy, NULL);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000263 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Eli Friedman1e692ac2008-06-13 23:01:12 +0000264 // FIXME: volatility
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000265 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
266 CGF.Builder.CreateStore(ReceiverClass, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000267
268 // Get the IMP
269 llvm::Constant *lookupFunction =
270 TheModule.getOrInsertFunction("objc_msg_lookup_super",
271 llvm::PointerType::getUnqual(impType),
272 llvm::PointerType::getUnqual(ObjCSuperTy),
273 SelectorTy, NULL);
274 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000275 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000276 lookupArgs+2);
277
278 // Call the method
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000279 CallArgList ActualArgs;
280 ActualArgs.push_back(std::make_pair(Receiver,
281 CGF.getContext().getObjCIdType()));
282 ActualArgs.push_back(std::make_pair(cmd,
283 CGF.getContext().getObjCSelType()));
284 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
285 return CGF.EmitCall(imp, E->getType(), ActualArgs);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000286}
287
288/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000289CodeGen::RValue
290CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
291 const ObjCMessageExpr *E,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000292 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000293 bool IsClassMessage,
294 const CallArgList &CallArgs) {
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000295 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(E->getType());
296 llvm::Value *cmd = GetSelector(CGF.Builder, E->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000297
298 // Look up the method implementation.
299 std::vector<const llvm::Type*> impArgTypes;
300 const llvm::Type *RetTy;
301 //TODO: Revisit this when LLVM supports aggregate return types.
302 if (ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
303 RetTy = ReturnTy;
304 } else {
305 // For struct returns allocate the space in the caller and pass it up to
306 // the sender.
307 RetTy = llvm::Type::VoidTy;
308 impArgTypes.push_back(llvm::PointerType::getUnqual(ReturnTy));
309 }
310 impArgTypes.push_back(Receiver->getType());
311 impArgTypes.push_back(SelectorTy);
312
313 // Avoid an explicit cast on the IMP by getting a version that has the right
314 // return type.
315 llvm::FunctionType *impType = llvm::FunctionType::get(RetTy, impArgTypes,
316 true);
Chris Lattner0f984262008-03-01 08:50:34 +0000317
318 llvm::Constant *lookupFunction =
319 TheModule.getOrInsertFunction("objc_msg_lookup",
Chris Lattner391d77a2008-03-30 23:03:07 +0000320 llvm::PointerType::getUnqual(impType),
321 Receiver->getType(), SelectorTy, NULL);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000322 llvm::Value *imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
Chris Lattner3eae03e2008-05-06 00:56:42 +0000323
324 // Call the method.
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000325 CallArgList ActualArgs;
326 ActualArgs.push_back(std::make_pair(Receiver,
327 CGF.getContext().getObjCIdType()));
328 ActualArgs.push_back(std::make_pair(cmd,
329 CGF.getContext().getObjCSelType()));
330 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
331 return CGF.EmitCall(imp, E->getType(), ActualArgs);
Chris Lattner0f984262008-03-01 08:50:34 +0000332}
333
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000334/// Generates a MethodList. Used in construction of a objc_class and
335/// objc_category structures.
336llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattnera4210072008-06-26 05:08:00 +0000337 const std::string &CategoryName,
338 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000339 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
340 bool isClassMethodList) {
341 // Get the method structure type.
342 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
343 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
344 PtrToInt8Ty, // Method types
345 llvm::PointerType::getUnqual(IMPTy), //Method pointer
346 NULL);
347 std::vector<llvm::Constant*> Methods;
348 std::vector<llvm::Constant*> Elements;
349 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
350 Elements.clear();
Daniel Dunbar61432932008-08-13 23:20:05 +0000351 llvm::Constant *C = CGM.GetAddrOfConstantCString(MethodSels[i].getName());
Chris Lattnera4210072008-06-26 05:08:00 +0000352 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000353 Elements.push_back(
354 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
355 llvm::Constant *Method =
356 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnera4210072008-06-26 05:08:00 +0000357 MethodSels[i].getName(),
Chris Lattner550b8db2008-06-26 04:05:20 +0000358 isClassMethodList));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000359 Method = llvm::ConstantExpr::getBitCast(Method,
360 llvm::PointerType::getUnqual(IMPTy));
361 Elements.push_back(Method);
362 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
363 }
364
365 // Array of method structures
366 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Chris Lattnera4210072008-06-26 05:08:00 +0000367 MethodSels.size());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000368 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000369 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000370
371 // Structure containing list pointer, array and array count
372 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
373 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
374 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
375 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
376 IntTy,
377 ObjCMethodArrayTy,
378 NULL);
379 // Refine next pointer type to concrete type
380 llvm::cast<llvm::OpaqueType>(
381 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
382 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
383
384 Methods.clear();
385 Methods.push_back(llvm::ConstantPointerNull::get(
386 llvm::PointerType::getUnqual(ObjCMethodListTy)));
387 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
388 MethodTypes.size()));
389 Methods.push_back(MethodArray);
390
391 // Create an instance of the structure
392 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
393}
394
395/// Generates an IvarList. Used in construction of a objc_class.
396llvm::Constant *CGObjCGNU::GenerateIvarList(
397 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
398 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
399 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
400 // Get the method structure type.
401 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
402 PtrToInt8Ty,
403 PtrToInt8Ty,
404 IntTy,
405 NULL);
406 std::vector<llvm::Constant*> Ivars;
407 std::vector<llvm::Constant*> Elements;
408 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
409 Elements.clear();
410 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
411 Zeros, 2));
412 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
413 Zeros, 2));
414 Elements.push_back(IvarOffsets[i]);
415 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
416 }
417
418 // Array of method structures
419 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
420 IvarNames.size());
421
422
423 Elements.clear();
424 Elements.push_back(llvm::ConstantInt::get(
425 llvm::cast<llvm::IntegerType>(IntTy), (int)IvarNames.size()));
426 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
427 // Structure containing array and array count
428 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
429 ObjCIvarArrayTy,
430 NULL);
431
432 // Create an instance of the structure
433 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
434}
435
436/// Generate a class structure
437llvm::Constant *CGObjCGNU::GenerateClassStructure(
438 llvm::Constant *MetaClass,
439 llvm::Constant *SuperClass,
440 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000441 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000442 llvm::Constant *Version,
443 llvm::Constant *InstanceSize,
444 llvm::Constant *IVars,
445 llvm::Constant *Methods,
446 llvm::Constant *Protocols) {
447 // Set up the class structure
448 // Note: Several of these are char*s when they should be ids. This is
449 // because the runtime performs this translation on load.
450 llvm::StructType *ClassTy = llvm::StructType::get(
451 PtrToInt8Ty, // class_pointer
452 PtrToInt8Ty, // super_class
453 PtrToInt8Ty, // name
454 LongTy, // version
455 LongTy, // info
456 LongTy, // instance_size
457 IVars->getType(), // ivars
458 Methods->getType(), // methods
459 // These are all filled in by the runtime, so we pretend
460 PtrTy, // dtable
461 PtrTy, // subclass_list
462 PtrTy, // sibling_class
463 PtrTy, // protocols
464 PtrTy, // gc_object_type
465 NULL);
466 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
467 llvm::Constant *NullP =
468 llvm::ConstantPointerNull::get(llvm::cast<llvm::PointerType>(PtrTy));
469 // Fill in the structure
470 std::vector<llvm::Constant*> Elements;
471 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
472 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000473 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000474 Elements.push_back(Zero);
475 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
476 Elements.push_back(InstanceSize);
477 Elements.push_back(IVars);
478 Elements.push_back(Methods);
479 Elements.push_back(NullP);
480 Elements.push_back(NullP);
481 Elements.push_back(NullP);
482 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
483 Elements.push_back(NullP);
484 // Create an instance of the structure
Chris Lattner1565e032008-07-21 06:31:05 +0000485 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000486}
487
488llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
489 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
490 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
491 // Get the method structure type.
492 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
493 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
494 PtrToInt8Ty,
495 NULL);
496 std::vector<llvm::Constant*> Methods;
497 std::vector<llvm::Constant*> Elements;
498 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
499 Elements.clear();
500 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
501 Zeros, 2));
502 Elements.push_back(
503 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
504 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
505 }
506 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
507 MethodNames.size());
508 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
509 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
510 IntTy, ObjCMethodArrayTy, NULL);
511 Methods.clear();
512 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
513 Methods.push_back(Array);
514 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
515}
516// Create the protocol list structure used in classes, categories and so on
517llvm::Constant *CGObjCGNU::GenerateProtocolList(
518 const llvm::SmallVectorImpl<std::string> &Protocols) {
519 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
520 Protocols.size());
521 llvm::StructType *ProtocolListTy = llvm::StructType::get(
522 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
523 LongTy,//FIXME: Should be size_t
524 ProtocolArrayTy,
525 NULL);
526 std::vector<llvm::Constant*> Elements;
527 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
528 iter != endIter ; iter++) {
529 llvm::Constant *Ptr =
530 llvm::ConstantExpr::getBitCast(ExistingProtocols[*iter], PtrToInt8Ty);
531 Elements.push_back(Ptr);
532 }
533 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
534 Elements);
535 Elements.clear();
536 Elements.push_back(NULLPtr);
537 Elements.push_back(llvm::ConstantInt::get(
538 llvm::cast<llvm::IntegerType>(LongTy), Protocols.size()));
539 Elements.push_back(ProtocolArray);
540 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
541}
542
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000543llvm::Value *CGObjCGNU::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
544 const ObjCProtocolDecl *PD) {
545 return ExistingProtocols[PD->getName()];
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000546}
547
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000548void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
549 ASTContext &Context = CGM.getContext();
550 const char *ProtocolName = PD->getName();
551 llvm::SmallVector<std::string, 16> Protocols;
552 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
553 E = PD->protocol_end(); PI != E; ++PI)
554 Protocols.push_back((*PI)->getName());
555 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
556 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
557 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
558 E = PD->instmeth_end(); iter != E; iter++) {
559 std::string TypeStr;
560 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
561 InstanceMethodNames.push_back(
Daniel Dunbar61432932008-08-13 23:20:05 +0000562 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
563 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000564 }
565 // Collect information about class methods:
566 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
567 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
568 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
569 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
570 std::string TypeStr;
571 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
572 ClassMethodNames.push_back(
Daniel Dunbar61432932008-08-13 23:20:05 +0000573 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
574 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000575 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000576
577 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
578 llvm::Constant *InstanceMethodList =
579 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
580 llvm::Constant *ClassMethodList =
581 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
582 // Protocols are objects containing lists of the methods implemented and
583 // protocols adopted.
584 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
585 PtrToInt8Ty,
586 ProtocolList->getType(),
587 InstanceMethodList->getType(),
588 ClassMethodList->getType(),
589 NULL);
590 std::vector<llvm::Constant*> Elements;
591 // The isa pointer must be set to a magic number so the runtime knows it's
592 // the correct layout.
593 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
594 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
595 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
596 Elements.push_back(ProtocolList);
597 Elements.push_back(InstanceMethodList);
598 Elements.push_back(ClassMethodList);
599 ExistingProtocols[ProtocolName] =
600 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
601 ".objc_protocol"), IdTy);
602}
603
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000604void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
605 const char *ClassName = OCD->getClassInterface()->getName();
606 const char *CategoryName = OCD->getName();
607 // Collect information about instance methods
608 llvm::SmallVector<Selector, 16> InstanceMethodSels;
609 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
610 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
611 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
612 InstanceMethodSels.push_back((*iter)->getSelector());
613 std::string TypeStr;
614 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
615 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
616 }
617
618 // Collect information about class methods
619 llvm::SmallVector<Selector, 16> ClassMethodSels;
620 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
621 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
622 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
623 ClassMethodSels.push_back((*iter)->getSelector());
624 std::string TypeStr;
625 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
626 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
627 }
628
629 // Collect the names of referenced protocols
630 llvm::SmallVector<std::string, 16> Protocols;
631 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
632 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
633 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
634 E = Protos.end(); I != E; ++I)
635 Protocols.push_back((*I)->getName());
636
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000637 std::vector<llvm::Constant*> Elements;
638 Elements.push_back(MakeConstantString(CategoryName));
639 Elements.push_back(MakeConstantString(ClassName));
640 // Instance method list
641 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000642 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000643 false), PtrTy));
644 // Class method list
645 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000646 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000647 PtrTy));
648 // Protocol list
649 Elements.push_back(llvm::ConstantExpr::getBitCast(
650 GenerateProtocolList(Protocols), PtrTy));
651 Categories.push_back(llvm::ConstantExpr::getBitCast(
652 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
653 PtrTy, PtrTy, NULL), Elements), PtrTy));
654}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000655
656void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
657 ASTContext &Context = CGM.getContext();
658
659 // Get the superclass name.
660 const ObjCInterfaceDecl * SuperClassDecl =
661 OID->getClassInterface()->getSuperClass();
662 const char * SuperClassName = NULL;
663 if (SuperClassDecl) {
664 SuperClassName = SuperClassDecl->getName();
665 }
666
667 // Get the class name
668 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
669 const char * ClassName = ClassDecl->getName();
670
671 // Get the size of instances. For runtimes that support late-bound instances
672 // this should probably be something different (size just of instance
673 // varaibles in this class, not superclasses?).
674 int instanceSize = 0;
675 const llvm::Type *ObjTy = 0;
676 if (!LateBoundIVars()) {
677 ObjTy = CGM.getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
678 instanceSize = CGM.getTargetData().getABITypeSize(ObjTy);
679 } else {
680 // This is required by newer ObjC runtimes.
681 assert(0 && "Late-bound instance variables not yet supported");
682 }
683
684 // Collect information about instance variables.
685 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
686 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
687 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
688 const llvm::StructLayout *Layout =
689 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(ObjTy));
690 ObjTy = llvm::PointerType::getUnqual(ObjTy);
691 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
692 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
693 // Store the name
694 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)->getName()));
695 // Get the type encoding for this ivar
696 std::string TypeStr;
697 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
698 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
699 EncodingRecordTypes);
700 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
701 // Get the offset
702 int offset =
703 (int)Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(*iter));
704 IvarOffsets.push_back(
705 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
706 }
707
708 // Collect information about instance methods
709 llvm::SmallVector<Selector, 16> InstanceMethodSels;
710 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
711 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
712 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
713 InstanceMethodSels.push_back((*iter)->getSelector());
714 std::string TypeStr;
715 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
716 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
717 }
718
719 // Collect information about class methods
720 llvm::SmallVector<Selector, 16> ClassMethodSels;
721 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
722 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
723 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
724 ClassMethodSels.push_back((*iter)->getSelector());
725 std::string TypeStr;
726 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
727 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
728 }
729 // Collect the names of referenced protocols
730 llvm::SmallVector<std::string, 16> Protocols;
731 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
732 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
733 E = Protos.end(); I != E; ++I)
734 Protocols.push_back((*I)->getName());
735
736
737
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000738 // Get the superclass pointer.
739 llvm::Constant *SuperClass;
740 if (SuperClassName) {
741 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
742 } else {
743 SuperClass = llvm::ConstantPointerNull::get(
744 llvm::cast<llvm::PointerType>(PtrToInt8Ty));
745 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000746 // Empty vector used to construct empty method lists
747 llvm::SmallVector<llvm::Constant*, 1> empty;
748 // Generate the method and instance variable lists
749 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000750 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000751 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000752 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000753 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
754 IvarOffsets);
755 //Generate metaclass for class methods
756 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner1565e032008-07-21 06:31:05 +0000757 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000758 empty, empty, empty), ClassMethodList, NULLPtr);
759 // Generate the class structure
760 llvm::Constant *ClassStruct = GenerateClassStructure(MetaClassStruct,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000761 SuperClass, 0x1L, ClassName, 0,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000762 llvm::ConstantInt::get(llvm::Type::Int32Ty, instanceSize), IvarList,
763 MethodList, GenerateProtocolList(Protocols));
764 // Add class structure to list to be added to the symtab later
765 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
766 Classes.push_back(ClassStruct);
767}
768
769llvm::Function *CGObjCGNU::ModuleInitFunction() {
770 // Only emit an ObjC load function if no Objective-C stuff has been called
771 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
772 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +0000773 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000774 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +0000775
776 // Name the ObjC types to make the IR a bit easier to read
777 TheModule.addTypeName(".objc_selector", SelectorTy);
778 TheModule.addTypeName(".objc_id", IdTy);
779 TheModule.addTypeName(".objc_imp", IMPTy);
780
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000781 std::vector<llvm::Constant*> Elements;
782 // Generate statics list:
783 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
784 ConstantStrings.size() + 1);
785 ConstantStrings.push_back(NULLPtr);
786 Elements.push_back(MakeConstantString("NSConstantString",
787 ".objc_static_class_name"));
788 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, ConstantStrings));
789 llvm::StructType *StaticsListTy =
790 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Chris Lattner630404b2008-06-26 04:10:42 +0000791 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000792 llvm::Constant *Statics =
793 MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Chris Lattner4e0b2642008-06-24 17:01:28 +0000794 llvm::ArrayType *StaticsListArrayTy =
Chris Lattner630404b2008-06-26 04:10:42 +0000795 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner4e0b2642008-06-24 17:01:28 +0000796 Elements.clear();
797 Elements.push_back(Statics);
Chris Lattner630404b2008-06-26 04:10:42 +0000798 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner4e0b2642008-06-24 17:01:28 +0000799 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000800 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
801 // Array of classes, categories, and constant objects
802 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
803 Classes.size() + Categories.size() + 2);
Chris Lattner630404b2008-06-26 04:10:42 +0000804 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelectorTy,
805 llvm::Type::Int16Ty,
806 llvm::Type::Int16Ty,
807 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000808
809 Elements.clear();
810 // Pointer to an array of selectors used in this module.
811 std::vector<llvm::Constant*> Selectors;
812 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
813 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
814 iter != iterEnd ; ++iter) {
Chris Lattner630404b2008-06-26 04:10:42 +0000815 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
816 Elements.push_back(MakeConstantString(iter->first.second,
817 ".objc_sel_types"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000818 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
819 Elements.clear();
820 }
821 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
822 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +0000823 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000824 Elements.push_back(
Chris Lattner630404b2008-06-26 04:10:42 +0000825 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000826 Elements.push_back(NULLPtr);
827 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
828 Elements.clear();
829 }
830 Elements.push_back(NULLPtr);
831 Elements.push_back(NULLPtr);
832 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
833 Elements.clear();
834 // Number of static selectors
835 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
836 llvm::Constant *SelectorList = MakeGlobal(
837 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
838 ".objc_selector_list");
839 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, SelectorTy));
840
841 // Now that all of the static selectors exist, create pointers to them.
842 int index = 0;
843 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
844 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
845 iter != iterEnd; ++iter) {
846 llvm::Constant *Idxs[] = {Zeros[0],
847 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
848 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
849 llvm::GlobalValue::InternalLinkage,
850 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
851 ".objc_sel_ptr", &TheModule);
852 (*iter).second->setAliasee(SelPtr);
853 }
854 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
855 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
856 iter != iterEnd; iter++) {
857 llvm::Constant *Idxs[] = {Zeros[0],
858 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
859 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
860 llvm::GlobalValue::InternalLinkage,
861 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
862 ".objc_sel_ptr", &TheModule);
863 (*iter).second->setAliasee(SelPtr);
864 }
865 // Number of classes defined.
866 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
867 Classes.size()));
868 // Number of categories defined
869 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
870 Categories.size()));
871 // Create an array of classes, then categories, then static object instances
872 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
873 // NULL-terminated list of static object instances (mainly constant strings)
874 Classes.push_back(Statics);
875 Classes.push_back(NULLPtr);
876 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
877 Elements.push_back(ClassList);
878 // Construct the symbol table
879 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
880
881 // The symbol table is contained in a module which has some version-checking
882 // constants
883 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
884 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
885 Elements.clear();
886 // Runtime version used for compatibility checking.
887 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
888 //FIXME: Should be sizeof(ModuleTy)
889 Elements.push_back(llvm::ConstantInt::get(LongTy, 16));
890 //FIXME: Should be the path to the file where this module was declared
891 Elements.push_back(NULLPtr);
892 Elements.push_back(SymTab);
893 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
894
895 // Create the load function calling the runtime entry point with the module
896 // structure
897 std::vector<const llvm::Type*> VoidArgs;
898 llvm::Function * LoadFunction = llvm::Function::Create(
899 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
900 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
901 &TheModule);
902 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Chris Lattner85e35682008-08-08 19:57:58 +0000903 llvm::IRBuilder<> Builder;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000904 Builder.SetInsertPoint(EntryBB);
905 llvm::Value *Register = TheModule.getOrInsertFunction("__objc_exec_class",
906 llvm::Type::VoidTy, llvm::PointerType::getUnqual(ModuleTy), NULL);
907 Builder.CreateCall(Register, Module);
908 Builder.CreateRetVoid();
909 return LoadFunction;
910}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000911
912llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD) {
913 const llvm::Type *ReturnTy =
914 CGM.getTypes().ConvertReturnType(OMD->getResultType());
915 const ObjCCategoryImplDecl *OCD =
916 dyn_cast<ObjCCategoryImplDecl>(OMD->getMethodContext());
917 const std::string &CategoryName = OCD ? OCD->getName() : "";
918 const llvm::Type *SelfTy = llvm::PointerType::getUnqual(llvm::Type::Int32Ty);
919 const std::string &ClassName = OMD->getClassInterface()->getName();
920 const std::string &MethodName = OMD->getSelector().getName();
921 unsigned ArgC = OMD->param_size();
922 bool isClassMethod = !OMD->isInstance();
923 bool isVarArg = OMD->isVariadic();
924
925 llvm::SmallVector<const llvm::Type *, 16> ArgTy;
926 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
927 const llvm::Type *Ty =
928 CGM.getTypes().ConvertType(OMD->getParamDecl(i)->getType());
929 if (Ty->isFirstClassType())
930 ArgTy.push_back(Ty);
931 else
932 ArgTy.push_back(llvm::PointerType::getUnqual(Ty));
933 }
934
Chris Lattner391d77a2008-03-30 23:03:07 +0000935 std::vector<const llvm::Type*> Args;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000936 if (!ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000937 Args.push_back(llvm::PointerType::getUnqual(ReturnTy));
938 ReturnTy = llvm::Type::VoidTy;
939 }
Chris Lattner391d77a2008-03-30 23:03:07 +0000940 Args.push_back(SelfTy);
941 Args.push_back(SelectorTy);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000942 Args.insert(Args.end(), ArgTy.begin(), ArgTy.begin()+ArgC);
Chris Lattner391d77a2008-03-30 23:03:07 +0000943
944 llvm::FunctionType *MethodTy = llvm::FunctionType::get(ReturnTy,
945 Args,
946 isVarArg);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000947 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
948 MethodName, isClassMethod);
949
Gabor Greif984d0b42008-04-06 20:42:52 +0000950 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattner391d77a2008-03-30 23:03:07 +0000951 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000952 FunctionName,
Chris Lattner391d77a2008-03-30 23:03:07 +0000953 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +0000954 return Method;
955}
956
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000957CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattnerdce14062008-06-26 04:19:03 +0000958 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +0000959}