blob: 4c678c9f8fb3923e6029064cf4bff20b9932fe48 [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"
19#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner0f984262008-03-01 08:50:34 +000022#include "llvm/Module.h"
Chris Lattner0f984262008-03-01 08:50:34 +000023#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000024#include "llvm/ADT/StringMap.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000025#include "llvm/Support/Compiler.h"
26#include "llvm/Support/IRBuilder.h"
27#include "llvm/Target/TargetData.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000028#include <map>
Chris Lattnerdce14062008-06-26 04:19:03 +000029using namespace clang;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000030using llvm::dyn_cast;
31
32// The version of the runtime that this class targets. Must match the version
33// in the runtime.
34static const int RuntimeVersion = 8;
35static const int ProtocolVersion = 2;
Chris Lattner0f984262008-03-01 08:50:34 +000036
Chris Lattner0f984262008-03-01 08:50:34 +000037namespace {
Chris Lattnerdce14062008-06-26 04:19:03 +000038class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattner0f984262008-03-01 08:50:34 +000039private:
Chris Lattnerdce14062008-06-26 04:19:03 +000040 CodeGen::CodeGenModule &CGM;
Chris Lattner0f984262008-03-01 08:50:34 +000041 llvm::Module &TheModule;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000042 const llvm::StructType *SelStructTy;
Chris Lattner391d77a2008-03-30 23:03:07 +000043 const llvm::Type *SelectorTy;
44 const llvm::Type *PtrToInt8Ty;
45 const llvm::Type *IMPTy;
46 const llvm::Type *IdTy;
47 const llvm::Type *IntTy;
48 const llvm::Type *PtrTy;
49 const llvm::Type *LongTy;
50 const llvm::Type *PtrToIntTy;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000051 std::vector<llvm::Constant*> Classes;
52 std::vector<llvm::Constant*> Categories;
53 std::vector<llvm::Constant*> ConstantStrings;
54 llvm::Function *LoadFunction;
55 llvm::StringMap<llvm::Constant*> ExistingProtocols;
56 typedef std::pair<std::string, std::string> TypedSelector;
57 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
58 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
59 // Some zeros used for GEPs in lots of places.
60 llvm::Constant *Zeros[2];
61 llvm::Constant *NULLPtr;
62private:
63 llvm::Constant *GenerateIvarList(
64 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
65 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
66 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
67 llvm::Constant *GenerateMethodList(const std::string &ClassName,
68 const std::string &CategoryName,
Chris Lattnera4210072008-06-26 05:08:00 +000069 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000070 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
71 bool isClassMethodList);
72 llvm::Constant *GenerateProtocolList(
73 const llvm::SmallVectorImpl<std::string> &Protocols);
74 llvm::Constant *GenerateClassStructure(
75 llvm::Constant *MetaClass,
76 llvm::Constant *SuperClass,
77 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +000078 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000079 llvm::Constant *Version,
80 llvm::Constant *InstanceSize,
81 llvm::Constant *IVars,
82 llvm::Constant *Methods,
83 llvm::Constant *Protocols);
84 llvm::Constant *GenerateProtocolMethodList(
85 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
86 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
87 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
88 &Name="");
89 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
90 std::vector<llvm::Constant*> &V, const std::string &Name="");
91 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
92 std::vector<llvm::Constant*> &V, const std::string &Name="");
Chris Lattner0f984262008-03-01 08:50:34 +000093public:
Chris Lattnerdce14062008-06-26 04:19:03 +000094 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000095 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Chris Lattner85e35682008-08-08 19:57:58 +000096 virtual llvm::Value *GenerateMessageSend(llvm::IRBuilder<> &Builder,
Chris Lattner0f984262008-03-01 08:50:34 +000097 const llvm::Type *ReturnTy,
98 llvm::Value *Receiver,
Chris Lattner9384c762008-06-26 04:42:20 +000099 Selector Sel,
Chris Lattner0f984262008-03-01 08:50:34 +0000100 llvm::Value** ArgV,
101 unsigned ArgC);
Chris Lattner85e35682008-08-08 19:57:58 +0000102 virtual llvm::Value *GenerateMessageSendSuper(llvm::IRBuilder<> &Builder,
Chris Lattner8e67b632008-06-26 04:37:12 +0000103 const llvm::Type *ReturnTy,
Chris Lattner8e67b632008-06-26 04:37:12 +0000104 const char *SuperClassName,
105 llvm::Value *Receiver,
106 Selector Sel,
107 llvm::Value** ArgV,
108 unsigned ArgC);
Chris Lattner85e35682008-08-08 19:57:58 +0000109 virtual llvm::Value *LookupClass(llvm::IRBuilder<> &Builder,
Chris Lattner9384c762008-06-26 04:42:20 +0000110 llvm::Value *ClassName);
Chris Lattner85e35682008-08-08 19:57:58 +0000111 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000112
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000113 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
114 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
115 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Chris Lattner85e35682008-08-08 19:57:58 +0000116 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000117 const ObjCProtocolDecl *PD);
118 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000119 virtual llvm::Function *ModuleInitFunction();
Chris Lattner0f984262008-03-01 08:50:34 +0000120};
121} // end anonymous namespace
122
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000123
124
125static std::string SymbolNameForClass(const std::string &ClassName) {
126 return ".objc_class_" + ClassName;
127}
128
129static std::string SymbolNameForMethod(const std::string &ClassName, const
130 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
131{
132 return "._objc_method_" + ClassName +"("+CategoryName+")"+
133 (isClassMethod ? "+" : "-") + MethodName;
134}
135
Chris Lattnerdce14062008-06-26 04:19:03 +0000136CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
137 : CGM(cgm), TheModule(CGM.getModule()) {
138 IntTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
139 LongTy = CGM.getTypes().ConvertType(CGM.getContext().LongTy);
140
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000141 Zeros[0] = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
142 Zeros[1] = Zeros[0];
143 NULLPtr = llvm::ConstantPointerNull::get(
144 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattner391d77a2008-03-30 23:03:07 +0000145 // C string type. Used in lots of places.
146 PtrToInt8Ty =
147 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
148 // Get the selector Type.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000149 SelStructTy = llvm::StructType::get(
Chris Lattner391d77a2008-03-30 23:03:07 +0000150 PtrToInt8Ty,
151 PtrToInt8Ty,
152 NULL);
153 SelectorTy = llvm::PointerType::getUnqual(SelStructTy);
154 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
155 PtrTy = PtrToInt8Ty;
156
157 // Object type
158 llvm::PATypeHolder OpaqueObjTy = llvm::OpaqueType::get();
159 llvm::Type *OpaqueIdTy = llvm::PointerType::getUnqual(OpaqueObjTy);
160 IdTy = llvm::StructType::get(OpaqueIdTy, NULL);
161 llvm::cast<llvm::OpaqueType>(OpaqueObjTy.get())->refineAbstractTypeTo(IdTy);
162 IdTy = llvm::cast<llvm::StructType>(OpaqueObjTy.get());
163 IdTy = llvm::PointerType::getUnqual(IdTy);
164
165 // IMP type
166 std::vector<const llvm::Type*> IMPArgs;
167 IMPArgs.push_back(IdTy);
168 IMPArgs.push_back(SelectorTy);
169 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000170}
171// This has to perform the lookup every time, since posing and related
172// techniques can modify the name -> class mapping.
Chris Lattner85e35682008-08-08 19:57:58 +0000173llvm::Value *CGObjCGNU::LookupClass(llvm::IRBuilder<> &Builder,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000174 llvm::Value *ClassName) {
175 llvm::Constant *ClassLookupFn =
176 TheModule.getOrInsertFunction("objc_lookup_class", IdTy, PtrToInt8Ty,
177 NULL);
178 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000179}
180
Chris Lattner8e67b632008-06-26 04:37:12 +0000181/// GetSelector - Return the pointer to the unique'd string for this selector.
Chris Lattner85e35682008-08-08 19:57:58 +0000182llvm::Value *CGObjCGNU::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Chris Lattner8e67b632008-06-26 04:37:12 +0000183 // FIXME: uniquing on the string is wasteful, unique on Sel instead!
184 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getName()];
185 if (US == 0)
186 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
187 llvm::GlobalValue::InternalLinkage,
188 ".objc_untyped_selector_alias",
189 NULL, &TheModule);
190
191 return Builder.CreateLoad(US);
192
193}
194
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000195llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
196 const std::string &Name) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000197 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
198 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
199 llvm::GlobalValue::InternalLinkage,
200 ConstStr, Name, &TheModule);
201 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
202}
203llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
204 std::vector<llvm::Constant*> &V, const std::string &Name) {
205 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
206 return new llvm::GlobalVariable(Ty, false,
207 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
208}
209llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
210 std::vector<llvm::Constant*> &V, const std::string &Name) {
211 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
212 return new llvm::GlobalVariable(Ty, false,
213 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
214}
215
216/// Generate an NSConstantString object.
217//TODO: In case there are any crazy people still using the GNU runtime without
218//an OpenStep implementation, this should let them select their own class for
219//constant strings.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000220llvm::Constant *CGObjCGNU::GenerateConstantString(const std::string &Str) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000221 std::vector<llvm::Constant*> Ivars;
222 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000223 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000224 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000225 llvm::Constant *ObjCStr = MakeGlobal(
226 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
227 Ivars, ".objc_str");
228 ConstantStrings.push_back(
229 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
230 return ObjCStr;
231}
232
233///Generates a message send where the super is the receiver. This is a message
234///send to self with special delivery semantics indicating which class's method
235///should be called.
Chris Lattner85e35682008-08-08 19:57:58 +0000236llvm::Value *CGObjCGNU::GenerateMessageSendSuper(llvm::IRBuilder<> &Builder,
Chris Lattner8e67b632008-06-26 04:37:12 +0000237 const llvm::Type *ReturnTy,
Chris Lattner8e67b632008-06-26 04:37:12 +0000238 const char *SuperClassName,
239 llvm::Value *Receiver,
240 Selector Sel,
241 llvm::Value** ArgV,
242 unsigned ArgC) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000243 // TODO: This should be cached, not looked up every time.
244 llvm::Value *ReceiverClass = LookupClass(Builder,
245 MakeConstantString(SuperClassName));
Chris Lattner8e67b632008-06-26 04:37:12 +0000246 llvm::Value *cmd = GetSelector(Builder, Sel);
Chris Lattner0f984262008-03-01 08:50:34 +0000247 std::vector<const llvm::Type*> impArgTypes;
248 impArgTypes.push_back(Receiver->getType());
Chris Lattner391d77a2008-03-30 23:03:07 +0000249 impArgTypes.push_back(SelectorTy);
Chris Lattner0f984262008-03-01 08:50:34 +0000250
251 // Avoid an explicit cast on the IMP by getting a version that has the right
252 // return type.
253 llvm::FunctionType *impType = llvm::FunctionType::get(ReturnTy, impArgTypes,
254 true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000255 // Construct the structure used to look up the IMP
256 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
257 IdTy, NULL);
258 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Eli Friedman1e692ac2008-06-13 23:01:12 +0000259 // FIXME: volatility
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000260 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
261 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
262
263 // Get the IMP
264 llvm::Constant *lookupFunction =
265 TheModule.getOrInsertFunction("objc_msg_lookup_super",
266 llvm::PointerType::getUnqual(impType),
267 llvm::PointerType::getUnqual(ObjCSuperTy),
268 SelectorTy, NULL);
269 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
270 llvm::Value *imp = Builder.CreateCall(lookupFunction, lookupArgs,
271 lookupArgs+2);
272
273 // Call the method
274 llvm::SmallVector<llvm::Value*, 8> callArgs;
275 callArgs.push_back(Receiver);
276 callArgs.push_back(cmd);
277 callArgs.insert(callArgs.end(), ArgV, ArgV+ArgC);
278 return Builder.CreateCall(imp, callArgs.begin(), callArgs.end());
279}
280
281/// Generate code for a message send expression.
Chris Lattner85e35682008-08-08 19:57:58 +0000282llvm::Value *CGObjCGNU::GenerateMessageSend(llvm::IRBuilder<> &Builder,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000283 const llvm::Type *ReturnTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000284 llvm::Value *Receiver,
Chris Lattner9384c762008-06-26 04:42:20 +0000285 Selector Sel,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000286 llvm::Value** ArgV,
287 unsigned ArgC) {
Chris Lattner9384c762008-06-26 04:42:20 +0000288 llvm::Value *cmd = GetSelector(Builder, Sel);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000289
290 // Look up the method implementation.
291 std::vector<const llvm::Type*> impArgTypes;
292 const llvm::Type *RetTy;
293 //TODO: Revisit this when LLVM supports aggregate return types.
294 if (ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
295 RetTy = ReturnTy;
296 } else {
297 // For struct returns allocate the space in the caller and pass it up to
298 // the sender.
299 RetTy = llvm::Type::VoidTy;
300 impArgTypes.push_back(llvm::PointerType::getUnqual(ReturnTy));
301 }
302 impArgTypes.push_back(Receiver->getType());
303 impArgTypes.push_back(SelectorTy);
304
305 // Avoid an explicit cast on the IMP by getting a version that has the right
306 // return type.
307 llvm::FunctionType *impType = llvm::FunctionType::get(RetTy, impArgTypes,
308 true);
Chris Lattner0f984262008-03-01 08:50:34 +0000309
310 llvm::Constant *lookupFunction =
311 TheModule.getOrInsertFunction("objc_msg_lookup",
Chris Lattner391d77a2008-03-30 23:03:07 +0000312 llvm::PointerType::getUnqual(impType),
313 Receiver->getType(), SelectorTy, NULL);
Chris Lattner3eae03e2008-05-06 00:56:42 +0000314 llvm::Value *imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
315
316 // Call the method.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000317 llvm::SmallVector<llvm::Value*, 16> Args;
318 if (!ReturnTy->isSingleValueType()) {
319 llvm::Value *Return = Builder.CreateAlloca(ReturnTy);
320 Args.push_back(Return);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000321 }
322 Args.push_back(Receiver);
323 Args.push_back(cmd);
324 Args.insert(Args.end(), ArgV, ArgV+ArgC);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000325 if (!ReturnTy->isSingleValueType()) {
326 Builder.CreateCall(imp, Args.begin(), Args.end());
327 return Args[0];
328 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000329 return Builder.CreateCall(imp, Args.begin(), Args.end());
Chris Lattner0f984262008-03-01 08:50:34 +0000330}
331
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000332/// Generates a MethodList. Used in construction of a objc_class and
333/// objc_category structures.
334llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattnera4210072008-06-26 05:08:00 +0000335 const std::string &CategoryName,
336 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000337 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
338 bool isClassMethodList) {
339 // Get the method structure type.
340 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
341 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
342 PtrToInt8Ty, // Method types
343 llvm::PointerType::getUnqual(IMPTy), //Method pointer
344 NULL);
345 std::vector<llvm::Constant*> Methods;
346 std::vector<llvm::Constant*> Elements;
347 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
348 Elements.clear();
Daniel Dunbar61432932008-08-13 23:20:05 +0000349 llvm::Constant *C = CGM.GetAddrOfConstantCString(MethodSels[i].getName());
Chris Lattnera4210072008-06-26 05:08:00 +0000350 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000351 Elements.push_back(
352 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
353 llvm::Constant *Method =
354 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnera4210072008-06-26 05:08:00 +0000355 MethodSels[i].getName(),
Chris Lattner550b8db2008-06-26 04:05:20 +0000356 isClassMethodList));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000357 Method = llvm::ConstantExpr::getBitCast(Method,
358 llvm::PointerType::getUnqual(IMPTy));
359 Elements.push_back(Method);
360 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
361 }
362
363 // Array of method structures
364 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Chris Lattnera4210072008-06-26 05:08:00 +0000365 MethodSels.size());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000366 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000367 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000368
369 // Structure containing list pointer, array and array count
370 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
371 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
372 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
373 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
374 IntTy,
375 ObjCMethodArrayTy,
376 NULL);
377 // Refine next pointer type to concrete type
378 llvm::cast<llvm::OpaqueType>(
379 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
380 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
381
382 Methods.clear();
383 Methods.push_back(llvm::ConstantPointerNull::get(
384 llvm::PointerType::getUnqual(ObjCMethodListTy)));
385 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
386 MethodTypes.size()));
387 Methods.push_back(MethodArray);
388
389 // Create an instance of the structure
390 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
391}
392
393/// Generates an IvarList. Used in construction of a objc_class.
394llvm::Constant *CGObjCGNU::GenerateIvarList(
395 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
396 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
397 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
398 // Get the method structure type.
399 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
400 PtrToInt8Ty,
401 PtrToInt8Ty,
402 IntTy,
403 NULL);
404 std::vector<llvm::Constant*> Ivars;
405 std::vector<llvm::Constant*> Elements;
406 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
407 Elements.clear();
408 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
409 Zeros, 2));
410 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
411 Zeros, 2));
412 Elements.push_back(IvarOffsets[i]);
413 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
414 }
415
416 // Array of method structures
417 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
418 IvarNames.size());
419
420
421 Elements.clear();
422 Elements.push_back(llvm::ConstantInt::get(
423 llvm::cast<llvm::IntegerType>(IntTy), (int)IvarNames.size()));
424 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
425 // Structure containing array and array count
426 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
427 ObjCIvarArrayTy,
428 NULL);
429
430 // Create an instance of the structure
431 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
432}
433
434/// Generate a class structure
435llvm::Constant *CGObjCGNU::GenerateClassStructure(
436 llvm::Constant *MetaClass,
437 llvm::Constant *SuperClass,
438 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000439 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000440 llvm::Constant *Version,
441 llvm::Constant *InstanceSize,
442 llvm::Constant *IVars,
443 llvm::Constant *Methods,
444 llvm::Constant *Protocols) {
445 // Set up the class structure
446 // Note: Several of these are char*s when they should be ids. This is
447 // because the runtime performs this translation on load.
448 llvm::StructType *ClassTy = llvm::StructType::get(
449 PtrToInt8Ty, // class_pointer
450 PtrToInt8Ty, // super_class
451 PtrToInt8Ty, // name
452 LongTy, // version
453 LongTy, // info
454 LongTy, // instance_size
455 IVars->getType(), // ivars
456 Methods->getType(), // methods
457 // These are all filled in by the runtime, so we pretend
458 PtrTy, // dtable
459 PtrTy, // subclass_list
460 PtrTy, // sibling_class
461 PtrTy, // protocols
462 PtrTy, // gc_object_type
463 NULL);
464 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
465 llvm::Constant *NullP =
466 llvm::ConstantPointerNull::get(llvm::cast<llvm::PointerType>(PtrTy));
467 // Fill in the structure
468 std::vector<llvm::Constant*> Elements;
469 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
470 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000471 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000472 Elements.push_back(Zero);
473 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
474 Elements.push_back(InstanceSize);
475 Elements.push_back(IVars);
476 Elements.push_back(Methods);
477 Elements.push_back(NullP);
478 Elements.push_back(NullP);
479 Elements.push_back(NullP);
480 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
481 Elements.push_back(NullP);
482 // Create an instance of the structure
Chris Lattner1565e032008-07-21 06:31:05 +0000483 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000484}
485
486llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
487 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
488 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
489 // Get the method structure type.
490 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
491 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
492 PtrToInt8Ty,
493 NULL);
494 std::vector<llvm::Constant*> Methods;
495 std::vector<llvm::Constant*> Elements;
496 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
497 Elements.clear();
498 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
499 Zeros, 2));
500 Elements.push_back(
501 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
502 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
503 }
504 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
505 MethodNames.size());
506 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
507 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
508 IntTy, ObjCMethodArrayTy, NULL);
509 Methods.clear();
510 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
511 Methods.push_back(Array);
512 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
513}
514// Create the protocol list structure used in classes, categories and so on
515llvm::Constant *CGObjCGNU::GenerateProtocolList(
516 const llvm::SmallVectorImpl<std::string> &Protocols) {
517 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
518 Protocols.size());
519 llvm::StructType *ProtocolListTy = llvm::StructType::get(
520 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
521 LongTy,//FIXME: Should be size_t
522 ProtocolArrayTy,
523 NULL);
524 std::vector<llvm::Constant*> Elements;
525 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
526 iter != endIter ; iter++) {
527 llvm::Constant *Ptr =
528 llvm::ConstantExpr::getBitCast(ExistingProtocols[*iter], PtrToInt8Ty);
529 Elements.push_back(Ptr);
530 }
531 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
532 Elements);
533 Elements.clear();
534 Elements.push_back(NULLPtr);
535 Elements.push_back(llvm::ConstantInt::get(
536 llvm::cast<llvm::IntegerType>(LongTy), Protocols.size()));
537 Elements.push_back(ProtocolArray);
538 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
539}
540
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000541llvm::Value *CGObjCGNU::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
542 const ObjCProtocolDecl *PD) {
543 return ExistingProtocols[PD->getName()];
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000544}
545
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000546void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
547 ASTContext &Context = CGM.getContext();
548 const char *ProtocolName = PD->getName();
549 llvm::SmallVector<std::string, 16> Protocols;
550 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
551 E = PD->protocol_end(); PI != E; ++PI)
552 Protocols.push_back((*PI)->getName());
553 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
554 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
555 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
556 E = PD->instmeth_end(); iter != E; iter++) {
557 std::string TypeStr;
558 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
559 InstanceMethodNames.push_back(
Daniel Dunbar61432932008-08-13 23:20:05 +0000560 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
561 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000562 }
563 // Collect information about class methods:
564 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
565 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
566 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
567 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
568 std::string TypeStr;
569 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
570 ClassMethodNames.push_back(
Daniel Dunbar61432932008-08-13 23:20:05 +0000571 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
572 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000573 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000574
575 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
576 llvm::Constant *InstanceMethodList =
577 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
578 llvm::Constant *ClassMethodList =
579 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
580 // Protocols are objects containing lists of the methods implemented and
581 // protocols adopted.
582 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
583 PtrToInt8Ty,
584 ProtocolList->getType(),
585 InstanceMethodList->getType(),
586 ClassMethodList->getType(),
587 NULL);
588 std::vector<llvm::Constant*> Elements;
589 // The isa pointer must be set to a magic number so the runtime knows it's
590 // the correct layout.
591 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
592 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
593 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
594 Elements.push_back(ProtocolList);
595 Elements.push_back(InstanceMethodList);
596 Elements.push_back(ClassMethodList);
597 ExistingProtocols[ProtocolName] =
598 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
599 ".objc_protocol"), IdTy);
600}
601
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000602void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
603 const char *ClassName = OCD->getClassInterface()->getName();
604 const char *CategoryName = OCD->getName();
605 // Collect information about instance methods
606 llvm::SmallVector<Selector, 16> InstanceMethodSels;
607 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
608 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
609 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
610 InstanceMethodSels.push_back((*iter)->getSelector());
611 std::string TypeStr;
612 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
613 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
614 }
615
616 // Collect information about class methods
617 llvm::SmallVector<Selector, 16> ClassMethodSels;
618 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
619 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
620 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
621 ClassMethodSels.push_back((*iter)->getSelector());
622 std::string TypeStr;
623 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
624 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
625 }
626
627 // Collect the names of referenced protocols
628 llvm::SmallVector<std::string, 16> Protocols;
629 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
630 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
631 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
632 E = Protos.end(); I != E; ++I)
633 Protocols.push_back((*I)->getName());
634
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000635 std::vector<llvm::Constant*> Elements;
636 Elements.push_back(MakeConstantString(CategoryName));
637 Elements.push_back(MakeConstantString(ClassName));
638 // Instance method list
639 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000640 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000641 false), PtrTy));
642 // Class method list
643 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000644 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000645 PtrTy));
646 // Protocol list
647 Elements.push_back(llvm::ConstantExpr::getBitCast(
648 GenerateProtocolList(Protocols), PtrTy));
649 Categories.push_back(llvm::ConstantExpr::getBitCast(
650 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
651 PtrTy, PtrTy, NULL), Elements), PtrTy));
652}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000653
654void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
655 ASTContext &Context = CGM.getContext();
656
657 // Get the superclass name.
658 const ObjCInterfaceDecl * SuperClassDecl =
659 OID->getClassInterface()->getSuperClass();
660 const char * SuperClassName = NULL;
661 if (SuperClassDecl) {
662 SuperClassName = SuperClassDecl->getName();
663 }
664
665 // Get the class name
666 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
667 const char * ClassName = ClassDecl->getName();
668
669 // Get the size of instances. For runtimes that support late-bound instances
670 // this should probably be something different (size just of instance
671 // varaibles in this class, not superclasses?).
672 int instanceSize = 0;
673 const llvm::Type *ObjTy = 0;
674 if (!LateBoundIVars()) {
675 ObjTy = CGM.getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
676 instanceSize = CGM.getTargetData().getABITypeSize(ObjTy);
677 } else {
678 // This is required by newer ObjC runtimes.
679 assert(0 && "Late-bound instance variables not yet supported");
680 }
681
682 // Collect information about instance variables.
683 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
684 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
685 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
686 const llvm::StructLayout *Layout =
687 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(ObjTy));
688 ObjTy = llvm::PointerType::getUnqual(ObjTy);
689 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
690 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
691 // Store the name
692 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)->getName()));
693 // Get the type encoding for this ivar
694 std::string TypeStr;
695 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
696 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
697 EncodingRecordTypes);
698 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
699 // Get the offset
700 int offset =
701 (int)Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(*iter));
702 IvarOffsets.push_back(
703 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
704 }
705
706 // Collect information about instance methods
707 llvm::SmallVector<Selector, 16> InstanceMethodSels;
708 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
709 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
710 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
711 InstanceMethodSels.push_back((*iter)->getSelector());
712 std::string TypeStr;
713 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
714 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
715 }
716
717 // Collect information about class methods
718 llvm::SmallVector<Selector, 16> ClassMethodSels;
719 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
720 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
721 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
722 ClassMethodSels.push_back((*iter)->getSelector());
723 std::string TypeStr;
724 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
725 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
726 }
727 // Collect the names of referenced protocols
728 llvm::SmallVector<std::string, 16> Protocols;
729 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
730 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
731 E = Protos.end(); I != E; ++I)
732 Protocols.push_back((*I)->getName());
733
734
735
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000736 // Get the superclass pointer.
737 llvm::Constant *SuperClass;
738 if (SuperClassName) {
739 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
740 } else {
741 SuperClass = llvm::ConstantPointerNull::get(
742 llvm::cast<llvm::PointerType>(PtrToInt8Ty));
743 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000744 // Empty vector used to construct empty method lists
745 llvm::SmallVector<llvm::Constant*, 1> empty;
746 // Generate the method and instance variable lists
747 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000748 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000749 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000750 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000751 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
752 IvarOffsets);
753 //Generate metaclass for class methods
754 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner1565e032008-07-21 06:31:05 +0000755 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000756 empty, empty, empty), ClassMethodList, NULLPtr);
757 // Generate the class structure
758 llvm::Constant *ClassStruct = GenerateClassStructure(MetaClassStruct,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000759 SuperClass, 0x1L, ClassName, 0,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000760 llvm::ConstantInt::get(llvm::Type::Int32Ty, instanceSize), IvarList,
761 MethodList, GenerateProtocolList(Protocols));
762 // Add class structure to list to be added to the symtab later
763 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
764 Classes.push_back(ClassStruct);
765}
766
767llvm::Function *CGObjCGNU::ModuleInitFunction() {
768 // Only emit an ObjC load function if no Objective-C stuff has been called
769 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
770 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +0000771 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000772 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +0000773
774 // Name the ObjC types to make the IR a bit easier to read
775 TheModule.addTypeName(".objc_selector", SelectorTy);
776 TheModule.addTypeName(".objc_id", IdTy);
777 TheModule.addTypeName(".objc_imp", IMPTy);
778
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000779 std::vector<llvm::Constant*> Elements;
780 // Generate statics list:
781 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
782 ConstantStrings.size() + 1);
783 ConstantStrings.push_back(NULLPtr);
784 Elements.push_back(MakeConstantString("NSConstantString",
785 ".objc_static_class_name"));
786 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, ConstantStrings));
787 llvm::StructType *StaticsListTy =
788 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Chris Lattner630404b2008-06-26 04:10:42 +0000789 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000790 llvm::Constant *Statics =
791 MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Chris Lattner4e0b2642008-06-24 17:01:28 +0000792 llvm::ArrayType *StaticsListArrayTy =
Chris Lattner630404b2008-06-26 04:10:42 +0000793 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner4e0b2642008-06-24 17:01:28 +0000794 Elements.clear();
795 Elements.push_back(Statics);
Chris Lattner630404b2008-06-26 04:10:42 +0000796 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner4e0b2642008-06-24 17:01:28 +0000797 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000798 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
799 // Array of classes, categories, and constant objects
800 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
801 Classes.size() + Categories.size() + 2);
Chris Lattner630404b2008-06-26 04:10:42 +0000802 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelectorTy,
803 llvm::Type::Int16Ty,
804 llvm::Type::Int16Ty,
805 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000806
807 Elements.clear();
808 // Pointer to an array of selectors used in this module.
809 std::vector<llvm::Constant*> Selectors;
810 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
811 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
812 iter != iterEnd ; ++iter) {
Chris Lattner630404b2008-06-26 04:10:42 +0000813 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
814 Elements.push_back(MakeConstantString(iter->first.second,
815 ".objc_sel_types"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000816 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
817 Elements.clear();
818 }
819 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
820 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +0000821 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000822 Elements.push_back(
Chris Lattner630404b2008-06-26 04:10:42 +0000823 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000824 Elements.push_back(NULLPtr);
825 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
826 Elements.clear();
827 }
828 Elements.push_back(NULLPtr);
829 Elements.push_back(NULLPtr);
830 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
831 Elements.clear();
832 // Number of static selectors
833 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
834 llvm::Constant *SelectorList = MakeGlobal(
835 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
836 ".objc_selector_list");
837 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, SelectorTy));
838
839 // Now that all of the static selectors exist, create pointers to them.
840 int index = 0;
841 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
842 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
843 iter != iterEnd; ++iter) {
844 llvm::Constant *Idxs[] = {Zeros[0],
845 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
846 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
847 llvm::GlobalValue::InternalLinkage,
848 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
849 ".objc_sel_ptr", &TheModule);
850 (*iter).second->setAliasee(SelPtr);
851 }
852 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
853 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
854 iter != iterEnd; iter++) {
855 llvm::Constant *Idxs[] = {Zeros[0],
856 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
857 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
858 llvm::GlobalValue::InternalLinkage,
859 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
860 ".objc_sel_ptr", &TheModule);
861 (*iter).second->setAliasee(SelPtr);
862 }
863 // Number of classes defined.
864 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
865 Classes.size()));
866 // Number of categories defined
867 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
868 Categories.size()));
869 // Create an array of classes, then categories, then static object instances
870 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
871 // NULL-terminated list of static object instances (mainly constant strings)
872 Classes.push_back(Statics);
873 Classes.push_back(NULLPtr);
874 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
875 Elements.push_back(ClassList);
876 // Construct the symbol table
877 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
878
879 // The symbol table is contained in a module which has some version-checking
880 // constants
881 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
882 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
883 Elements.clear();
884 // Runtime version used for compatibility checking.
885 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
886 //FIXME: Should be sizeof(ModuleTy)
887 Elements.push_back(llvm::ConstantInt::get(LongTy, 16));
888 //FIXME: Should be the path to the file where this module was declared
889 Elements.push_back(NULLPtr);
890 Elements.push_back(SymTab);
891 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
892
893 // Create the load function calling the runtime entry point with the module
894 // structure
895 std::vector<const llvm::Type*> VoidArgs;
896 llvm::Function * LoadFunction = llvm::Function::Create(
897 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
898 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
899 &TheModule);
900 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Chris Lattner85e35682008-08-08 19:57:58 +0000901 llvm::IRBuilder<> Builder;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000902 Builder.SetInsertPoint(EntryBB);
903 llvm::Value *Register = TheModule.getOrInsertFunction("__objc_exec_class",
904 llvm::Type::VoidTy, llvm::PointerType::getUnqual(ModuleTy), NULL);
905 Builder.CreateCall(Register, Module);
906 Builder.CreateRetVoid();
907 return LoadFunction;
908}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000909
910llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD) {
911 const llvm::Type *ReturnTy =
912 CGM.getTypes().ConvertReturnType(OMD->getResultType());
913 const ObjCCategoryImplDecl *OCD =
914 dyn_cast<ObjCCategoryImplDecl>(OMD->getMethodContext());
915 const std::string &CategoryName = OCD ? OCD->getName() : "";
916 const llvm::Type *SelfTy = llvm::PointerType::getUnqual(llvm::Type::Int32Ty);
917 const std::string &ClassName = OMD->getClassInterface()->getName();
918 const std::string &MethodName = OMD->getSelector().getName();
919 unsigned ArgC = OMD->param_size();
920 bool isClassMethod = !OMD->isInstance();
921 bool isVarArg = OMD->isVariadic();
922
923 llvm::SmallVector<const llvm::Type *, 16> ArgTy;
924 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
925 const llvm::Type *Ty =
926 CGM.getTypes().ConvertType(OMD->getParamDecl(i)->getType());
927 if (Ty->isFirstClassType())
928 ArgTy.push_back(Ty);
929 else
930 ArgTy.push_back(llvm::PointerType::getUnqual(Ty));
931 }
932
Chris Lattner391d77a2008-03-30 23:03:07 +0000933 std::vector<const llvm::Type*> Args;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000934 if (!ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000935 Args.push_back(llvm::PointerType::getUnqual(ReturnTy));
936 ReturnTy = llvm::Type::VoidTy;
937 }
Chris Lattner391d77a2008-03-30 23:03:07 +0000938 Args.push_back(SelfTy);
939 Args.push_back(SelectorTy);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000940 Args.insert(Args.end(), ArgTy.begin(), ArgTy.begin()+ArgC);
Chris Lattner391d77a2008-03-30 23:03:07 +0000941
942 llvm::FunctionType *MethodTy = llvm::FunctionType::get(ReturnTy,
943 Args,
944 isVarArg);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
946 MethodName, isClassMethod);
947
Gabor Greif984d0b42008-04-06 20:42:52 +0000948 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattner391d77a2008-03-30 23:03:07 +0000949 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000950 FunctionName,
Chris Lattner391d77a2008-03-30 23:03:07 +0000951 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +0000952 llvm::Function::arg_iterator AI = Method->arg_begin();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000953 // Name the struct return argument.
954 // FIXME: This is probably the wrong test.
955 if (!ReturnTy->isFirstClassType() && ReturnTy != llvm::Type::VoidTy) {
956 AI->setName("agg.result");
957 ++AI;
958 }
Chris Lattner391d77a2008-03-30 23:03:07 +0000959 AI->setName("self");
960 ++AI;
961 AI->setName("_cmd");
962 return Method;
963}
964
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000965CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattnerdce14062008-06-26 04:19:03 +0000966 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +0000967}