CGObjCGNU.cpp revision ddb2a3d55a24a1dbdf9152621642d9a4b4fc2f61
1//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
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//
10// 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.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclObjC.h"
22#include "llvm/Module.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/IRBuilder.h"
27#include "llvm/Target/TargetData.h"
28#include <map>
29using namespace clang;
30using 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;
36
37namespace {
38class CGObjCGNU : public CodeGen::CGObjCRuntime {
39private:
40  CodeGen::CodeGenModule &CGM;
41  llvm::Module &TheModule;
42  const llvm::StructType *SelStructTy;
43  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;
51  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,
69      const llvm::SmallVectorImpl<Selector>  &MethodSels,
70      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,
78      const char *Name,
79      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="");
93public:
94  CGObjCGNU(CodeGen::CodeGenModule &cgm);
95  virtual llvm::Constant *GenerateConstantString(const std::string &String);
96  virtual llvm::Value *GenerateMessageSend(llvm::IRBuilder<> &Builder,
97                                           const llvm::Type *ReturnTy,
98                                           llvm::Value *Receiver,
99                                           Selector Sel,
100                                           llvm::Value** ArgV,
101                                           unsigned ArgC);
102  virtual llvm::Value *GenerateMessageSendSuper(llvm::IRBuilder<> &Builder,
103                                                const llvm::Type *ReturnTy,
104                                            const ObjCInterfaceDecl *SuperClass,
105                                                llvm::Value *Receiver,
106                                                Selector Sel,
107                                                llvm::Value** ArgV,
108                                                unsigned ArgC);
109  virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
110                                const ObjCInterfaceDecl *OID);
111  virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
112
113  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
114  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
115  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
116  virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
117                                           const ObjCProtocolDecl *PD);
118  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
119  virtual llvm::Function *ModuleInitFunction();
120};
121} // end anonymous namespace
122
123
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
136CGObjCGNU::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
141  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));
145  // C string type.  Used in lots of places.
146  PtrToInt8Ty =
147    llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
148  // Get the selector Type.
149  SelStructTy = llvm::StructType::get(
150      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);
170}
171// This has to perform the lookup every time, since posing and related
172// techniques can modify the name -> class mapping.
173llvm::Value *CGObjCGNU::GetClass(llvm::IRBuilder<> &Builder,
174                                 const ObjCInterfaceDecl *OID) {
175  llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getName());
176  ClassName = Builder.CreateStructGEP(ClassName, 0);
177
178  llvm::Constant *ClassLookupFn =
179    TheModule.getOrInsertFunction("objc_lookup_class", IdTy, PtrToInt8Ty,
180        NULL);
181  return Builder.CreateCall(ClassLookupFn, ClassName);
182}
183
184/// GetSelector - Return the pointer to the unique'd string for this selector.
185llvm::Value *CGObjCGNU::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
186  // FIXME: uniquing on the string is wasteful, unique on Sel instead!
187  llvm::GlobalAlias *&US = UntypedSelectors[Sel.getName()];
188  if (US == 0)
189    US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
190                               llvm::GlobalValue::InternalLinkage,
191                               ".objc_untyped_selector_alias",
192                               NULL, &TheModule);
193
194  return Builder.CreateLoad(US);
195
196}
197
198llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
199                                              const std::string &Name) {
200  llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
201  ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
202                               llvm::GlobalValue::InternalLinkage,
203                               ConstStr, Name, &TheModule);
204  return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
205}
206llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
207    std::vector<llvm::Constant*> &V, const std::string &Name) {
208  llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
209  return new llvm::GlobalVariable(Ty, false,
210      llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
211}
212llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
213    std::vector<llvm::Constant*> &V, const std::string &Name) {
214  llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
215  return new llvm::GlobalVariable(Ty, false,
216      llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
217}
218
219/// Generate an NSConstantString object.
220//TODO: In case there are any crazy people still using the GNU runtime without
221//an OpenStep implementation, this should let them select their own class for
222//constant strings.
223llvm::Constant *CGObjCGNU::GenerateConstantString(const std::string &Str) {
224  std::vector<llvm::Constant*> Ivars;
225  Ivars.push_back(NULLPtr);
226  Ivars.push_back(MakeConstantString(Str));
227  Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
228  llvm::Constant *ObjCStr = MakeGlobal(
229    llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
230    Ivars, ".objc_str");
231  ConstantStrings.push_back(
232      llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
233  return ObjCStr;
234}
235
236///Generates a message send where the super is the receiver.  This is a message
237///send to self with special delivery semantics indicating which class's method
238///should be called.
239llvm::Value *CGObjCGNU::GenerateMessageSendSuper(llvm::IRBuilder<> &Builder,
240                                                 const llvm::Type *ReturnTy,
241                                            const ObjCInterfaceDecl *SuperClass,
242                                                 llvm::Value *Receiver,
243                                                 Selector Sel,
244                                                 llvm::Value** ArgV,
245                                                 unsigned ArgC) {
246  // TODO: This should be cached, not looked up every time.
247  llvm::Value *ReceiverClass = GetClass(Builder, SuperClass);
248  llvm::Value *cmd = GetSelector(Builder, Sel);
249  std::vector<const llvm::Type*> impArgTypes;
250  impArgTypes.push_back(Receiver->getType());
251  impArgTypes.push_back(SelectorTy);
252
253  // Avoid an explicit cast on the IMP by getting a version that has the right
254  // return type.
255  llvm::FunctionType *impType = llvm::FunctionType::get(ReturnTy, impArgTypes,
256                                                        true);
257  // Construct the structure used to look up the IMP
258  llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
259      IdTy, NULL);
260  llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
261  // FIXME: volatility
262  Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
263  Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
264
265  // Get the IMP
266  llvm::Constant *lookupFunction =
267     TheModule.getOrInsertFunction("objc_msg_lookup_super",
268                                   llvm::PointerType::getUnqual(impType),
269                                   llvm::PointerType::getUnqual(ObjCSuperTy),
270                                   SelectorTy, NULL);
271  llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
272  llvm::Value *imp = Builder.CreateCall(lookupFunction, lookupArgs,
273      lookupArgs+2);
274
275  // Call the method
276  llvm::SmallVector<llvm::Value*, 8> callArgs;
277  callArgs.push_back(Receiver);
278  callArgs.push_back(cmd);
279  callArgs.insert(callArgs.end(), ArgV, ArgV+ArgC);
280  return Builder.CreateCall(imp, callArgs.begin(), callArgs.end());
281}
282
283/// Generate code for a message send expression.
284llvm::Value *CGObjCGNU::GenerateMessageSend(llvm::IRBuilder<> &Builder,
285                                            const llvm::Type *ReturnTy,
286                                            llvm::Value *Receiver,
287                                            Selector Sel,
288                                            llvm::Value** ArgV,
289                                            unsigned ArgC) {
290  llvm::Value *cmd = GetSelector(Builder, Sel);
291
292  // Look up the method implementation.
293  std::vector<const llvm::Type*> impArgTypes;
294  const llvm::Type *RetTy;
295  //TODO: Revisit this when LLVM supports aggregate return types.
296  if (ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
297    RetTy = ReturnTy;
298  } else {
299    // For struct returns allocate the space in the caller and pass it up to
300    // the sender.
301    RetTy = llvm::Type::VoidTy;
302    impArgTypes.push_back(llvm::PointerType::getUnqual(ReturnTy));
303  }
304  impArgTypes.push_back(Receiver->getType());
305  impArgTypes.push_back(SelectorTy);
306
307  // Avoid an explicit cast on the IMP by getting a version that has the right
308  // return type.
309  llvm::FunctionType *impType = llvm::FunctionType::get(RetTy, impArgTypes,
310                                                        true);
311
312  llvm::Constant *lookupFunction =
313     TheModule.getOrInsertFunction("objc_msg_lookup",
314                                   llvm::PointerType::getUnqual(impType),
315                                   Receiver->getType(), SelectorTy, NULL);
316  llvm::Value *imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
317
318  // Call the method.
319  llvm::SmallVector<llvm::Value*, 16> Args;
320  if (!ReturnTy->isSingleValueType()) {
321    llvm::Value *Return = Builder.CreateAlloca(ReturnTy);
322    Args.push_back(Return);
323  }
324  Args.push_back(Receiver);
325  Args.push_back(cmd);
326  Args.insert(Args.end(), ArgV, ArgV+ArgC);
327  if (!ReturnTy->isSingleValueType()) {
328    Builder.CreateCall(imp, Args.begin(), Args.end());
329    return Args[0];
330  }
331  return Builder.CreateCall(imp, Args.begin(), Args.end());
332}
333
334/// Generates a MethodList.  Used in construction of a objc_class and
335/// objc_category structures.
336llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
337                                              const std::string &CategoryName,
338    const llvm::SmallVectorImpl<Selector> &MethodSels,
339    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();
351    llvm::Constant *C = CGM.GetAddrOfConstantCString(MethodSels[i].getName());
352    Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
353    Elements.push_back(
354          llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
355    llvm::Constant *Method =
356      TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
357                                                MethodSels[i].getName(),
358                                                isClassMethodList));
359    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,
367                                                            MethodSels.size());
368  llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
369                                                         Methods);
370
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,
441    const char *Name,
442    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);
473  Elements.push_back(MakeConstantString(Name, ".class_name"));
474  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
485  return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
486}
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
543llvm::Value *CGObjCGNU::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
544                                            const ObjCProtocolDecl *PD) {
545  return ExistingProtocols[PD->getName()];
546}
547
548void 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(
562        CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
563    InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
564  }
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(
573        CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
574    ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
575  }
576
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
604void 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
637  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(
642          ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
643          false), PtrTy));
644  // Class method list
645  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
646          ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
647        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}
655
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
738  // 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  }
746  // 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, "",
750      InstanceMethodSels, InstanceMethodTypes, false);
751  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
752      ClassMethodSels, ClassMethodTypes, true);
753  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
754      IvarOffsets);
755  //Generate metaclass for class methods
756  llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
757      NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
758        empty, empty, empty), ClassMethodList, NULLPtr);
759  // Generate the class structure
760  llvm::Constant *ClassStruct = GenerateClassStructure(MetaClassStruct,
761      SuperClass, 0x1L, ClassName, 0,
762      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() &&
773      UntypedSelectors.empty())
774    return NULL;
775
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
781  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);
791  llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
792  llvm::Constant *Statics =
793    MakeGlobal(StaticsListTy, Elements, ".objc_statics");
794  llvm::ArrayType *StaticsListArrayTy =
795    llvm::ArrayType::get(StaticsListPtrTy, 2);
796  Elements.clear();
797  Elements.push_back(Statics);
798  Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
799  Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
800  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);
804  llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelectorTy,
805                                                     llvm::Type::Int16Ty,
806                                                     llvm::Type::Int16Ty,
807                                                     ClassListTy, NULL);
808
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) {
815    Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
816    Elements.push_back(MakeConstantString(iter->first.second,
817                                          ".objc_sel_types"));
818    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();
823      iter != iterEnd; ++iter) {
824    Elements.push_back(
825        MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
826    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);
903  llvm::IRBuilder<> Builder;
904  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}
911
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
935  std::vector<const llvm::Type*> Args;
936  if (!ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
937    Args.push_back(llvm::PointerType::getUnqual(ReturnTy));
938    ReturnTy = llvm::Type::VoidTy;
939  }
940  Args.push_back(SelfTy);
941  Args.push_back(SelectorTy);
942  Args.insert(Args.end(), ArgTy.begin(), ArgTy.begin()+ArgC);
943
944  llvm::FunctionType *MethodTy = llvm::FunctionType::get(ReturnTy,
945      Args,
946      isVarArg);
947  std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
948      MethodName, isClassMethod);
949
950  llvm::Function *Method = llvm::Function::Create(MethodTy,
951      llvm::GlobalValue::InternalLinkage,
952      FunctionName,
953      &TheModule);
954  llvm::Function::arg_iterator AI = Method->arg_begin();
955  // Name the struct return argument.
956  // FIXME: This is probably the wrong test.
957  if (!ReturnTy->isFirstClassType() && ReturnTy != llvm::Type::VoidTy) {
958    AI->setName("agg.result");
959    ++AI;
960  }
961  AI->setName("self");
962  ++AI;
963  AI->setName("_cmd");
964  return Method;
965}
966
967CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
968  return new CGObjCGNU(CGM);
969}
970