CGObjCGNU.cpp revision 195099
1193326Sed//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This provides Objective-C code generation targetting the GNU runtime.  The
11193326Sed// class in this file generates structures used by the GNU Objective-C runtime
12193326Sed// library.  These structures are defined in objc/objc.h and objc/objc-api.h in
13193326Sed// the GNU runtime distribution.
14193326Sed//
15193326Sed//===----------------------------------------------------------------------===//
16193326Sed
17193326Sed#include "CGObjCRuntime.h"
18193326Sed#include "CodeGenModule.h"
19193326Sed#include "CodeGenFunction.h"
20193326Sed
21193326Sed#include "clang/AST/ASTContext.h"
22193326Sed#include "clang/AST/Decl.h"
23193326Sed#include "clang/AST/DeclObjC.h"
24193326Sed#include "clang/AST/RecordLayout.h"
25193326Sed#include "clang/AST/StmtObjC.h"
26193326Sed
27193326Sed#include "llvm/Intrinsics.h"
28193326Sed#include "llvm/Module.h"
29193326Sed#include "llvm/ADT/SmallVector.h"
30193326Sed#include "llvm/ADT/StringMap.h"
31193326Sed#include "llvm/Support/Compiler.h"
32193326Sed#include "llvm/Target/TargetData.h"
33193326Sed
34193326Sed#include <map>
35193326Sed
36193326Sed
37193326Sedusing namespace clang;
38193326Sedusing namespace CodeGen;
39193326Sedusing llvm::dyn_cast;
40193326Sed
41193326Sed// The version of the runtime that this class targets.  Must match the version
42193326Sed// in the runtime.
43193326Sedstatic const int RuntimeVersion = 8;
44193326Sedstatic const int NonFragileRuntimeVersion = 9;
45193326Sedstatic const int ProtocolVersion = 2;
46193326Sed
47193326Sednamespace {
48193326Sedclass CGObjCGNU : public CodeGen::CGObjCRuntime {
49193326Sedprivate:
50193326Sed  CodeGen::CodeGenModule &CGM;
51193326Sed  llvm::Module &TheModule;
52193326Sed  const llvm::PointerType *SelectorTy;
53193326Sed  const llvm::PointerType *PtrToInt8Ty;
54193326Sed  const llvm::FunctionType *IMPTy;
55193326Sed  const llvm::PointerType *IdTy;
56193326Sed  const llvm::IntegerType *IntTy;
57193326Sed  const llvm::PointerType *PtrTy;
58193326Sed  const llvm::IntegerType *LongTy;
59193326Sed  const llvm::PointerType *PtrToIntTy;
60193326Sed  llvm::GlobalAlias *ClassPtrAlias;
61193326Sed  llvm::GlobalAlias *MetaClassPtrAlias;
62193326Sed  std::vector<llvm::Constant*> Classes;
63193326Sed  std::vector<llvm::Constant*> Categories;
64193326Sed  std::vector<llvm::Constant*> ConstantStrings;
65193326Sed  llvm::Function *LoadFunction;
66193326Sed  llvm::StringMap<llvm::Constant*> ExistingProtocols;
67193326Sed  typedef std::pair<std::string, std::string> TypedSelector;
68193326Sed  std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
69193326Sed  llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
70193326Sed  // Some zeros used for GEPs in lots of places.
71193326Sed  llvm::Constant *Zeros[2];
72193326Sed  llvm::Constant *NULLPtr;
73193326Sedprivate:
74193326Sed  llvm::Constant *GenerateIvarList(
75193326Sed      const llvm::SmallVectorImpl<llvm::Constant *>  &IvarNames,
76193326Sed      const llvm::SmallVectorImpl<llvm::Constant *>  &IvarTypes,
77193326Sed      const llvm::SmallVectorImpl<llvm::Constant *>  &IvarOffsets);
78193326Sed  llvm::Constant *GenerateMethodList(const std::string &ClassName,
79193326Sed      const std::string &CategoryName,
80193326Sed      const llvm::SmallVectorImpl<Selector>  &MethodSels,
81193326Sed      const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes,
82193326Sed      bool isClassMethodList);
83193326Sed  llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
84193326Sed  llvm::Constant *GenerateProtocolList(
85193326Sed      const llvm::SmallVectorImpl<std::string> &Protocols);
86193326Sed  llvm::Constant *GenerateClassStructure(
87193326Sed      llvm::Constant *MetaClass,
88193326Sed      llvm::Constant *SuperClass,
89193326Sed      unsigned info,
90193326Sed      const char *Name,
91193326Sed      llvm::Constant *Version,
92193326Sed      llvm::Constant *InstanceSize,
93193326Sed      llvm::Constant *IVars,
94193326Sed      llvm::Constant *Methods,
95193326Sed      llvm::Constant *Protocols);
96193326Sed  llvm::Constant *GenerateProtocolMethodList(
97193326Sed      const llvm::SmallVectorImpl<llvm::Constant *>  &MethodNames,
98193326Sed      const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes);
99193326Sed  llvm::Constant *MakeConstantString(const std::string &Str, const std::string
100193326Sed      &Name="");
101193326Sed  llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
102193326Sed      std::vector<llvm::Constant*> &V, const std::string &Name="");
103193326Sed  llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
104193326Sed      std::vector<llvm::Constant*> &V, const std::string &Name="");
105193326Sed  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
106193326Sed      const ObjCIvarDecl *Ivar);
107194613Sed  void EmitClassRef(const std::string &className);
108193326Sedpublic:
109193326Sed  CGObjCGNU(CodeGen::CodeGenModule &cgm);
110193326Sed  virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *);
111193326Sed  virtual CodeGen::RValue
112193326Sed  GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
113193326Sed                      QualType ResultType,
114193326Sed                      Selector Sel,
115193326Sed                      llvm::Value *Receiver,
116193326Sed                      bool IsClassMessage,
117193326Sed                      const CallArgList &CallArgs,
118193326Sed                      const ObjCMethodDecl *Method);
119193326Sed  virtual CodeGen::RValue
120193326Sed  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
121193326Sed                           QualType ResultType,
122193326Sed                           Selector Sel,
123193326Sed                           const ObjCInterfaceDecl *Class,
124193326Sed                           bool isCategoryImpl,
125193326Sed                           llvm::Value *Receiver,
126193326Sed                           bool IsClassMessage,
127193326Sed                           const CallArgList &CallArgs);
128193326Sed  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
129193326Sed                                const ObjCInterfaceDecl *OID);
130193326Sed  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
131193326Sed  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
132193326Sed      *Method);
133193326Sed
134193326Sed  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
135193326Sed                                         const ObjCContainerDecl *CD);
136193326Sed  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
137193326Sed  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
138193326Sed  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
139193326Sed                                           const ObjCProtocolDecl *PD);
140193326Sed  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
141193326Sed  virtual llvm::Function *ModuleInitFunction();
142195099Sed  virtual void MergeMetadataGlobals(std::vector<llvm::Constant*> &UsedArray);
143193326Sed  virtual llvm::Function *GetPropertyGetFunction();
144193326Sed  virtual llvm::Function *GetPropertySetFunction();
145193326Sed  virtual llvm::Function *EnumerationMutationFunction();
146193326Sed
147193326Sed  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
148193326Sed                                         const Stmt &S);
149193326Sed  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
150193326Sed                             const ObjCAtThrowStmt &S);
151193326Sed  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
152193326Sed                                         llvm::Value *AddrWeakObj);
153193326Sed  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
154193326Sed                                  llvm::Value *src, llvm::Value *dst);
155193326Sed  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
156193326Sed                                    llvm::Value *src, llvm::Value *dest);
157193326Sed  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
158193326Sed                                    llvm::Value *src, llvm::Value *dest);
159193326Sed  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
160193326Sed                                        llvm::Value *src, llvm::Value *dest);
161193326Sed  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
162193326Sed                                      QualType ObjectTy,
163193326Sed                                      llvm::Value *BaseValue,
164193326Sed                                      const ObjCIvarDecl *Ivar,
165193326Sed                                      unsigned CVRQualifiers);
166193326Sed  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
167193326Sed                                      const ObjCInterfaceDecl *Interface,
168193326Sed                                      const ObjCIvarDecl *Ivar);
169193326Sed};
170193326Sed} // end anonymous namespace
171193326Sed
172193326Sed
173194613Sed/// Emits a reference to a dummy variable which is emitted with each class.
174194613Sed/// This ensures that a linker error will be generated when trying to link
175194613Sed/// together modules where a referenced class is not defined.
176194613Sedvoid CGObjCGNU::EmitClassRef(const std::string &className){
177194613Sed  std::string symbolRef = "__objc_class_ref_" + className;
178194613Sed  // Don't emit two copies of the same symbol
179194613Sed  if (TheModule.getGlobalVariable(symbolRef)) return;
180194613Sed  std::string symbolName = "__objc_class_name_" + className;
181194613Sed  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
182194613Sed  if (!ClassSymbol) {
183194613Sed	ClassSymbol = new llvm::GlobalVariable(LongTy, false,
184194613Sed        llvm::GlobalValue::ExternalLinkage, 0, symbolName, &TheModule);
185194613Sed  }
186194613Sed  new llvm::GlobalVariable(ClassSymbol->getType(), true,
187194613Sed    llvm::GlobalValue::CommonLinkage, ClassSymbol, symbolRef,  &TheModule);
188194613Sed}
189193326Sed
190193326Sedstatic std::string SymbolNameForClass(const std::string &ClassName) {
191194613Sed  return "_OBJC_CLASS_" + ClassName;
192193326Sed}
193193326Sed
194193326Sedstatic std::string SymbolNameForMethod(const std::string &ClassName, const
195193326Sed  std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
196193326Sed{
197194613Sed  return "_OBJC_METHOD_" + ClassName + "("+CategoryName+")"+
198193326Sed            (isClassMethod ? "+" : "-") + MethodName;
199193326Sed}
200193326Sed
201193326SedCGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
202193326Sed  : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
203193326Sed    MetaClassPtrAlias(0) {
204193326Sed  IntTy = cast<llvm::IntegerType>(
205193326Sed      CGM.getTypes().ConvertType(CGM.getContext().IntTy));
206193326Sed  LongTy = cast<llvm::IntegerType>(
207193326Sed      CGM.getTypes().ConvertType(CGM.getContext().LongTy));
208193326Sed
209193326Sed  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
210193326Sed  Zeros[1] = Zeros[0];
211193326Sed  NULLPtr = llvm::ConstantPointerNull::get(
212193326Sed    llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
213193326Sed  // C string type.  Used in lots of places.
214193326Sed  PtrToInt8Ty =
215193326Sed    llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
216193326Sed  // Get the selector Type.
217193326Sed  SelectorTy = cast<llvm::PointerType>(
218193326Sed    CGM.getTypes().ConvertType(CGM.getContext().getObjCSelType()));
219193326Sed
220193326Sed  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
221193326Sed  PtrTy = PtrToInt8Ty;
222193326Sed
223193326Sed  // Object type
224193326Sed  IdTy = cast<llvm::PointerType>(
225193326Sed		  CGM.getTypes().ConvertType(CGM.getContext().getObjCIdType()));
226193326Sed
227193326Sed  // IMP type
228193326Sed  std::vector<const llvm::Type*> IMPArgs;
229193326Sed  IMPArgs.push_back(IdTy);
230193326Sed  IMPArgs.push_back(SelectorTy);
231193326Sed  IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
232193326Sed}
233193326Sed// This has to perform the lookup every time, since posing and related
234193326Sed// techniques can modify the name -> class mapping.
235193326Sedllvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
236193326Sed                                 const ObjCInterfaceDecl *OID) {
237193326Sed  llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
238194613Sed  EmitClassRef(OID->getNameAsString());
239193326Sed  ClassName = Builder.CreateStructGEP(ClassName, 0);
240193326Sed
241193326Sed  std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
242193326Sed  llvm::Constant *ClassLookupFn =
243193326Sed    CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
244193326Sed                                                      Params,
245193326Sed                                                      true),
246193326Sed                              "objc_lookup_class");
247193326Sed  return Builder.CreateCall(ClassLookupFn, ClassName);
248193326Sed}
249193326Sed
250193326Sedllvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
251193326Sed  llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
252193326Sed  if (US == 0)
253193326Sed    US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
254193326Sed                               llvm::GlobalValue::InternalLinkage,
255193326Sed                               ".objc_untyped_selector_alias",
256193326Sed                               NULL, &TheModule);
257193326Sed
258193326Sed  return Builder.CreateLoad(US);
259193326Sed}
260193326Sed
261193326Sedllvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
262193326Sed    *Method) {
263193326Sed
264193326Sed  std::string SelName = Method->getSelector().getAsString();
265193326Sed  std::string SelTypes;
266193326Sed  CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
267193326Sed  // Typed selectors
268193326Sed  TypedSelector Selector = TypedSelector(SelName,
269193326Sed          SelTypes);
270193326Sed
271193326Sed  // If it's already cached, return it.
272193326Sed  if (TypedSelectors[Selector])
273193326Sed  {
274193326Sed      return Builder.CreateLoad(TypedSelectors[Selector]);
275193326Sed  }
276193326Sed
277193326Sed  // If it isn't, cache it.
278193326Sed  llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
279193326Sed          llvm::PointerType::getUnqual(SelectorTy),
280193326Sed          llvm::GlobalValue::InternalLinkage, SelName,
281193326Sed          NULL, &TheModule);
282193326Sed  TypedSelectors[Selector] = Sel;
283193326Sed
284193326Sed  return Builder.CreateLoad(Sel);
285193326Sed}
286193326Sed
287193326Sedllvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
288193326Sed                                              const std::string &Name) {
289193326Sed  llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
290193326Sed  ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
291193326Sed                               llvm::GlobalValue::InternalLinkage,
292193326Sed                               ConstStr, Name, &TheModule);
293193326Sed  return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
294193326Sed}
295193326Sedllvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
296193326Sed    std::vector<llvm::Constant*> &V, const std::string &Name) {
297193326Sed  llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
298193326Sed  return new llvm::GlobalVariable(Ty, false,
299193326Sed      llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
300193326Sed}
301193326Sedllvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
302193326Sed    std::vector<llvm::Constant*> &V, const std::string &Name) {
303193326Sed  llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
304193326Sed  return new llvm::GlobalVariable(Ty, false,
305193326Sed      llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
306193326Sed}
307193326Sed
308193326Sed/// Generate an NSConstantString object.
309193326Sed//TODO: In case there are any crazy people still using the GNU runtime without
310193326Sed//an OpenStep implementation, this should let them select their own class for
311193326Sed//constant strings.
312193326Sedllvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) {
313193326Sed  std::string Str(SL->getString()->getStrData(),
314193326Sed                  SL->getString()->getByteLength());
315193326Sed  std::vector<llvm::Constant*> Ivars;
316193326Sed  Ivars.push_back(NULLPtr);
317193326Sed  Ivars.push_back(MakeConstantString(Str));
318193326Sed  Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
319193326Sed  llvm::Constant *ObjCStr = MakeGlobal(
320193326Sed    llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
321193326Sed    Ivars, ".objc_str");
322193326Sed  ConstantStrings.push_back(
323193326Sed      llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
324193326Sed  return ObjCStr;
325193326Sed}
326193326Sed
327193326Sed///Generates a message send where the super is the receiver.  This is a message
328193326Sed///send to self with special delivery semantics indicating which class's method
329193326Sed///should be called.
330193326SedCodeGen::RValue
331193326SedCGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
332193326Sed                                    QualType ResultType,
333193326Sed                                    Selector Sel,
334193326Sed                                    const ObjCInterfaceDecl *Class,
335193326Sed                                    bool isCategoryImpl,
336193326Sed                                    llvm::Value *Receiver,
337193326Sed                                    bool IsClassMessage,
338193326Sed                                    const CallArgList &CallArgs) {
339193326Sed  llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
340193326Sed
341193326Sed  CallArgList ActualArgs;
342193326Sed
343193326Sed  ActualArgs.push_back(
344193326Sed	  std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
345193326Sed	  CGF.getContext().getObjCIdType()));
346193326Sed  ActualArgs.push_back(std::make_pair(RValue::get(cmd),
347193326Sed                                      CGF.getContext().getObjCSelType()));
348193326Sed  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
349193326Sed
350193326Sed  CodeGenTypes &Types = CGM.getTypes();
351193326Sed  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
352193326Sed  const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
353193326Sed
354193326Sed  llvm::Value *ReceiverClass = 0;
355193326Sed  if (isCategoryImpl) {
356193326Sed    llvm::Constant *classLookupFunction = 0;
357193326Sed    std::vector<const llvm::Type*> Params;
358193326Sed    Params.push_back(PtrTy);
359193326Sed    if (IsClassMessage)  {
360193326Sed      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
361193326Sed            IdTy, Params, true), "objc_get_meta_class");
362193326Sed    } else {
363193326Sed      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
364193326Sed            IdTy, Params, true), "objc_get_class");
365193326Sed    }
366193326Sed    ReceiverClass = CGF.Builder.CreateCall(classLookupFunction,
367193326Sed        MakeConstantString(Class->getNameAsString()));
368193326Sed  } else {
369193326Sed    // Set up global aliases for the metaclass or class pointer if they do not
370193326Sed    // already exist.  These will are forward-references which will be set to
371193326Sed    // pointers to the class and metaclass structure created for the runtime load
372193326Sed    // function.  To send a message to super, we look up the value of the
373193326Sed    // super_class pointer from either the class or metaclass structure.
374193326Sed    if (IsClassMessage)  {
375193326Sed      if (!MetaClassPtrAlias) {
376193326Sed        MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
377193326Sed            llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
378193326Sed            Class->getNameAsString(), NULL, &TheModule);
379193326Sed      }
380193326Sed      ReceiverClass = MetaClassPtrAlias;
381193326Sed    } else {
382193326Sed      if (!ClassPtrAlias) {
383193326Sed        ClassPtrAlias = new llvm::GlobalAlias(IdTy,
384193326Sed            llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
385193326Sed            Class->getNameAsString(), NULL, &TheModule);
386193326Sed      }
387193326Sed      ReceiverClass = ClassPtrAlias;
388193326Sed    }
389193326Sed  }
390193326Sed  // Cast the pointer to a simplified version of the class structure
391193326Sed  ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass,
392193326Sed      llvm::PointerType::getUnqual(llvm::StructType::get(IdTy, IdTy, NULL)));
393193326Sed  // Get the superclass pointer
394193326Sed  ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1);
395193326Sed  // Load the superclass pointer
396193326Sed  ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass);
397193326Sed  // Construct the structure used to look up the IMP
398193326Sed  llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
399193326Sed      IdTy, NULL);
400193326Sed  llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
401193326Sed
402193326Sed  CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
403193326Sed  CGF.Builder.CreateStore(ReceiverClass,
404193326Sed      CGF.Builder.CreateStructGEP(ObjCSuper, 1));
405193326Sed
406193326Sed  // Get the IMP
407193326Sed  std::vector<const llvm::Type*> Params;
408193326Sed  Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
409193326Sed  Params.push_back(SelectorTy);
410193326Sed  llvm::Constant *lookupFunction =
411193326Sed    CGM.CreateRuntimeFunction(llvm::FunctionType::get(
412193326Sed          llvm::PointerType::getUnqual(impType), Params, true),
413193326Sed        "objc_msg_lookup_super");
414193326Sed
415193326Sed  llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
416193326Sed  llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
417193326Sed      lookupArgs+2);
418193326Sed
419193326Sed  return CGF.EmitCall(FnInfo, imp, ActualArgs);
420193326Sed}
421193326Sed
422193326Sed/// Generate code for a message send expression.
423193326SedCodeGen::RValue
424193326SedCGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
425193326Sed                               QualType ResultType,
426193326Sed                               Selector Sel,
427193326Sed                               llvm::Value *Receiver,
428193326Sed                               bool IsClassMessage,
429193326Sed                               const CallArgList &CallArgs,
430193326Sed                               const ObjCMethodDecl *Method) {
431193326Sed  llvm::Value *cmd;
432193326Sed  if (Method)
433193326Sed    cmd = GetSelector(CGF.Builder, Method);
434193326Sed  else
435193326Sed    cmd = GetSelector(CGF.Builder, Sel);
436193326Sed  CallArgList ActualArgs;
437193326Sed
438193326Sed  ActualArgs.push_back(
439193326Sed    std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
440193326Sed    CGF.getContext().getObjCIdType()));
441193326Sed  ActualArgs.push_back(std::make_pair(RValue::get(cmd),
442193326Sed                                      CGF.getContext().getObjCSelType()));
443193326Sed  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
444193326Sed
445193326Sed  CodeGenTypes &Types = CGM.getTypes();
446193326Sed  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
447193326Sed  const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
448193326Sed
449193326Sed  llvm::Value *imp;
450193326Sed  std::vector<const llvm::Type*> Params;
451193326Sed  Params.push_back(Receiver->getType());
452193326Sed  Params.push_back(SelectorTy);
453193326Sed  // For sender-aware dispatch, we pass the sender as the third argument to a
454193326Sed  // lookup function.  When sending messages from C code, the sender is nil.
455193326Sed  // objc_msg_lookup_sender(id receiver, SEL selector, id sender);
456193326Sed  if (CGM.getContext().getLangOptions().ObjCSenderDispatch) {
457193326Sed    llvm::Value *self;
458193326Sed
459193326Sed    if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
460193326Sed      self = CGF.LoadObjCSelf();
461193326Sed    } else {
462193326Sed      self = llvm::ConstantPointerNull::get(IdTy);
463193326Sed    }
464193326Sed    Params.push_back(self->getType());
465193326Sed    llvm::Constant *lookupFunction =
466193326Sed      CGM.CreateRuntimeFunction(llvm::FunctionType::get(
467193326Sed          llvm::PointerType::getUnqual(impType), Params, true),
468193326Sed        "objc_msg_lookup_sender");
469193326Sed
470193326Sed    imp = CGF.Builder.CreateCall3(lookupFunction, Receiver, cmd, self);
471193326Sed  } else {
472193326Sed    llvm::Constant *lookupFunction =
473193326Sed    CGM.CreateRuntimeFunction(llvm::FunctionType::get(
474193326Sed        llvm::PointerType::getUnqual(impType), Params, true),
475193326Sed      "objc_msg_lookup");
476193326Sed
477193326Sed    imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
478193326Sed  }
479193326Sed
480193326Sed  return CGF.EmitCall(FnInfo, imp, ActualArgs);
481193326Sed}
482193326Sed
483193326Sed/// Generates a MethodList.  Used in construction of a objc_class and
484193326Sed/// objc_category structures.
485193326Sedllvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
486193326Sed                                              const std::string &CategoryName,
487193326Sed    const llvm::SmallVectorImpl<Selector> &MethodSels,
488193326Sed    const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
489193326Sed    bool isClassMethodList) {
490193326Sed  // Get the method structure type.
491193326Sed  llvm::StructType *ObjCMethodTy = llvm::StructType::get(
492193326Sed    PtrToInt8Ty, // Really a selector, but the runtime creates it us.
493193326Sed    PtrToInt8Ty, // Method types
494193326Sed    llvm::PointerType::getUnqual(IMPTy), //Method pointer
495193326Sed    NULL);
496193326Sed  std::vector<llvm::Constant*> Methods;
497193326Sed  std::vector<llvm::Constant*> Elements;
498193326Sed  for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
499193326Sed    Elements.clear();
500193326Sed    if (llvm::Constant *Method =
501193326Sed      TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
502193326Sed                                                MethodSels[i].getAsString(),
503193326Sed                                                isClassMethodList))) {
504193326Sed      llvm::Constant *C =
505193326Sed        CGM.GetAddrOfConstantCString(MethodSels[i].getAsString());
506193326Sed      Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
507193326Sed      Elements.push_back(
508193326Sed            llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
509193326Sed      Method = llvm::ConstantExpr::getBitCast(Method,
510193326Sed          llvm::PointerType::getUnqual(IMPTy));
511193326Sed      Elements.push_back(Method);
512193326Sed      Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
513193326Sed    }
514193326Sed  }
515193326Sed
516193326Sed  // Array of method structures
517193326Sed  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
518193326Sed                                                            Methods.size());
519193326Sed  llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
520193326Sed                                                         Methods);
521193326Sed
522193326Sed  // Structure containing list pointer, array and array count
523193326Sed  llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
524193326Sed  llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
525193326Sed  llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
526193326Sed  llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
527193326Sed      IntTy,
528193326Sed      ObjCMethodArrayTy,
529193326Sed      NULL);
530193326Sed  // Refine next pointer type to concrete type
531193326Sed  llvm::cast<llvm::OpaqueType>(
532193326Sed      OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
533193326Sed  ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
534193326Sed
535193326Sed  Methods.clear();
536193326Sed  Methods.push_back(llvm::ConstantPointerNull::get(
537193326Sed        llvm::PointerType::getUnqual(ObjCMethodListTy)));
538193326Sed  Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
539193326Sed        MethodTypes.size()));
540193326Sed  Methods.push_back(MethodArray);
541193326Sed
542193326Sed  // Create an instance of the structure
543193326Sed  return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
544193326Sed}
545193326Sed
546193326Sed/// Generates an IvarList.  Used in construction of a objc_class.
547193326Sedllvm::Constant *CGObjCGNU::GenerateIvarList(
548193326Sed    const llvm::SmallVectorImpl<llvm::Constant *>  &IvarNames,
549193326Sed    const llvm::SmallVectorImpl<llvm::Constant *>  &IvarTypes,
550193326Sed    const llvm::SmallVectorImpl<llvm::Constant *>  &IvarOffsets) {
551193326Sed  // Get the method structure type.
552193326Sed  llvm::StructType *ObjCIvarTy = llvm::StructType::get(
553193326Sed    PtrToInt8Ty,
554193326Sed    PtrToInt8Ty,
555193326Sed    IntTy,
556193326Sed    NULL);
557193326Sed  std::vector<llvm::Constant*> Ivars;
558193326Sed  std::vector<llvm::Constant*> Elements;
559193326Sed  for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
560193326Sed    Elements.clear();
561193326Sed    Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
562193326Sed          Zeros, 2));
563193326Sed    Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
564193326Sed          Zeros, 2));
565193326Sed    Elements.push_back(IvarOffsets[i]);
566193326Sed    Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
567193326Sed  }
568193326Sed
569193326Sed  // Array of method structures
570193326Sed  llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
571193326Sed      IvarNames.size());
572193326Sed
573193326Sed
574193326Sed  Elements.clear();
575193326Sed  Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
576193326Sed  Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
577193326Sed  // Structure containing array and array count
578193326Sed  llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
579193326Sed    ObjCIvarArrayTy,
580193326Sed    NULL);
581193326Sed
582193326Sed  // Create an instance of the structure
583193326Sed  return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
584193326Sed}
585193326Sed
586193326Sed/// Generate a class structure
587193326Sedllvm::Constant *CGObjCGNU::GenerateClassStructure(
588193326Sed    llvm::Constant *MetaClass,
589193326Sed    llvm::Constant *SuperClass,
590193326Sed    unsigned info,
591193326Sed    const char *Name,
592193326Sed    llvm::Constant *Version,
593193326Sed    llvm::Constant *InstanceSize,
594193326Sed    llvm::Constant *IVars,
595193326Sed    llvm::Constant *Methods,
596193326Sed    llvm::Constant *Protocols) {
597193326Sed  // Set up the class structure
598193326Sed  // Note:  Several of these are char*s when they should be ids.  This is
599193326Sed  // because the runtime performs this translation on load.
600193326Sed  llvm::StructType *ClassTy = llvm::StructType::get(
601193326Sed      PtrToInt8Ty,        // class_pointer
602193326Sed      PtrToInt8Ty,        // super_class
603193326Sed      PtrToInt8Ty,        // name
604193326Sed      LongTy,             // version
605193326Sed      LongTy,             // info
606193326Sed      LongTy,             // instance_size
607193326Sed      IVars->getType(),   // ivars
608193326Sed      Methods->getType(), // methods
609193326Sed      // These are all filled in by the runtime, so we pretend
610193326Sed      PtrTy,              // dtable
611193326Sed      PtrTy,              // subclass_list
612193326Sed      PtrTy,              // sibling_class
613193326Sed      PtrTy,              // protocols
614193326Sed      PtrTy,              // gc_object_type
615193326Sed      NULL);
616193326Sed  llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
617193326Sed  llvm::Constant *NullP =
618193326Sed    llvm::ConstantPointerNull::get(PtrTy);
619193326Sed  // Fill in the structure
620193326Sed  std::vector<llvm::Constant*> Elements;
621193326Sed  Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
622193326Sed  Elements.push_back(SuperClass);
623193326Sed  Elements.push_back(MakeConstantString(Name, ".class_name"));
624193326Sed  Elements.push_back(Zero);
625193326Sed  Elements.push_back(llvm::ConstantInt::get(LongTy, info));
626193326Sed  Elements.push_back(InstanceSize);
627193326Sed  Elements.push_back(IVars);
628193326Sed  Elements.push_back(Methods);
629193326Sed  Elements.push_back(NullP);
630193326Sed  Elements.push_back(NullP);
631193326Sed  Elements.push_back(NullP);
632193326Sed  Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
633193326Sed  Elements.push_back(NullP);
634193326Sed  // Create an instance of the structure
635193326Sed  return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
636193326Sed}
637193326Sed
638193326Sedllvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
639193326Sed    const llvm::SmallVectorImpl<llvm::Constant *>  &MethodNames,
640193326Sed    const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes) {
641193326Sed  // Get the method structure type.
642193326Sed  llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
643193326Sed    PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
644193326Sed    PtrToInt8Ty,
645193326Sed    NULL);
646193326Sed  std::vector<llvm::Constant*> Methods;
647193326Sed  std::vector<llvm::Constant*> Elements;
648193326Sed  for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
649193326Sed    Elements.clear();
650193326Sed    Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
651193326Sed          Zeros, 2));
652193326Sed    Elements.push_back(
653193326Sed          llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
654193326Sed    Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
655193326Sed  }
656193326Sed  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
657193326Sed      MethodNames.size());
658193326Sed  llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
659193326Sed  llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
660193326Sed      IntTy, ObjCMethodArrayTy, NULL);
661193326Sed  Methods.clear();
662193326Sed  Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
663193326Sed  Methods.push_back(Array);
664193326Sed  return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
665193326Sed}
666193326Sed// Create the protocol list structure used in classes, categories and so on
667193326Sedllvm::Constant *CGObjCGNU::GenerateProtocolList(
668193326Sed    const llvm::SmallVectorImpl<std::string> &Protocols) {
669193326Sed  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
670193326Sed      Protocols.size());
671193326Sed  llvm::StructType *ProtocolListTy = llvm::StructType::get(
672193326Sed      PtrTy, //Should be a recurisve pointer, but it's always NULL here.
673193326Sed      LongTy,//FIXME: Should be size_t
674193326Sed      ProtocolArrayTy,
675193326Sed      NULL);
676193326Sed  std::vector<llvm::Constant*> Elements;
677193326Sed  for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
678193326Sed      iter != endIter ; iter++) {
679193326Sed    llvm::Constant *protocol = ExistingProtocols[*iter];
680193326Sed    if (!protocol)
681193326Sed      protocol = GenerateEmptyProtocol(*iter);
682193326Sed    llvm::Constant *Ptr =
683193326Sed      llvm::ConstantExpr::getBitCast(protocol, PtrToInt8Ty);
684193326Sed    Elements.push_back(Ptr);
685193326Sed  }
686193326Sed  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
687193326Sed      Elements);
688193326Sed  Elements.clear();
689193326Sed  Elements.push_back(NULLPtr);
690193326Sed  Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
691193326Sed  Elements.push_back(ProtocolArray);
692193326Sed  return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
693193326Sed}
694193326Sed
695193326Sedllvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
696193326Sed                                            const ObjCProtocolDecl *PD) {
697193326Sed  llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
698193326Sed  const llvm::Type *T =
699193326Sed    CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
700193326Sed  return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
701193326Sed}
702193326Sed
703193326Sedllvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
704193326Sed  const std::string &ProtocolName) {
705193326Sed  llvm::SmallVector<std::string, 0> EmptyStringVector;
706193326Sed  llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
707193326Sed
708193326Sed  llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
709193326Sed  llvm::Constant *InstanceMethodList =
710193326Sed    GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
711193326Sed  llvm::Constant *ClassMethodList =
712193326Sed    GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
713193326Sed  // Protocols are objects containing lists of the methods implemented and
714193326Sed  // protocols adopted.
715193326Sed  llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
716193326Sed      PtrToInt8Ty,
717193326Sed      ProtocolList->getType(),
718193326Sed      InstanceMethodList->getType(),
719193326Sed      ClassMethodList->getType(),
720193326Sed      NULL);
721193326Sed  std::vector<llvm::Constant*> Elements;
722193326Sed  // The isa pointer must be set to a magic number so the runtime knows it's
723193326Sed  // the correct layout.
724193326Sed  Elements.push_back(llvm::ConstantExpr::getIntToPtr(
725193326Sed        llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
726193326Sed  Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
727193326Sed  Elements.push_back(ProtocolList);
728193326Sed  Elements.push_back(InstanceMethodList);
729193326Sed  Elements.push_back(ClassMethodList);
730193326Sed  return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
731193326Sed}
732193326Sed
733193326Sedvoid CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
734193326Sed  ASTContext &Context = CGM.getContext();
735193326Sed  std::string ProtocolName = PD->getNameAsString();
736193326Sed  llvm::SmallVector<std::string, 16> Protocols;
737193326Sed  for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
738193326Sed       E = PD->protocol_end(); PI != E; ++PI)
739193326Sed    Protocols.push_back((*PI)->getNameAsString());
740193326Sed  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
741193326Sed  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
742193326Sed  for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(Context),
743193326Sed       E = PD->instmeth_end(Context); iter != E; iter++) {
744193326Sed    std::string TypeStr;
745193326Sed    Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
746193326Sed    InstanceMethodNames.push_back(
747193326Sed        CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
748193326Sed    InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
749193326Sed  }
750193326Sed  // Collect information about class methods:
751193326Sed  llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
752193326Sed  llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
753193326Sed  for (ObjCProtocolDecl::classmeth_iterator
754193326Sed         iter = PD->classmeth_begin(Context),
755193326Sed         endIter = PD->classmeth_end(Context) ; iter != endIter ; iter++) {
756193326Sed    std::string TypeStr;
757193326Sed    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
758193326Sed    ClassMethodNames.push_back(
759193326Sed        CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
760193326Sed    ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
761193326Sed  }
762193326Sed
763193326Sed  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
764193326Sed  llvm::Constant *InstanceMethodList =
765193326Sed    GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
766193326Sed  llvm::Constant *ClassMethodList =
767193326Sed    GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
768193326Sed  // Protocols are objects containing lists of the methods implemented and
769193326Sed  // protocols adopted.
770193326Sed  llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
771193326Sed      PtrToInt8Ty,
772193326Sed      ProtocolList->getType(),
773193326Sed      InstanceMethodList->getType(),
774193326Sed      ClassMethodList->getType(),
775193326Sed      NULL);
776193326Sed  std::vector<llvm::Constant*> Elements;
777193326Sed  // The isa pointer must be set to a magic number so the runtime knows it's
778193326Sed  // the correct layout.
779193326Sed  Elements.push_back(llvm::ConstantExpr::getIntToPtr(
780193326Sed        llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
781193326Sed  Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
782193326Sed  Elements.push_back(ProtocolList);
783193326Sed  Elements.push_back(InstanceMethodList);
784193326Sed  Elements.push_back(ClassMethodList);
785193326Sed  ExistingProtocols[ProtocolName] =
786193326Sed    llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
787193326Sed          ".objc_protocol"), IdTy);
788193326Sed}
789193326Sed
790193326Sedvoid CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
791193326Sed  std::string ClassName = OCD->getClassInterface()->getNameAsString();
792193326Sed  std::string CategoryName = OCD->getNameAsString();
793193326Sed  // Collect information about instance methods
794193326Sed  llvm::SmallVector<Selector, 16> InstanceMethodSels;
795193326Sed  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
796193326Sed  for (ObjCCategoryImplDecl::instmeth_iterator
797193326Sed         iter = OCD->instmeth_begin(CGM.getContext()),
798193326Sed         endIter = OCD->instmeth_end(CGM.getContext());
799193326Sed       iter != endIter ; iter++) {
800193326Sed    InstanceMethodSels.push_back((*iter)->getSelector());
801193326Sed    std::string TypeStr;
802193326Sed    CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
803193326Sed    InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
804193326Sed  }
805193326Sed
806193326Sed  // Collect information about class methods
807193326Sed  llvm::SmallVector<Selector, 16> ClassMethodSels;
808193326Sed  llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
809193326Sed  for (ObjCCategoryImplDecl::classmeth_iterator
810193326Sed         iter = OCD->classmeth_begin(CGM.getContext()),
811193326Sed         endIter = OCD->classmeth_end(CGM.getContext());
812193326Sed       iter != endIter ; iter++) {
813193326Sed    ClassMethodSels.push_back((*iter)->getSelector());
814193326Sed    std::string TypeStr;
815193326Sed    CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
816193326Sed    ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
817193326Sed  }
818193326Sed
819193326Sed  // Collect the names of referenced protocols
820193326Sed  llvm::SmallVector<std::string, 16> Protocols;
821193326Sed  const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
822193326Sed  const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
823193326Sed  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
824193326Sed       E = Protos.end(); I != E; ++I)
825193326Sed    Protocols.push_back((*I)->getNameAsString());
826193326Sed
827193326Sed  std::vector<llvm::Constant*> Elements;
828193326Sed  Elements.push_back(MakeConstantString(CategoryName));
829193326Sed  Elements.push_back(MakeConstantString(ClassName));
830193326Sed  // Instance method list
831193326Sed  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
832193326Sed          ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
833193326Sed          false), PtrTy));
834193326Sed  // Class method list
835193326Sed  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
836193326Sed          ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
837193326Sed        PtrTy));
838193326Sed  // Protocol list
839193326Sed  Elements.push_back(llvm::ConstantExpr::getBitCast(
840193326Sed        GenerateProtocolList(Protocols), PtrTy));
841193326Sed  Categories.push_back(llvm::ConstantExpr::getBitCast(
842193326Sed        MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
843193326Sed            PtrTy, PtrTy, NULL), Elements), PtrTy));
844193326Sed}
845193326Sed
846193326Sedvoid CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
847193326Sed  ASTContext &Context = CGM.getContext();
848193326Sed
849193326Sed  // Get the superclass name.
850193326Sed  const ObjCInterfaceDecl * SuperClassDecl =
851193326Sed    OID->getClassInterface()->getSuperClass();
852193326Sed  std::string SuperClassName;
853194613Sed  if (SuperClassDecl) {
854193326Sed    SuperClassName = SuperClassDecl->getNameAsString();
855194613Sed    EmitClassRef(SuperClassName);
856194613Sed  }
857193326Sed
858193326Sed  // Get the class name
859193326Sed  ObjCInterfaceDecl *ClassDecl =
860193326Sed    const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
861193326Sed  std::string ClassName = ClassDecl->getNameAsString();
862194613Sed  // Emit the symbol that is used to generate linker errors if this class is
863194613Sed  // referenced in other modules but not declared.
864194613Sed  new llvm::GlobalVariable(LongTy, false, llvm::GlobalValue::ExternalLinkage,
865194613Sed    llvm::ConstantInt::get(LongTy, 0), "__objc_class_name_" + ClassName,
866194613Sed    &TheModule);
867194613Sed
868193326Sed  // Get the size of instances.
869193326Sed  int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
870193326Sed
871193326Sed  // Collect information about instance variables.
872193326Sed  llvm::SmallVector<llvm::Constant*, 16> IvarNames;
873193326Sed  llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
874193326Sed  llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
875193326Sed
876193326Sed  int superInstanceSize = !SuperClassDecl ? 0 :
877193326Sed    Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
878193326Sed  // For non-fragile ivars, set the instance size to 0 - {the size of just this
879193326Sed  // class}.  The runtime will then set this to the correct value on load.
880193326Sed  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
881193326Sed    instanceSize = 0 - (instanceSize - superInstanceSize);
882193326Sed  }
883193326Sed  for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
884193326Sed      endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
885193326Sed      // Store the name
886193326Sed      IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)
887193326Sed                                                         ->getNameAsString()));
888193326Sed      // Get the type encoding for this ivar
889193326Sed      std::string TypeStr;
890193326Sed      Context.getObjCEncodingForType((*iter)->getType(), TypeStr);
891193326Sed      IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
892193326Sed      // Get the offset
893193326Sed      uint64_t Offset;
894193326Sed      if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
895193326Sed		Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter) -
896193326Sed			superInstanceSize;
897193326Sed        ObjCIvarOffsetVariable(ClassDecl, *iter);
898193326Sed      } else {
899193326Sed        Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter);
900193326Sed      }
901193326Sed      IvarOffsets.push_back(
902193326Sed          llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset));
903193326Sed  }
904193326Sed
905193326Sed  // Collect information about instance methods
906193326Sed  llvm::SmallVector<Selector, 16> InstanceMethodSels;
907193326Sed  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
908193326Sed  for (ObjCImplementationDecl::instmeth_iterator
909193326Sed         iter = OID->instmeth_begin(CGM.getContext()),
910193326Sed         endIter = OID->instmeth_end(CGM.getContext());
911193326Sed       iter != endIter ; iter++) {
912193326Sed    InstanceMethodSels.push_back((*iter)->getSelector());
913193326Sed    std::string TypeStr;
914193326Sed    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
915193326Sed    InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
916193326Sed  }
917193326Sed  for (ObjCImplDecl::propimpl_iterator
918193326Sed         iter = OID->propimpl_begin(CGM.getContext()),
919193326Sed         endIter = OID->propimpl_end(CGM.getContext());
920193326Sed       iter != endIter ; iter++) {
921193326Sed    ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
922193326Sed    if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
923193326Sed      InstanceMethodSels.push_back(getter->getSelector());
924193326Sed      std::string TypeStr;
925193326Sed      Context.getObjCEncodingForMethodDecl(getter,TypeStr);
926193326Sed      InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
927193326Sed    }
928193326Sed    if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
929193326Sed      InstanceMethodSels.push_back(setter->getSelector());
930193326Sed      std::string TypeStr;
931193326Sed      Context.getObjCEncodingForMethodDecl(setter,TypeStr);
932193326Sed      InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
933193326Sed    }
934193326Sed  }
935193326Sed
936193326Sed  // Collect information about class methods
937193326Sed  llvm::SmallVector<Selector, 16> ClassMethodSels;
938193326Sed  llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
939193326Sed  for (ObjCImplementationDecl::classmeth_iterator
940193326Sed         iter = OID->classmeth_begin(CGM.getContext()),
941193326Sed         endIter = OID->classmeth_end(CGM.getContext());
942193326Sed       iter != endIter ; iter++) {
943193326Sed    ClassMethodSels.push_back((*iter)->getSelector());
944193326Sed    std::string TypeStr;
945193326Sed    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
946193326Sed    ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
947193326Sed  }
948193326Sed  // Collect the names of referenced protocols
949193326Sed  llvm::SmallVector<std::string, 16> Protocols;
950193326Sed  const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
951193326Sed  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
952193326Sed       E = Protos.end(); I != E; ++I)
953193326Sed    Protocols.push_back((*I)->getNameAsString());
954193326Sed
955193326Sed
956193326Sed
957193326Sed  // Get the superclass pointer.
958193326Sed  llvm::Constant *SuperClass;
959193326Sed  if (!SuperClassName.empty()) {
960193326Sed    SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
961193326Sed  } else {
962193326Sed    SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
963193326Sed  }
964193326Sed  // Empty vector used to construct empty method lists
965193326Sed  llvm::SmallVector<llvm::Constant*, 1>  empty;
966193326Sed  // Generate the method and instance variable lists
967193326Sed  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
968193326Sed      InstanceMethodSels, InstanceMethodTypes, false);
969193326Sed  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
970193326Sed      ClassMethodSels, ClassMethodTypes, true);
971193326Sed  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
972193326Sed      IvarOffsets);
973193326Sed  //Generate metaclass for class methods
974193326Sed  llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
975193326Sed      NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
976193326Sed        empty, empty, empty), ClassMethodList, NULLPtr);
977193326Sed
978193326Sed  // Generate the class structure
979193326Sed  llvm::Constant *ClassStruct =
980193326Sed    GenerateClassStructure(MetaClassStruct, SuperClass, 0x1L,
981193326Sed                           ClassName.c_str(), 0,
982193326Sed      llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
983193326Sed      MethodList, GenerateProtocolList(Protocols));
984193326Sed
985193326Sed  // Resolve the class aliases, if they exist.
986193326Sed  if (ClassPtrAlias) {
987193326Sed    ClassPtrAlias->setAliasee(
988193326Sed        llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
989193326Sed    ClassPtrAlias = 0;
990193326Sed  }
991193326Sed  if (MetaClassPtrAlias) {
992193326Sed    MetaClassPtrAlias->setAliasee(
993193326Sed        llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
994193326Sed    MetaClassPtrAlias = 0;
995193326Sed  }
996193326Sed
997193326Sed  // Add class structure to list to be added to the symtab later
998193326Sed  ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
999193326Sed  Classes.push_back(ClassStruct);
1000193326Sed}
1001193326Sed
1002195099Sedvoid CGObjCGNU::MergeMetadataGlobals(
1003195099Sed                          std::vector<llvm::Constant*> &UsedArray) {
1004195099Sed}
1005195099Sed
1006193326Sedllvm::Function *CGObjCGNU::ModuleInitFunction() {
1007193326Sed  // Only emit an ObjC load function if no Objective-C stuff has been called
1008193326Sed  if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1009193326Sed      ExistingProtocols.empty() && TypedSelectors.empty() &&
1010193326Sed      UntypedSelectors.empty())
1011193326Sed    return NULL;
1012193326Sed
1013193326Sed  const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1014193326Sed          SelectorTy->getElementType());
1015193326Sed  const llvm::Type *SelStructPtrTy = SelectorTy;
1016193326Sed  bool isSelOpaque = false;
1017193326Sed  if (SelStructTy == 0) {
1018193326Sed    SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
1019193326Sed    SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
1020193326Sed    isSelOpaque = true;
1021193326Sed  }
1022193326Sed
1023193326Sed  // Name the ObjC types to make the IR a bit easier to read
1024193326Sed  TheModule.addTypeName(".objc_selector", SelStructPtrTy);
1025193326Sed  TheModule.addTypeName(".objc_id", IdTy);
1026193326Sed  TheModule.addTypeName(".objc_imp", IMPTy);
1027193326Sed
1028193326Sed  std::vector<llvm::Constant*> Elements;
1029193326Sed  llvm::Constant *Statics = NULLPtr;
1030193326Sed  // Generate statics list:
1031193326Sed  if (ConstantStrings.size()) {
1032193326Sed    llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1033193326Sed        ConstantStrings.size() + 1);
1034193326Sed    ConstantStrings.push_back(NULLPtr);
1035193326Sed    Elements.push_back(MakeConstantString("NSConstantString",
1036193326Sed          ".objc_static_class_name"));
1037193326Sed    Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
1038193326Sed       ConstantStrings));
1039193326Sed    llvm::StructType *StaticsListTy =
1040193326Sed      llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
1041193326Sed    llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
1042193326Sed    Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
1043193326Sed    llvm::ArrayType *StaticsListArrayTy =
1044193326Sed      llvm::ArrayType::get(StaticsListPtrTy, 2);
1045193326Sed    Elements.clear();
1046193326Sed    Elements.push_back(Statics);
1047193326Sed    Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
1048193326Sed    Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
1049193326Sed    Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
1050193326Sed  }
1051193326Sed  // Array of classes, categories, and constant objects
1052193326Sed  llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
1053193326Sed      Classes.size() + Categories.size()  + 2);
1054193326Sed  llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
1055193326Sed                                                     llvm::Type::Int16Ty,
1056193326Sed                                                     llvm::Type::Int16Ty,
1057193326Sed                                                     ClassListTy, NULL);
1058193326Sed
1059193326Sed  Elements.clear();
1060193326Sed  // Pointer to an array of selectors used in this module.
1061193326Sed  std::vector<llvm::Constant*> Selectors;
1062193326Sed  for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1063193326Sed     iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1064193326Sed     iter != iterEnd ; ++iter) {
1065193326Sed    Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
1066193326Sed    Elements.push_back(MakeConstantString(iter->first.second,
1067193326Sed                                          ".objc_sel_types"));
1068193326Sed    Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1069193326Sed    Elements.clear();
1070193326Sed  }
1071193326Sed  for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1072193326Sed      iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1073193326Sed      iter != iterEnd; ++iter) {
1074193326Sed    Elements.push_back(
1075193326Sed        MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
1076193326Sed    Elements.push_back(NULLPtr);
1077193326Sed    Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1078193326Sed    Elements.clear();
1079193326Sed  }
1080193326Sed  Elements.push_back(NULLPtr);
1081193326Sed  Elements.push_back(NULLPtr);
1082193326Sed  Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1083193326Sed  Elements.clear();
1084193326Sed  // Number of static selectors
1085193326Sed  Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
1086193326Sed  llvm::Constant *SelectorList = MakeGlobal(
1087193326Sed          llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
1088193326Sed          ".objc_selector_list");
1089193326Sed  Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
1090193326Sed    SelStructPtrTy));
1091193326Sed
1092193326Sed  // Now that all of the static selectors exist, create pointers to them.
1093193326Sed  int index = 0;
1094193326Sed  for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1095193326Sed     iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1096193326Sed     iter != iterEnd; ++iter) {
1097193326Sed    llvm::Constant *Idxs[] = {Zeros[0],
1098193326Sed      llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
1099193326Sed    llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy,
1100193326Sed        true, llvm::GlobalValue::InternalLinkage,
1101193326Sed        llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1102193326Sed        ".objc_sel_ptr", &TheModule);
1103193326Sed    // If selectors are defined as an opaque type, cast the pointer to this
1104193326Sed    // type.
1105193326Sed    if (isSelOpaque) {
1106193326Sed      SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1107193326Sed        llvm::PointerType::getUnqual(SelectorTy));
1108193326Sed    }
1109193326Sed    (*iter).second->setAliasee(SelPtr);
1110193326Sed  }
1111193326Sed  for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1112193326Sed      iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1113193326Sed      iter != iterEnd; iter++) {
1114193326Sed    llvm::Constant *Idxs[] = {Zeros[0],
1115193326Sed      llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
1116193326Sed    llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy, true,
1117193326Sed        llvm::GlobalValue::InternalLinkage,
1118193326Sed        llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1119193326Sed        ".objc_sel_ptr", &TheModule);
1120193326Sed    // If selectors are defined as an opaque type, cast the pointer to this
1121193326Sed    // type.
1122193326Sed    if (isSelOpaque) {
1123193326Sed      SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1124193326Sed        llvm::PointerType::getUnqual(SelectorTy));
1125193326Sed    }
1126193326Sed    (*iter).second->setAliasee(SelPtr);
1127193326Sed  }
1128193326Sed  // Number of classes defined.
1129193326Sed  Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1130193326Sed        Classes.size()));
1131193326Sed  // Number of categories defined
1132193326Sed  Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1133193326Sed        Categories.size()));
1134193326Sed  // Create an array of classes, then categories, then static object instances
1135193326Sed  Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1136193326Sed  //  NULL-terminated list of static object instances (mainly constant strings)
1137193326Sed  Classes.push_back(Statics);
1138193326Sed  Classes.push_back(NULLPtr);
1139193326Sed  llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
1140193326Sed  Elements.push_back(ClassList);
1141193326Sed  // Construct the symbol table
1142193326Sed  llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1143193326Sed
1144193326Sed  // The symbol table is contained in a module which has some version-checking
1145193326Sed  // constants
1146193326Sed  llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
1147193326Sed      PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
1148193326Sed  Elements.clear();
1149193326Sed  // Runtime version used for compatibility checking.
1150193326Sed  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1151193326Sed	Elements.push_back(llvm::ConstantInt::get(LongTy,
1152193326Sed        NonFragileRuntimeVersion));
1153193326Sed  } else {
1154193326Sed    Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
1155193326Sed  }
1156193326Sed  // sizeof(ModuleTy)
1157193326Sed  llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1158193326Sed  Elements.push_back(llvm::ConstantInt::get(LongTy, td.getTypeSizeInBits(ModuleTy)/8));
1159193326Sed  //FIXME: Should be the path to the file where this module was declared
1160193326Sed  Elements.push_back(NULLPtr);
1161193326Sed  Elements.push_back(SymTab);
1162193326Sed  llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1163193326Sed
1164193326Sed  // Create the load function calling the runtime entry point with the module
1165193326Sed  // structure
1166193326Sed  std::vector<const llvm::Type*> VoidArgs;
1167193326Sed  llvm::Function * LoadFunction = llvm::Function::Create(
1168193326Sed      llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
1169193326Sed      llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1170193326Sed      &TheModule);
1171193326Sed  llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
1172193326Sed  CGBuilderTy Builder;
1173193326Sed  Builder.SetInsertPoint(EntryBB);
1174193326Sed
1175193326Sed  std::vector<const llvm::Type*> Params(1,
1176193326Sed      llvm::PointerType::getUnqual(ModuleTy));
1177193326Sed  llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1178193326Sed        llvm::Type::VoidTy, Params, true), "__objc_exec_class");
1179193326Sed  Builder.CreateCall(Register, Module);
1180193326Sed  Builder.CreateRetVoid();
1181193326Sed
1182193326Sed  return LoadFunction;
1183193326Sed}
1184193326Sed
1185193326Sedllvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
1186193326Sed                                          const ObjCContainerDecl *CD) {
1187193326Sed  const ObjCCategoryImplDecl *OCD =
1188193326Sed    dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
1189193326Sed  std::string CategoryName = OCD ? OCD->getNameAsString() : "";
1190193326Sed  std::string ClassName = OMD->getClassInterface()->getNameAsString();
1191193326Sed  std::string MethodName = OMD->getSelector().getAsString();
1192193326Sed  bool isClassMethod = !OMD->isInstanceMethod();
1193193326Sed
1194193326Sed  CodeGenTypes &Types = CGM.getTypes();
1195193326Sed  const llvm::FunctionType *MethodTy =
1196193326Sed    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
1197193326Sed  std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1198193326Sed      MethodName, isClassMethod);
1199193326Sed
1200193326Sed  llvm::Function *Method = llvm::Function::Create(MethodTy,
1201193326Sed      llvm::GlobalValue::InternalLinkage,
1202193326Sed      FunctionName,
1203193326Sed      &TheModule);
1204193326Sed  return Method;
1205193326Sed}
1206193326Sed
1207193326Sedllvm::Function *CGObjCGNU::GetPropertyGetFunction() {
1208193326Sed	std::vector<const llvm::Type*> Params;
1209193326Sed	const llvm::Type *BoolTy =
1210193326Sed		CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1211193326Sed	Params.push_back(IdTy);
1212193326Sed	Params.push_back(SelectorTy);
1213193326Sed	// FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1214193326Sed	Params.push_back(LongTy);
1215193326Sed	Params.push_back(BoolTy);
1216193326Sed	// void objc_getProperty (id, SEL, ptrdiff_t, bool)
1217193326Sed	const llvm::FunctionType *FTy =
1218193326Sed		llvm::FunctionType::get(IdTy, Params, false);
1219193326Sed	return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1220193326Sed				"objc_getProperty"));
1221193326Sed}
1222193326Sed
1223193326Sedllvm::Function *CGObjCGNU::GetPropertySetFunction() {
1224193326Sed	std::vector<const llvm::Type*> Params;
1225193326Sed	const llvm::Type *BoolTy =
1226193326Sed		CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1227193326Sed	Params.push_back(IdTy);
1228193326Sed	Params.push_back(SelectorTy);
1229193326Sed	// FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1230193326Sed	Params.push_back(LongTy);
1231193326Sed	Params.push_back(IdTy);
1232193326Sed	Params.push_back(BoolTy);
1233193326Sed	Params.push_back(BoolTy);
1234193326Sed	// void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
1235193326Sed	const llvm::FunctionType *FTy =
1236193326Sed		llvm::FunctionType::get(llvm::Type::VoidTy, Params, false);
1237193326Sed	return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1238193326Sed				"objc_setProperty"));
1239193326Sed}
1240193326Sed
1241193326Sedllvm::Function *CGObjCGNU::EnumerationMutationFunction() {
1242193326Sed  std::vector<const llvm::Type*> Params(1, IdTy);
1243193326Sed  return cast<llvm::Function>(CGM.CreateRuntimeFunction(
1244193326Sed        llvm::FunctionType::get(llvm::Type::VoidTy, Params, true),
1245193326Sed        "objc_enumerationMutation"));
1246193326Sed}
1247193326Sed
1248193326Sedvoid CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1249193326Sed                                          const Stmt &S) {
1250193326Sed  // Pointer to the personality function
1251193326Sed  llvm::Constant *Personality =
1252193326Sed    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
1253193326Sed          std::vector<const llvm::Type*>(), true),
1254193326Sed        "__gnu_objc_personality_v0");
1255193326Sed  Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
1256193326Sed  std::vector<const llvm::Type*> Params;
1257193326Sed  Params.push_back(PtrTy);
1258193326Sed  llvm::Value *RethrowFn =
1259193326Sed    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
1260193326Sed          Params, false), "_Unwind_Resume_or_Rethrow");
1261193326Sed
1262193326Sed  bool isTry = isa<ObjCAtTryStmt>(S);
1263193326Sed  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1264193326Sed  llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1265193326Sed  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1266193326Sed  llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
1267193326Sed  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1268193326Sed  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1269193326Sed  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1270193326Sed
1271193326Sed  // GNU runtime does not currently support @synchronized()
1272193326Sed  if (!isTry) {
1273193326Sed    std::vector<const llvm::Type*> Args(1, IdTy);
1274193326Sed    llvm::FunctionType *FTy =
1275193326Sed      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1276193326Sed    llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1277193326Sed    llvm::Value *SyncArg =
1278193326Sed      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1279193326Sed    SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1280193326Sed    CGF.Builder.CreateCall(SyncEnter, SyncArg);
1281193326Sed  }
1282193326Sed
1283193326Sed
1284193326Sed  // Push an EH context entry, used for handling rethrows and jumps
1285193326Sed  // through finally.
1286193326Sed  CGF.PushCleanupBlock(FinallyBlock);
1287193326Sed
1288193326Sed  // Emit the statements in the @try {} block
1289193326Sed  CGF.setInvokeDest(TryHandler);
1290193326Sed
1291193326Sed  CGF.EmitBlock(TryBlock);
1292193326Sed  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1293193326Sed                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1294193326Sed
1295193326Sed  // Jump to @finally if there is no exception
1296193326Sed  CGF.EmitBranchThroughCleanup(FinallyEnd);
1297193326Sed
1298193326Sed  // Emit the handlers
1299193326Sed  CGF.EmitBlock(TryHandler);
1300193326Sed
1301193326Sed  // Get the correct versions of the exception handling intrinsics
1302193326Sed  llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1303193326Sed  int PointerWidth = td.getTypeSizeInBits(PtrTy);
1304193326Sed  assert((PointerWidth == 32 || PointerWidth == 64) &&
1305193326Sed    "Can't yet handle exceptions if pointers are not 32 or 64 bits");
1306193326Sed  llvm::Value *llvm_eh_exception =
1307193326Sed    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
1308193326Sed  llvm::Value *llvm_eh_selector = PointerWidth == 32 ?
1309193326Sed    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32) :
1310193326Sed    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
1311193326Sed  llvm::Value *llvm_eh_typeid_for = PointerWidth == 32 ?
1312193326Sed    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i32) :
1313193326Sed    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
1314193326Sed
1315193326Sed  // Exception object
1316193326Sed  llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1317193326Sed  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1318193326Sed
1319193326Sed  llvm::SmallVector<llvm::Value*, 8> ESelArgs;
1320193326Sed  llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
1321193326Sed
1322193326Sed  ESelArgs.push_back(Exc);
1323193326Sed  ESelArgs.push_back(Personality);
1324193326Sed
1325193326Sed  bool HasCatchAll = false;
1326193326Sed  // Only @try blocks are allowed @catch blocks, but both can have @finally
1327193326Sed  if (isTry) {
1328193326Sed    if (const ObjCAtCatchStmt* CatchStmt =
1329193326Sed      cast<ObjCAtTryStmt>(S).getCatchStmts())  {
1330193326Sed      CGF.setInvokeDest(CatchInCatch);
1331193326Sed
1332193326Sed      for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1333193326Sed        const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1334193326Sed        Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
1335193326Sed
1336193326Sed        // @catch() and @catch(id) both catch any ObjC exception
1337193326Sed        if (!CatchDecl || CGF.getContext().isObjCIdType(CatchDecl->getType())
1338193326Sed            || CatchDecl->getType()->isObjCQualifiedIdType()) {
1339193326Sed          // Use i8* null here to signal this is a catch all, not a cleanup.
1340193326Sed          ESelArgs.push_back(NULLPtr);
1341193326Sed          HasCatchAll = true;
1342193326Sed          // No further catches after this one will ever by reached
1343193326Sed          break;
1344193326Sed        }
1345193326Sed
1346193326Sed        // All other types should be Objective-C interface pointer types.
1347193326Sed        const PointerType *PT = CatchDecl->getType()->getAsPointerType();
1348193326Sed        assert(PT && "Invalid @catch type.");
1349193326Sed        const ObjCInterfaceType *IT =
1350193326Sed          PT->getPointeeType()->getAsObjCInterfaceType();
1351193326Sed        assert(IT && "Invalid @catch type.");
1352193326Sed        llvm::Value *EHType =
1353193326Sed          MakeConstantString(IT->getDecl()->getNameAsString());
1354193326Sed        ESelArgs.push_back(EHType);
1355193326Sed      }
1356193326Sed    }
1357193326Sed  }
1358193326Sed
1359193326Sed  // We use a cleanup unless there was already a catch all.
1360193326Sed  if (!HasCatchAll) {
1361193326Sed    ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1362193326Sed    Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1363193326Sed  }
1364193326Sed
1365193326Sed  // Find which handler was matched.
1366193326Sed  llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
1367193326Sed      ESelArgs.begin(), ESelArgs.end(), "selector");
1368193326Sed
1369193326Sed  for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
1370193326Sed    const ParmVarDecl *CatchParam = Handlers[i].first;
1371193326Sed    const Stmt *CatchBody = Handlers[i].second;
1372193326Sed
1373193326Sed    llvm::BasicBlock *Next = 0;
1374193326Sed
1375193326Sed    // The last handler always matches.
1376193326Sed    if (i + 1 != e) {
1377193326Sed      assert(CatchParam && "Only last handler can be a catch all.");
1378193326Sed
1379193326Sed      // Test whether this block matches the type for the selector and branch
1380193326Sed      // to Match if it does, or to the next BB if it doesn't.
1381193326Sed      llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1382193326Sed      Next = CGF.createBasicBlock("catch.next");
1383193326Sed      llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
1384193326Sed          CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1385193326Sed      CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1386193326Sed          Next);
1387193326Sed
1388193326Sed      CGF.EmitBlock(Match);
1389193326Sed    }
1390193326Sed
1391193326Sed    if (CatchBody) {
1392193326Sed      llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1393193326Sed          CGF.ConvertType(CatchParam->getType()));
1394193326Sed
1395193326Sed      // Bind the catch parameter if it exists.
1396193326Sed      if (CatchParam) {
1397193326Sed        // CatchParam is a ParmVarDecl because of the grammar
1398193326Sed        // construction used to handle this, but for codegen purposes
1399193326Sed        // we treat this as a local decl.
1400193326Sed        CGF.EmitLocalBlockVarDecl(*CatchParam);
1401193326Sed        CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1402193326Sed      }
1403193326Sed
1404193326Sed      CGF.ObjCEHValueStack.push_back(ExcObject);
1405193326Sed      CGF.EmitStmt(CatchBody);
1406193326Sed      CGF.ObjCEHValueStack.pop_back();
1407193326Sed
1408193326Sed      CGF.EmitBranchThroughCleanup(FinallyEnd);
1409193326Sed
1410193326Sed      if (Next)
1411193326Sed        CGF.EmitBlock(Next);
1412193326Sed    } else {
1413193326Sed      assert(!Next && "catchup should be last handler.");
1414193326Sed
1415193326Sed      CGF.Builder.CreateStore(Exc, RethrowPtr);
1416193326Sed      CGF.EmitBranchThroughCleanup(FinallyRethrow);
1417193326Sed    }
1418193326Sed  }
1419193326Sed  // The @finally block is a secondary landing pad for any exceptions thrown in
1420193326Sed  // @catch() blocks
1421193326Sed  CGF.EmitBlock(CatchInCatch);
1422193326Sed  Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1423193326Sed  ESelArgs.clear();
1424193326Sed  ESelArgs.push_back(Exc);
1425193326Sed  ESelArgs.push_back(Personality);
1426193326Sed  ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1427193326Sed  CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
1428193326Sed      "selector");
1429193326Sed  CGF.Builder.CreateCall(llvm_eh_typeid_for,
1430193326Sed      CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
1431193326Sed  CGF.Builder.CreateStore(Exc, RethrowPtr);
1432193326Sed  CGF.EmitBranchThroughCleanup(FinallyRethrow);
1433193326Sed
1434193326Sed  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
1435193326Sed
1436193326Sed  CGF.setInvokeDest(PrevLandingPad);
1437193326Sed
1438193326Sed  CGF.EmitBlock(FinallyBlock);
1439193326Sed
1440193326Sed
1441193326Sed  if (isTry) {
1442193326Sed    if (const ObjCAtFinallyStmt* FinallyStmt =
1443193326Sed        cast<ObjCAtTryStmt>(S).getFinallyStmt())
1444193326Sed      CGF.EmitStmt(FinallyStmt->getFinallyBody());
1445193326Sed  } else {
1446193326Sed    // Emit 'objc_sync_exit(expr)' as finally's sole statement for
1447193326Sed    // @synchronized.
1448193326Sed    std::vector<const llvm::Type*> Args(1, IdTy);
1449193326Sed    llvm::FunctionType *FTy =
1450193326Sed      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1451193326Sed    llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
1452193326Sed    llvm::Value *SyncArg =
1453193326Sed      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1454193326Sed    SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1455193326Sed    CGF.Builder.CreateCall(SyncExit, SyncArg);
1456193326Sed  }
1457193326Sed
1458193326Sed  if (Info.SwitchBlock)
1459193326Sed    CGF.EmitBlock(Info.SwitchBlock);
1460193326Sed  if (Info.EndBlock)
1461193326Sed    CGF.EmitBlock(Info.EndBlock);
1462193326Sed
1463193326Sed  // Branch around the rethrow code.
1464193326Sed  CGF.EmitBranch(FinallyEnd);
1465193326Sed
1466193326Sed  CGF.EmitBlock(FinallyRethrow);
1467193326Sed  CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr));
1468193326Sed  CGF.Builder.CreateUnreachable();
1469193326Sed
1470193326Sed  CGF.EmitBlock(FinallyEnd);
1471193326Sed
1472193326Sed}
1473193326Sed
1474193326Sedvoid CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1475193326Sed                              const ObjCAtThrowStmt &S) {
1476193326Sed  llvm::Value *ExceptionAsObject;
1477193326Sed
1478193326Sed  std::vector<const llvm::Type*> Args(1, IdTy);
1479193326Sed  llvm::FunctionType *FTy =
1480193326Sed    llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1481193326Sed  llvm::Value *ThrowFn =
1482193326Sed    CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1483193326Sed
1484193326Sed  if (const Expr *ThrowExpr = S.getThrowExpr()) {
1485193326Sed    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1486193326Sed    ExceptionAsObject = Exception;
1487193326Sed  } else {
1488193326Sed    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
1489193326Sed           "Unexpected rethrow outside @catch block.");
1490193326Sed    ExceptionAsObject = CGF.ObjCEHValueStack.back();
1491193326Sed  }
1492193326Sed  ExceptionAsObject =
1493193326Sed      CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
1494193326Sed
1495193326Sed  // Note: This may have to be an invoke, if we want to support constructs like:
1496193326Sed  // @try {
1497193326Sed  //  @throw(obj);
1498193326Sed  // }
1499193326Sed  // @catch(id) ...
1500193326Sed  //
1501193326Sed  // This is effectively turning @throw into an incredibly-expensive goto, but
1502193326Sed  // it may happen as a result of inlining followed by missed optimizations, or
1503193326Sed  // as a result of stupidity.
1504193326Sed  llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
1505193326Sed  if (!UnwindBB) {
1506193326Sed    CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
1507193326Sed    CGF.Builder.CreateUnreachable();
1508193326Sed  } else {
1509193326Sed    CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
1510193326Sed        &ExceptionAsObject+1);
1511193326Sed  }
1512193326Sed  // Clear the insertion point to indicate we are in unreachable code.
1513193326Sed  CGF.Builder.ClearInsertionPoint();
1514193326Sed}
1515193326Sed
1516193326Sedllvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1517193326Sed                                          llvm::Value *AddrWeakObj)
1518193326Sed{
1519193326Sed  return 0;
1520193326Sed}
1521193326Sed
1522193326Sedvoid CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1523193326Sed                                   llvm::Value *src, llvm::Value *dst)
1524193326Sed{
1525193326Sed  return;
1526193326Sed}
1527193326Sed
1528193326Sedvoid CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1529193326Sed                                     llvm::Value *src, llvm::Value *dst)
1530193326Sed{
1531193326Sed  return;
1532193326Sed}
1533193326Sed
1534193326Sedvoid CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1535193326Sed                                   llvm::Value *src, llvm::Value *dst)
1536193326Sed{
1537193326Sed  return;
1538193326Sed}
1539193326Sed
1540193326Sedvoid CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1541193326Sed                                         llvm::Value *src, llvm::Value *dst)
1542193326Sed{
1543193326Sed  return;
1544193326Sed}
1545193326Sed
1546193326Sedllvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
1547193326Sed                              const ObjCInterfaceDecl *ID,
1548193326Sed                              const ObjCIvarDecl *Ivar) {
1549193326Sed  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1550193326Sed    + '.' + Ivar->getNameAsString();
1551193326Sed  // Emit the variable and initialize it with what we think the correct value
1552193326Sed  // is.  This allows code compiled with non-fragile ivars to work correctly
1553193326Sed  // when linked against code which isn't (most of the time).
1554193326Sed  llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
1555193326Sed  if (!IvarOffsetGV) {
1556193326Sed    uint64_t Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
1557193326Sed    llvm::ConstantInt *OffsetGuess =
1558193326Sed      llvm::ConstantInt::get(LongTy, Offset, "ivar");
1559193326Sed    IvarOffsetGV = new llvm::GlobalVariable(LongTy, false,
1560193326Sed        llvm::GlobalValue::CommonLinkage, OffsetGuess, Name, &TheModule);
1561193326Sed  }
1562193326Sed  return IvarOffsetGV;
1563193326Sed}
1564193326Sed
1565193326SedLValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1566193326Sed                                       QualType ObjectTy,
1567193326Sed                                       llvm::Value *BaseValue,
1568193326Sed                                       const ObjCIvarDecl *Ivar,
1569193326Sed                                       unsigned CVRQualifiers) {
1570193326Sed  const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
1571193326Sed  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
1572193326Sed                                  EmitIvarOffset(CGF, ID, Ivar));
1573193326Sed}
1574193326Sedstatic const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
1575193326Sed                                                  const ObjCInterfaceDecl *OID,
1576193326Sed                                                  const ObjCIvarDecl *OIVD) {
1577193326Sed  llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
1578193576Sed  Context.ShallowCollectObjCIvars(OID, Ivars);
1579193326Sed  for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
1580193326Sed    if (OIVD == Ivars[k])
1581193326Sed      return OID;
1582193326Sed  }
1583193326Sed
1584193326Sed  // Otherwise check in the super class.
1585193326Sed  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1586193326Sed    return FindIvarInterface(Context, Super, OIVD);
1587193326Sed
1588193326Sed  return 0;
1589193326Sed}
1590193326Sed
1591193326Sedllvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1592193326Sed                         const ObjCInterfaceDecl *Interface,
1593193326Sed                         const ObjCIvarDecl *Ivar) {
1594193326Sed  if (CGF.getContext().getLangOptions().ObjCNonFragileABI)
1595193326Sed  {
1596193326Sed    Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
1597193326Sed    return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
1598193326Sed        false, "ivar");
1599193326Sed  }
1600193326Sed  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
1601193326Sed  return llvm::ConstantInt::get(LongTy, Offset, "ivar");
1602193326Sed}
1603193326Sed
1604193326SedCodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
1605193326Sed  return new CGObjCGNU(CGM);
1606193326Sed}
1607