CGObjCGNU.cpp revision 208954
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 "CodeGenFunction.h"
20
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtObjC.h"
26
27#include "llvm/Intrinsics.h"
28#include "llvm/Module.h"
29#include "llvm/LLVMContext.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringMap.h"
32#include "llvm/Support/Compiler.h"
33#include "llvm/Target/TargetData.h"
34
35#include <map>
36
37
38using namespace clang;
39using namespace CodeGen;
40using llvm::dyn_cast;
41
42// The version of the runtime that this class targets.  Must match the version
43// in the runtime.
44static const int RuntimeVersion = 8;
45static const int NonFragileRuntimeVersion = 9;
46static const int ProtocolVersion = 2;
47static const int NonFragileProtocolVersion = 3;
48
49namespace {
50class CGObjCGNU : public CodeGen::CGObjCRuntime {
51private:
52  CodeGen::CodeGenModule &CGM;
53  llvm::Module &TheModule;
54  const llvm::PointerType *SelectorTy;
55  const llvm::IntegerType *Int8Ty;
56  const llvm::PointerType *PtrToInt8Ty;
57  const llvm::FunctionType *IMPTy;
58  const llvm::PointerType *IdTy;
59  const llvm::PointerType *PtrToIdTy;
60  CanQualType ASTIdTy;
61  const llvm::IntegerType *IntTy;
62  const llvm::PointerType *PtrTy;
63  const llvm::IntegerType *LongTy;
64  const llvm::PointerType *PtrToIntTy;
65  llvm::GlobalAlias *ClassPtrAlias;
66  llvm::GlobalAlias *MetaClassPtrAlias;
67  std::vector<llvm::Constant*> Classes;
68  std::vector<llvm::Constant*> Categories;
69  std::vector<llvm::Constant*> ConstantStrings;
70  llvm::StringMap<llvm::Constant*> ObjCStrings;
71  llvm::Function *LoadFunction;
72  llvm::StringMap<llvm::Constant*> ExistingProtocols;
73  typedef std::pair<std::string, std::string> TypedSelector;
74  std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
75  llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
76  // Selectors that we don't emit in GC mode
77  Selector RetainSel, ReleaseSel, AutoreleaseSel;
78  // Functions used for GC.
79  llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
80    *WeakAssignFn, *GlobalAssignFn;
81  // Some zeros used for GEPs in lots of places.
82  llvm::Constant *Zeros[2];
83  llvm::Constant *NULLPtr;
84  llvm::LLVMContext &VMContext;
85  /// Metadata kind used to tie method lookups to message sends.
86  unsigned msgSendMDKind;
87private:
88  llvm::Constant *GenerateIvarList(
89      const llvm::SmallVectorImpl<llvm::Constant *>  &IvarNames,
90      const llvm::SmallVectorImpl<llvm::Constant *>  &IvarTypes,
91      const llvm::SmallVectorImpl<llvm::Constant *>  &IvarOffsets);
92  llvm::Constant *GenerateMethodList(const std::string &ClassName,
93      const std::string &CategoryName,
94      const llvm::SmallVectorImpl<Selector>  &MethodSels,
95      const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes,
96      bool isClassMethodList);
97  llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
98  llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
99        llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
100        llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
101  llvm::Constant *GenerateProtocolList(
102      const llvm::SmallVectorImpl<std::string> &Protocols);
103  // To ensure that all protocols are seen by the runtime, we add a category on
104  // a class defined in the runtime, declaring no methods, but adopting the
105  // protocols.
106  void GenerateProtocolHolderCategory(void);
107  llvm::Constant *GenerateClassStructure(
108      llvm::Constant *MetaClass,
109      llvm::Constant *SuperClass,
110      unsigned info,
111      const char *Name,
112      llvm::Constant *Version,
113      llvm::Constant *InstanceSize,
114      llvm::Constant *IVars,
115      llvm::Constant *Methods,
116      llvm::Constant *Protocols,
117      llvm::Constant *IvarOffsets,
118      llvm::Constant *Properties,
119      bool isMeta=false);
120  llvm::Constant *GenerateProtocolMethodList(
121      const llvm::SmallVectorImpl<llvm::Constant *>  &MethodNames,
122      const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes);
123  llvm::Constant *MakeConstantString(const std::string &Str, const std::string
124      &Name="");
125  llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
126          prefix);
127  llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
128    std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
129    llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
130  llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
131    std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
132    llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
133  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
134      const ObjCIvarDecl *Ivar);
135  void EmitClassRef(const std::string &className);
136  llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
137    if (V->getType() == Ty) return V;
138    return B.CreateBitCast(V, Ty);
139  }
140public:
141  CGObjCGNU(CodeGen::CodeGenModule &cgm);
142  virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
143  virtual CodeGen::RValue
144  GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
145                      ReturnValueSlot Return,
146                      QualType ResultType,
147                      Selector Sel,
148                      llvm::Value *Receiver,
149                      const CallArgList &CallArgs,
150                      const ObjCInterfaceDecl *Class,
151                      const ObjCMethodDecl *Method);
152  virtual CodeGen::RValue
153  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
154                           ReturnValueSlot Return,
155                           QualType ResultType,
156                           Selector Sel,
157                           const ObjCInterfaceDecl *Class,
158                           bool isCategoryImpl,
159                           llvm::Value *Receiver,
160                           bool IsClassMessage,
161                           const CallArgList &CallArgs,
162                           const ObjCMethodDecl *Method);
163  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
164                                const ObjCInterfaceDecl *OID);
165  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
166  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
167      *Method);
168
169  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
170                                         const ObjCContainerDecl *CD);
171  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
172  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
173  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
174                                           const ObjCProtocolDecl *PD);
175  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
176  virtual llvm::Function *ModuleInitFunction();
177  virtual llvm::Function *GetPropertyGetFunction();
178  virtual llvm::Function *GetPropertySetFunction();
179  virtual llvm::Function *GetCopyStructFunction();
180  virtual llvm::Constant *EnumerationMutationFunction();
181
182  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
183                                         const Stmt &S);
184  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
185                             const ObjCAtThrowStmt &S);
186  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
187                                         llvm::Value *AddrWeakObj);
188  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
189                                  llvm::Value *src, llvm::Value *dst);
190  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
191                                    llvm::Value *src, llvm::Value *dest);
192  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
193                                    llvm::Value *src, llvm::Value *dest,
194                                    llvm::Value *ivarOffset);
195  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
196                                        llvm::Value *src, llvm::Value *dest);
197  virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
198                                        llvm::Value *DestPtr,
199                                        llvm::Value *SrcPtr,
200                                        QualType Ty);
201  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
202                                      QualType ObjectTy,
203                                      llvm::Value *BaseValue,
204                                      const ObjCIvarDecl *Ivar,
205                                      unsigned CVRQualifiers);
206  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
207                                      const ObjCInterfaceDecl *Interface,
208                                      const ObjCIvarDecl *Ivar);
209};
210} // end anonymous namespace
211
212
213/// Emits a reference to a dummy variable which is emitted with each class.
214/// This ensures that a linker error will be generated when trying to link
215/// together modules where a referenced class is not defined.
216void CGObjCGNU::EmitClassRef(const std::string &className) {
217  std::string symbolRef = "__objc_class_ref_" + className;
218  // Don't emit two copies of the same symbol
219  if (TheModule.getGlobalVariable(symbolRef))
220    return;
221  std::string symbolName = "__objc_class_name_" + className;
222  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
223  if (!ClassSymbol) {
224    ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
225        llvm::GlobalValue::ExternalLinkage, 0, symbolName);
226  }
227  new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
228    llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
229}
230
231static std::string SymbolNameForMethod(const std::string &ClassName, const
232  std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
233{
234  std::string MethodNameColonStripped = MethodName;
235  std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
236      ':', '_');
237  return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
238    CategoryName + "_" + MethodNameColonStripped;
239}
240static std::string MangleSelectorTypes(const std::string &TypeString) {
241  std::string Mangled = TypeString;
242  // Simple mangling to avoid breaking when we mix JIT / static code.
243  // Not part of the ABI, subject to change without notice.
244  std::replace(Mangled.begin(), Mangled.end(), '@', '_');
245  std::replace(Mangled.begin(), Mangled.end(), ':', 'J');
246  std::replace(Mangled.begin(), Mangled.end(), '*', 'e');
247  std::replace(Mangled.begin(), Mangled.end(), '#', 'E');
248  std::replace(Mangled.begin(), Mangled.end(), ':', 'j');
249  std::replace(Mangled.begin(), Mangled.end(), '(', 'g');
250  std::replace(Mangled.begin(), Mangled.end(), ')', 'G');
251  std::replace(Mangled.begin(), Mangled.end(), '[', 'h');
252  std::replace(Mangled.begin(), Mangled.end(), ']', 'H');
253  return Mangled;
254}
255
256CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
257  : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
258    MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
259
260  msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
261
262  IntTy = cast<llvm::IntegerType>(
263      CGM.getTypes().ConvertType(CGM.getContext().IntTy));
264  LongTy = cast<llvm::IntegerType>(
265      CGM.getTypes().ConvertType(CGM.getContext().LongTy));
266
267  Int8Ty = llvm::Type::getInt8Ty(VMContext);
268  // C string type.  Used in lots of places.
269  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
270
271  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
272  Zeros[1] = Zeros[0];
273  NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
274  // Get the selector Type.
275  QualType selTy = CGM.getContext().getObjCSelType();
276  if (QualType() == selTy) {
277    SelectorTy = PtrToInt8Ty;
278  } else {
279    SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
280  }
281
282  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
283  PtrTy = PtrToInt8Ty;
284
285  // Object type
286  ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
287  if (QualType() == ASTIdTy) {
288    IdTy = PtrToInt8Ty;
289  } else {
290    IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
291  }
292  PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
293
294  // IMP type
295  std::vector<const llvm::Type*> IMPArgs;
296  IMPArgs.push_back(IdTy);
297  IMPArgs.push_back(SelectorTy);
298  IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
299
300  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
301    // Get selectors needed in GC mode
302    RetainSel = GetNullarySelector("retain", CGM.getContext());
303    ReleaseSel = GetNullarySelector("release", CGM.getContext());
304    AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
305
306    // Get functions needed in GC mode
307
308    // id objc_assign_ivar(id, id, ptrdiff_t);
309    std::vector<const llvm::Type*> Args(1, IdTy);
310    Args.push_back(PtrToIdTy);
311    // FIXME: ptrdiff_t
312    Args.push_back(LongTy);
313    llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
314    IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
315    // id objc_assign_strongCast (id, id*)
316    Args.pop_back();
317    FTy = llvm::FunctionType::get(IdTy, Args, false);
318    StrongCastAssignFn =
319        CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
320    // id objc_assign_global(id, id*);
321    FTy = llvm::FunctionType::get(IdTy, Args, false);
322    GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
323    // id objc_assign_weak(id, id*);
324    FTy = llvm::FunctionType::get(IdTy, Args, false);
325    WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
326    // id objc_read_weak(id*);
327    Args.clear();
328    Args.push_back(PtrToIdTy);
329    FTy = llvm::FunctionType::get(IdTy, Args, false);
330    WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
331    // void *objc_memmove_collectable(void*, void *, size_t);
332    Args.clear();
333    Args.push_back(PtrToInt8Ty);
334    Args.push_back(PtrToInt8Ty);
335    // FIXME: size_t
336    Args.push_back(LongTy);
337    FTy = llvm::FunctionType::get(IdTy, Args, false);
338    MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
339  }
340}
341
342// This has to perform the lookup every time, since posing and related
343// techniques can modify the name -> class mapping.
344llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
345                                 const ObjCInterfaceDecl *OID) {
346  llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
347  // With the incompatible ABI, this will need to be replaced with a direct
348  // reference to the class symbol.  For the compatible nonfragile ABI we are
349  // still performing this lookup at run time but emitting the symbol for the
350  // class externally so that we can make the switch later.
351  EmitClassRef(OID->getNameAsString());
352  ClassName = Builder.CreateStructGEP(ClassName, 0);
353
354  std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
355  llvm::Constant *ClassLookupFn =
356    CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
357                                                      Params,
358                                                      true),
359                              "objc_lookup_class");
360  return Builder.CreateCall(ClassLookupFn, ClassName);
361}
362
363llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
364  llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
365  if (US == 0)
366    US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
367                               llvm::GlobalValue::PrivateLinkage,
368                               ".objc_untyped_selector_alias"+Sel.getAsString(),
369                               NULL, &TheModule);
370
371  return Builder.CreateLoad(US);
372}
373
374llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
375    *Method) {
376
377  std::string SelName = Method->getSelector().getAsString();
378  std::string SelTypes;
379  CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
380  // Typed selectors
381  TypedSelector Selector = TypedSelector(SelName,
382          SelTypes);
383
384  // If it's already cached, return it.
385  if (TypedSelectors[Selector]) {
386    return Builder.CreateLoad(TypedSelectors[Selector]);
387  }
388
389  // If it isn't, cache it.
390  llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
391          llvm::PointerType::getUnqual(SelectorTy),
392          llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
393          NULL, &TheModule);
394  TypedSelectors[Selector] = Sel;
395
396  return Builder.CreateLoad(Sel);
397}
398
399llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
400                                              const std::string &Name) {
401  llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
402  return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
403}
404llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
405        const std::string prefix) {
406  std::string name = prefix + Str;
407  llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
408  if (!ConstStr) {
409    llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
410    ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
411            llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
412  }
413  return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
414}
415
416llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
417    std::vector<llvm::Constant*> &V, llvm::StringRef Name,
418    llvm::GlobalValue::LinkageTypes linkage) {
419  llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
420  return new llvm::GlobalVariable(TheModule, Ty, false,
421      llvm::GlobalValue::InternalLinkage, C, Name);
422}
423
424llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
425    std::vector<llvm::Constant*> &V, llvm::StringRef Name,
426    llvm::GlobalValue::LinkageTypes linkage) {
427  llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
428  return new llvm::GlobalVariable(TheModule, Ty, false,
429                                  llvm::GlobalValue::InternalLinkage, C, Name);
430}
431
432/// Generate an NSConstantString object.
433llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
434
435  std::string Str(SL->getStrData(), SL->getByteLength());
436
437  // Look for an existing one
438  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
439  if (old != ObjCStrings.end())
440    return old->getValue();
441
442  std::vector<llvm::Constant*> Ivars;
443  Ivars.push_back(NULLPtr);
444  Ivars.push_back(MakeConstantString(Str));
445  Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
446  llvm::Constant *ObjCStr = MakeGlobal(
447    llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
448    Ivars, ".objc_str");
449  ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
450  ObjCStrings[Str] = ObjCStr;
451  ConstantStrings.push_back(ObjCStr);
452  return ObjCStr;
453}
454
455///Generates a message send where the super is the receiver.  This is a message
456///send to self with special delivery semantics indicating which class's method
457///should be called.
458CodeGen::RValue
459CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
460                                    ReturnValueSlot Return,
461                                    QualType ResultType,
462                                    Selector Sel,
463                                    const ObjCInterfaceDecl *Class,
464                                    bool isCategoryImpl,
465                                    llvm::Value *Receiver,
466                                    bool IsClassMessage,
467                                    const CallArgList &CallArgs,
468                                    const ObjCMethodDecl *Method) {
469  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
470    if (Sel == RetainSel || Sel == AutoreleaseSel) {
471      return RValue::get(Receiver);
472    }
473    if (Sel == ReleaseSel) {
474      return RValue::get(0);
475    }
476  }
477
478  CGBuilderTy &Builder = CGF.Builder;
479  llvm::Value *cmd = GetSelector(Builder, Sel);
480
481
482  CallArgList ActualArgs;
483
484  ActualArgs.push_back(
485      std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
486      ASTIdTy));
487  ActualArgs.push_back(std::make_pair(RValue::get(cmd),
488                                      CGF.getContext().getObjCSelType()));
489  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
490
491  CodeGenTypes &Types = CGM.getTypes();
492  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
493                                                       FunctionType::ExtInfo());
494  const llvm::FunctionType *impType =
495    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
496
497  llvm::Value *ReceiverClass = 0;
498  if (isCategoryImpl) {
499    llvm::Constant *classLookupFunction = 0;
500    std::vector<const llvm::Type*> Params;
501    Params.push_back(PtrTy);
502    if (IsClassMessage)  {
503      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
504            IdTy, Params, true), "objc_get_meta_class");
505    } else {
506      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
507            IdTy, Params, true), "objc_get_class");
508    }
509    ReceiverClass = Builder.CreateCall(classLookupFunction,
510        MakeConstantString(Class->getNameAsString()));
511  } else {
512    // Set up global aliases for the metaclass or class pointer if they do not
513    // already exist.  These will are forward-references which will be set to
514    // pointers to the class and metaclass structure created for the runtime
515    // load function.  To send a message to super, we look up the value of the
516    // super_class pointer from either the class or metaclass structure.
517    if (IsClassMessage)  {
518      if (!MetaClassPtrAlias) {
519        MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
520            llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
521            Class->getNameAsString(), NULL, &TheModule);
522      }
523      ReceiverClass = MetaClassPtrAlias;
524    } else {
525      if (!ClassPtrAlias) {
526        ClassPtrAlias = new llvm::GlobalAlias(IdTy,
527            llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
528            Class->getNameAsString(), NULL, &TheModule);
529      }
530      ReceiverClass = ClassPtrAlias;
531    }
532  }
533  // Cast the pointer to a simplified version of the class structure
534  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
535      llvm::PointerType::getUnqual(
536        llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
537  // Get the superclass pointer
538  ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
539  // Load the superclass pointer
540  ReceiverClass = Builder.CreateLoad(ReceiverClass);
541  // Construct the structure used to look up the IMP
542  llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
543      Receiver->getType(), IdTy, NULL);
544  llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
545
546  Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
547  Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
548
549  // Get the IMP
550  std::vector<const llvm::Type*> Params;
551  Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
552  Params.push_back(SelectorTy);
553
554  llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
555  llvm::Value *imp;
556
557  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
558    // The lookup function returns a slot, which can be safely cached.
559    llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
560            IntTy, llvm::PointerType::getUnqual(impType), NULL);
561
562    llvm::Constant *lookupFunction =
563      CGM.CreateRuntimeFunction(llvm::FunctionType::get(
564            llvm::PointerType::getUnqual(SlotTy), Params, true),
565          "objc_slot_lookup_super");
566
567    llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
568        lookupArgs+2);
569    slot->setOnlyReadsMemory();
570
571    imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
572  } else {
573  llvm::Constant *lookupFunction =
574    CGM.CreateRuntimeFunction(llvm::FunctionType::get(
575          llvm::PointerType::getUnqual(impType), Params, true),
576        "objc_msg_lookup_super");
577    imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
578  }
579
580  llvm::Value *impMD[] = {
581      llvm::MDString::get(VMContext, Sel.getAsString()),
582      llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
583      llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
584   };
585  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
586
587  llvm::Instruction *call;
588  RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
589      0, &call);
590  call->setMetadata(msgSendMDKind, node);
591  return msgRet;
592}
593
594/// Generate code for a message send expression.
595CodeGen::RValue
596CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
597                               ReturnValueSlot Return,
598                               QualType ResultType,
599                               Selector Sel,
600                               llvm::Value *Receiver,
601                               const CallArgList &CallArgs,
602                               const ObjCInterfaceDecl *Class,
603                               const ObjCMethodDecl *Method) {
604  // Strip out message sends to retain / release in GC mode
605  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
606    if (Sel == RetainSel || Sel == AutoreleaseSel) {
607      return RValue::get(Receiver);
608    }
609    if (Sel == ReleaseSel) {
610      return RValue::get(0);
611    }
612  }
613
614  CGBuilderTy &Builder = CGF.Builder;
615
616  // If the return type is something that goes in an integer register, the
617  // runtime will handle 0 returns.  For other cases, we fill in the 0 value
618  // ourselves.
619  //
620  // The language spec says the result of this kind of message send is
621  // undefined, but lots of people seem to have forgotten to read that
622  // paragraph and insist on sending messages to nil that have structure
623  // returns.  With GCC, this generates a random return value (whatever happens
624  // to be on the stack / in those registers at the time) on most platforms,
625  // and generates a SegV on SPARC.  With LLVM it corrupts the stack.
626  bool isPointerSizedReturn = false;
627  if (ResultType->isAnyPointerType() || ResultType->isIntegralType() ||
628      ResultType->isVoidType())
629    isPointerSizedReturn = true;
630
631  llvm::BasicBlock *startBB = 0;
632  llvm::BasicBlock *messageBB = 0;
633  llvm::BasicBlock *continueBB = 0;
634
635  if (!isPointerSizedReturn) {
636    startBB = Builder.GetInsertBlock();
637    messageBB = CGF.createBasicBlock("msgSend");
638    continueBB = CGF.createBasicBlock("continue");
639
640    llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
641            llvm::Constant::getNullValue(Receiver->getType()));
642    Builder.CreateCondBr(isNil, continueBB, messageBB);
643    CGF.EmitBlock(messageBB);
644  }
645
646  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
647  llvm::Value *cmd;
648  if (Method)
649    cmd = GetSelector(Builder, Method);
650  else
651    cmd = GetSelector(Builder, Sel);
652  CallArgList ActualArgs;
653
654  Receiver = Builder.CreateBitCast(Receiver, IdTy);
655  ActualArgs.push_back(
656    std::make_pair(RValue::get(Receiver), ASTIdTy));
657  ActualArgs.push_back(std::make_pair(RValue::get(cmd),
658                                      CGF.getContext().getObjCSelType()));
659  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
660
661  CodeGenTypes &Types = CGM.getTypes();
662  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
663                                                       FunctionType::ExtInfo());
664  const llvm::FunctionType *impType =
665    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
666
667  llvm::Value *impMD[] = {
668        llvm::MDString::get(VMContext, Sel.getAsString()),
669        llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
670        llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
671   };
672  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
673
674
675  llvm::Value *imp;
676  // For sender-aware dispatch, we pass the sender as the third argument to a
677  // lookup function.  When sending messages from C code, the sender is nil.
678  // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
679  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
680
681    std::vector<const llvm::Type*> Params;
682    llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
683    Builder.CreateStore(Receiver, ReceiverPtr);
684    Params.push_back(ReceiverPtr->getType());
685    Params.push_back(SelectorTy);
686    llvm::Value *self;
687
688    if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
689      self = CGF.LoadObjCSelf();
690    } else {
691      self = llvm::ConstantPointerNull::get(IdTy);
692    }
693
694    Params.push_back(self->getType());
695
696    // The lookup function returns a slot, which can be safely cached.
697    llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
698            IntTy, llvm::PointerType::getUnqual(impType), NULL);
699    llvm::Constant *lookupFunction =
700      CGM.CreateRuntimeFunction(llvm::FunctionType::get(
701          llvm::PointerType::getUnqual(SlotTy), Params, true),
702        "objc_msg_lookup_sender");
703
704    // The lookup function is guaranteed not to capture the receiver pointer.
705    if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
706      LookupFn->setDoesNotCapture(1);
707    }
708
709    llvm::CallInst *slot =
710        Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
711    slot->setOnlyReadsMemory();
712    slot->setMetadata(msgSendMDKind, node);
713
714    imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
715
716    // The lookup function may have changed the receiver, so make sure we use
717    // the new one.
718    ActualArgs[0] =
719        std::make_pair(RValue::get(Builder.CreateLoad(ReceiverPtr)), ASTIdTy);
720  } else {
721    std::vector<const llvm::Type*> Params;
722    Params.push_back(Receiver->getType());
723    Params.push_back(SelectorTy);
724    llvm::Constant *lookupFunction =
725    CGM.CreateRuntimeFunction(llvm::FunctionType::get(
726        llvm::PointerType::getUnqual(impType), Params, true),
727      "objc_msg_lookup");
728
729    imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
730    cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
731  }
732  llvm::Instruction *call;
733  RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
734      0, &call);
735  call->setMetadata(msgSendMDKind, node);
736
737
738  if (!isPointerSizedReturn) {
739    messageBB = CGF.Builder.GetInsertBlock();
740    CGF.Builder.CreateBr(continueBB);
741    CGF.EmitBlock(continueBB);
742    if (msgRet.isScalar()) {
743      llvm::Value *v = msgRet.getScalarVal();
744      llvm::PHINode *phi = Builder.CreatePHI(v->getType());
745      phi->addIncoming(v, messageBB);
746      phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
747      msgRet = RValue::get(phi);
748    } else if (msgRet.isAggregate()) {
749      llvm::Value *v = msgRet.getAggregateAddr();
750      llvm::PHINode *phi = Builder.CreatePHI(v->getType());
751      const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
752      llvm::AllocaInst *NullVal =
753          CGF.CreateTempAlloca(RetTy->getElementType(), "null");
754      CGF.InitTempAlloca(NullVal,
755          llvm::Constant::getNullValue(RetTy->getElementType()));
756      phi->addIncoming(v, messageBB);
757      phi->addIncoming(NullVal, startBB);
758      msgRet = RValue::getAggregate(phi);
759    } else /* isComplex() */ {
760      std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
761      llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
762      phi->addIncoming(v.first, messageBB);
763      phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
764          startBB);
765      llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
766      phi2->addIncoming(v.second, messageBB);
767      phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
768          startBB);
769      msgRet = RValue::getComplex(phi, phi2);
770    }
771  }
772  return msgRet;
773}
774
775/// Generates a MethodList.  Used in construction of a objc_class and
776/// objc_category structures.
777llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
778                                              const std::string &CategoryName,
779    const llvm::SmallVectorImpl<Selector> &MethodSels,
780    const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
781    bool isClassMethodList) {
782  if (MethodSels.empty())
783    return NULLPtr;
784  // Get the method structure type.
785  llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
786    PtrToInt8Ty, // Really a selector, but the runtime creates it us.
787    PtrToInt8Ty, // Method types
788    llvm::PointerType::getUnqual(IMPTy), //Method pointer
789    NULL);
790  std::vector<llvm::Constant*> Methods;
791  std::vector<llvm::Constant*> Elements;
792  for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
793    Elements.clear();
794    if (llvm::Constant *Method =
795      TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
796                                                MethodSels[i].getAsString(),
797                                                isClassMethodList))) {
798      llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
799      Elements.push_back(C);
800      Elements.push_back(MethodTypes[i]);
801      Method = llvm::ConstantExpr::getBitCast(Method,
802          llvm::PointerType::getUnqual(IMPTy));
803      Elements.push_back(Method);
804      Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
805    }
806  }
807
808  // Array of method structures
809  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
810                                                            Methods.size());
811  llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
812                                                         Methods);
813
814  // Structure containing list pointer, array and array count
815  llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
816  llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
817  llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
818  llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
819      NextPtrTy,
820      IntTy,
821      ObjCMethodArrayTy,
822      NULL);
823  // Refine next pointer type to concrete type
824  llvm::cast<llvm::OpaqueType>(
825      OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
826  ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
827
828  Methods.clear();
829  Methods.push_back(llvm::ConstantPointerNull::get(
830        llvm::PointerType::getUnqual(ObjCMethodListTy)));
831  Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
832        MethodTypes.size()));
833  Methods.push_back(MethodArray);
834
835  // Create an instance of the structure
836  return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
837}
838
839/// Generates an IvarList.  Used in construction of a objc_class.
840llvm::Constant *CGObjCGNU::GenerateIvarList(
841    const llvm::SmallVectorImpl<llvm::Constant *>  &IvarNames,
842    const llvm::SmallVectorImpl<llvm::Constant *>  &IvarTypes,
843    const llvm::SmallVectorImpl<llvm::Constant *>  &IvarOffsets) {
844  if (IvarNames.size() == 0)
845    return NULLPtr;
846  // Get the method structure type.
847  llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
848    PtrToInt8Ty,
849    PtrToInt8Ty,
850    IntTy,
851    NULL);
852  std::vector<llvm::Constant*> Ivars;
853  std::vector<llvm::Constant*> Elements;
854  for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
855    Elements.clear();
856    Elements.push_back(IvarNames[i]);
857    Elements.push_back(IvarTypes[i]);
858    Elements.push_back(IvarOffsets[i]);
859    Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
860  }
861
862  // Array of method structures
863  llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
864      IvarNames.size());
865
866
867  Elements.clear();
868  Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
869  Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
870  // Structure containing array and array count
871  llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
872    ObjCIvarArrayTy,
873    NULL);
874
875  // Create an instance of the structure
876  return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
877}
878
879/// Generate a class structure
880llvm::Constant *CGObjCGNU::GenerateClassStructure(
881    llvm::Constant *MetaClass,
882    llvm::Constant *SuperClass,
883    unsigned info,
884    const char *Name,
885    llvm::Constant *Version,
886    llvm::Constant *InstanceSize,
887    llvm::Constant *IVars,
888    llvm::Constant *Methods,
889    llvm::Constant *Protocols,
890    llvm::Constant *IvarOffsets,
891    llvm::Constant *Properties,
892    bool isMeta) {
893  // Set up the class structure
894  // Note:  Several of these are char*s when they should be ids.  This is
895  // because the runtime performs this translation on load.
896  //
897  // Fields marked New ABI are part of the GNUstep runtime.  We emit them
898  // anyway; the classes will still work with the GNU runtime, they will just
899  // be ignored.
900  llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
901      PtrToInt8Ty,        // class_pointer
902      PtrToInt8Ty,        // super_class
903      PtrToInt8Ty,        // name
904      LongTy,             // version
905      LongTy,             // info
906      LongTy,             // instance_size
907      IVars->getType(),   // ivars
908      Methods->getType(), // methods
909      // These are all filled in by the runtime, so we pretend
910      PtrTy,              // dtable
911      PtrTy,              // subclass_list
912      PtrTy,              // sibling_class
913      PtrTy,              // protocols
914      PtrTy,              // gc_object_type
915      // New ABI:
916      LongTy,                 // abi_version
917      IvarOffsets->getType(), // ivar_offsets
918      Properties->getType(),  // properties
919      NULL);
920  llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
921  // Fill in the structure
922  std::vector<llvm::Constant*> Elements;
923  Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
924  Elements.push_back(SuperClass);
925  Elements.push_back(MakeConstantString(Name, ".class_name"));
926  Elements.push_back(Zero);
927  Elements.push_back(llvm::ConstantInt::get(LongTy, info));
928  Elements.push_back(InstanceSize);
929  Elements.push_back(IVars);
930  Elements.push_back(Methods);
931  Elements.push_back(NULLPtr);
932  Elements.push_back(NULLPtr);
933  Elements.push_back(NULLPtr);
934  Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
935  Elements.push_back(NULLPtr);
936  Elements.push_back(Zero);
937  Elements.push_back(IvarOffsets);
938  Elements.push_back(Properties);
939  // Create an instance of the structure
940  // This is now an externally visible symbol, so that we can speed up class
941  // messages in the next ABI.
942  return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
943      "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
944}
945
946llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
947    const llvm::SmallVectorImpl<llvm::Constant *>  &MethodNames,
948    const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes) {
949  // Get the method structure type.
950  llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
951    PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
952    PtrToInt8Ty,
953    NULL);
954  std::vector<llvm::Constant*> Methods;
955  std::vector<llvm::Constant*> Elements;
956  for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
957    Elements.clear();
958    Elements.push_back(MethodNames[i]);
959    Elements.push_back(MethodTypes[i]);
960    Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
961  }
962  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
963      MethodNames.size());
964  llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
965                                                   Methods);
966  llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
967      IntTy, ObjCMethodArrayTy, NULL);
968  Methods.clear();
969  Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
970  Methods.push_back(Array);
971  return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
972}
973
974// Create the protocol list structure used in classes, categories and so on
975llvm::Constant *CGObjCGNU::GenerateProtocolList(
976    const llvm::SmallVectorImpl<std::string> &Protocols) {
977  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
978      Protocols.size());
979  llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
980      PtrTy, //Should be a recurisve pointer, but it's always NULL here.
981      LongTy,//FIXME: Should be size_t
982      ProtocolArrayTy,
983      NULL);
984  std::vector<llvm::Constant*> Elements;
985  for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
986      iter != endIter ; iter++) {
987    llvm::Constant *protocol = 0;
988    llvm::StringMap<llvm::Constant*>::iterator value =
989      ExistingProtocols.find(*iter);
990    if (value == ExistingProtocols.end()) {
991      protocol = GenerateEmptyProtocol(*iter);
992    } else {
993      protocol = value->getValue();
994    }
995    llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
996                                                           PtrToInt8Ty);
997    Elements.push_back(Ptr);
998  }
999  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1000      Elements);
1001  Elements.clear();
1002  Elements.push_back(NULLPtr);
1003  Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1004  Elements.push_back(ProtocolArray);
1005  return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1006}
1007
1008llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
1009                                            const ObjCProtocolDecl *PD) {
1010  llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1011  const llvm::Type *T =
1012    CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1013  return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1014}
1015
1016llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1017  const std::string &ProtocolName) {
1018  llvm::SmallVector<std::string, 0> EmptyStringVector;
1019  llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1020
1021  llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1022  llvm::Constant *MethodList =
1023    GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1024  // Protocols are objects containing lists of the methods implemented and
1025  // protocols adopted.
1026  llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
1027      PtrToInt8Ty,
1028      ProtocolList->getType(),
1029      MethodList->getType(),
1030      MethodList->getType(),
1031      MethodList->getType(),
1032      MethodList->getType(),
1033      NULL);
1034  std::vector<llvm::Constant*> Elements;
1035  // The isa pointer must be set to a magic number so the runtime knows it's
1036  // the correct layout.
1037  int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1038      NonFragileProtocolVersion : ProtocolVersion;
1039  Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1040        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
1041  Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1042  Elements.push_back(ProtocolList);
1043  Elements.push_back(MethodList);
1044  Elements.push_back(MethodList);
1045  Elements.push_back(MethodList);
1046  Elements.push_back(MethodList);
1047  return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1048}
1049
1050void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1051  ASTContext &Context = CGM.getContext();
1052  std::string ProtocolName = PD->getNameAsString();
1053  llvm::SmallVector<std::string, 16> Protocols;
1054  for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1055       E = PD->protocol_end(); PI != E; ++PI)
1056    Protocols.push_back((*PI)->getNameAsString());
1057  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1058  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1059  llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1060  llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1061  for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1062       E = PD->instmeth_end(); iter != E; iter++) {
1063    std::string TypeStr;
1064    Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
1065    if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1066      InstanceMethodNames.push_back(
1067          MakeConstantString((*iter)->getSelector().getAsString()));
1068      InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1069    } else {
1070      OptionalInstanceMethodNames.push_back(
1071          MakeConstantString((*iter)->getSelector().getAsString()));
1072      OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1073    }
1074  }
1075  // Collect information about class methods:
1076  llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1077  llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1078  llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1079  llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1080  for (ObjCProtocolDecl::classmeth_iterator
1081         iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1082       iter != endIter ; iter++) {
1083    std::string TypeStr;
1084    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1085    if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1086      ClassMethodNames.push_back(
1087          MakeConstantString((*iter)->getSelector().getAsString()));
1088      ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1089    } else {
1090      OptionalClassMethodNames.push_back(
1091          MakeConstantString((*iter)->getSelector().getAsString()));
1092      OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1093    }
1094  }
1095
1096  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1097  llvm::Constant *InstanceMethodList =
1098    GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1099  llvm::Constant *ClassMethodList =
1100    GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1101  llvm::Constant *OptionalInstanceMethodList =
1102    GenerateProtocolMethodList(OptionalInstanceMethodNames,
1103            OptionalInstanceMethodTypes);
1104  llvm::Constant *OptionalClassMethodList =
1105    GenerateProtocolMethodList(OptionalClassMethodNames,
1106            OptionalClassMethodTypes);
1107
1108  // Property metadata: name, attributes, isSynthesized, setter name, setter
1109  // types, getter name, getter types.
1110  // The isSynthesized value is always set to 0 in a protocol.  It exists to
1111  // simplify the runtime library by allowing it to use the same data
1112  // structures for protocol metadata everywhere.
1113  llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1114          PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1115          PtrToInt8Ty, NULL);
1116  std::vector<llvm::Constant*> Properties;
1117  std::vector<llvm::Constant*> OptionalProperties;
1118
1119  // Add all of the property methods need adding to the method list and to the
1120  // property metadata list.
1121  for (ObjCContainerDecl::prop_iterator
1122         iter = PD->prop_begin(), endIter = PD->prop_end();
1123       iter != endIter ; iter++) {
1124    std::vector<llvm::Constant*> Fields;
1125    ObjCPropertyDecl *property = (*iter);
1126
1127    Fields.push_back(MakeConstantString(property->getNameAsString()));
1128    Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1129                property->getPropertyAttributes()));
1130    Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1131    if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1132      std::string TypeStr;
1133      Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1134      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1135      InstanceMethodTypes.push_back(TypeEncoding);
1136      Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1137      Fields.push_back(TypeEncoding);
1138    } else {
1139      Fields.push_back(NULLPtr);
1140      Fields.push_back(NULLPtr);
1141    }
1142    if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1143      std::string TypeStr;
1144      Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1145      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1146      InstanceMethodTypes.push_back(TypeEncoding);
1147      Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1148      Fields.push_back(TypeEncoding);
1149    } else {
1150      Fields.push_back(NULLPtr);
1151      Fields.push_back(NULLPtr);
1152    }
1153    if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1154      OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1155    } else {
1156      Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1157    }
1158  }
1159  llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1160      llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1161  llvm::Constant* PropertyListInitFields[] =
1162    {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1163
1164  llvm::Constant *PropertyListInit =
1165      llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
1166  llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1167      PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1168      PropertyListInit, ".objc_property_list");
1169
1170  llvm::Constant *OptionalPropertyArray =
1171      llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1172          OptionalProperties.size()) , OptionalProperties);
1173  llvm::Constant* OptionalPropertyListInitFields[] = {
1174      llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1175      OptionalPropertyArray };
1176
1177  llvm::Constant *OptionalPropertyListInit =
1178      llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
1179  llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1180          OptionalPropertyListInit->getType(), false,
1181          llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1182          ".objc_property_list");
1183
1184  // Protocols are objects containing lists of the methods implemented and
1185  // protocols adopted.
1186  llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
1187      PtrToInt8Ty,
1188      ProtocolList->getType(),
1189      InstanceMethodList->getType(),
1190      ClassMethodList->getType(),
1191      OptionalInstanceMethodList->getType(),
1192      OptionalClassMethodList->getType(),
1193      PropertyList->getType(),
1194      OptionalPropertyList->getType(),
1195      NULL);
1196  std::vector<llvm::Constant*> Elements;
1197  // The isa pointer must be set to a magic number so the runtime knows it's
1198  // the correct layout.
1199  int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1200      NonFragileProtocolVersion : ProtocolVersion;
1201  Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1202        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
1203  Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1204  Elements.push_back(ProtocolList);
1205  Elements.push_back(InstanceMethodList);
1206  Elements.push_back(ClassMethodList);
1207  Elements.push_back(OptionalInstanceMethodList);
1208  Elements.push_back(OptionalClassMethodList);
1209  Elements.push_back(PropertyList);
1210  Elements.push_back(OptionalPropertyList);
1211  ExistingProtocols[ProtocolName] =
1212    llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1213          ".objc_protocol"), IdTy);
1214}
1215void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1216  // Collect information about instance methods
1217  llvm::SmallVector<Selector, 1> MethodSels;
1218  llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1219
1220  std::vector<llvm::Constant*> Elements;
1221  const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1222  const std::string CategoryName = "AnotherHack";
1223  Elements.push_back(MakeConstantString(CategoryName));
1224  Elements.push_back(MakeConstantString(ClassName));
1225  // Instance method list
1226  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1227          ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1228  // Class method list
1229  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1230          ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1231  // Protocol list
1232  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1233      ExistingProtocols.size());
1234  llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1235      PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1236      LongTy,//FIXME: Should be size_t
1237      ProtocolArrayTy,
1238      NULL);
1239  std::vector<llvm::Constant*> ProtocolElements;
1240  for (llvm::StringMapIterator<llvm::Constant*> iter =
1241       ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1242       iter != endIter ; iter++) {
1243    llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1244            PtrTy);
1245    ProtocolElements.push_back(Ptr);
1246  }
1247  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1248      ProtocolElements);
1249  ProtocolElements.clear();
1250  ProtocolElements.push_back(NULLPtr);
1251  ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1252              ExistingProtocols.size()));
1253  ProtocolElements.push_back(ProtocolArray);
1254  Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1255                  ProtocolElements, ".objc_protocol_list"), PtrTy));
1256  Categories.push_back(llvm::ConstantExpr::getBitCast(
1257        MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1258            PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1259}
1260
1261void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1262  std::string ClassName = OCD->getClassInterface()->getNameAsString();
1263  std::string CategoryName = OCD->getNameAsString();
1264  // Collect information about instance methods
1265  llvm::SmallVector<Selector, 16> InstanceMethodSels;
1266  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1267  for (ObjCCategoryImplDecl::instmeth_iterator
1268         iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
1269       iter != endIter ; iter++) {
1270    InstanceMethodSels.push_back((*iter)->getSelector());
1271    std::string TypeStr;
1272    CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
1273    InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1274  }
1275
1276  // Collect information about class methods
1277  llvm::SmallVector<Selector, 16> ClassMethodSels;
1278  llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1279  for (ObjCCategoryImplDecl::classmeth_iterator
1280         iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
1281       iter != endIter ; iter++) {
1282    ClassMethodSels.push_back((*iter)->getSelector());
1283    std::string TypeStr;
1284    CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
1285    ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1286  }
1287
1288  // Collect the names of referenced protocols
1289  llvm::SmallVector<std::string, 16> Protocols;
1290  const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1291  const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
1292  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1293       E = Protos.end(); I != E; ++I)
1294    Protocols.push_back((*I)->getNameAsString());
1295
1296  std::vector<llvm::Constant*> Elements;
1297  Elements.push_back(MakeConstantString(CategoryName));
1298  Elements.push_back(MakeConstantString(ClassName));
1299  // Instance method list
1300  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1301          ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
1302          false), PtrTy));
1303  // Class method list
1304  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1305          ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
1306        PtrTy));
1307  // Protocol list
1308  Elements.push_back(llvm::ConstantExpr::getBitCast(
1309        GenerateProtocolList(Protocols), PtrTy));
1310  Categories.push_back(llvm::ConstantExpr::getBitCast(
1311        MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1312            PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1313}
1314
1315llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1316        llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1317        llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1318  ASTContext &Context = CGM.getContext();
1319  //
1320  // Property metadata: name, attributes, isSynthesized, setter name, setter
1321  // types, getter name, getter types.
1322  llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1323          PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1324          PtrToInt8Ty, NULL);
1325  std::vector<llvm::Constant*> Properties;
1326
1327
1328  // Add all of the property methods need adding to the method list and to the
1329  // property metadata list.
1330  for (ObjCImplDecl::propimpl_iterator
1331         iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1332       iter != endIter ; iter++) {
1333    std::vector<llvm::Constant*> Fields;
1334    ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
1335    ObjCPropertyImplDecl *propertyImpl = *iter;
1336    bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1337        ObjCPropertyImplDecl::Synthesize);
1338
1339    Fields.push_back(MakeConstantString(property->getNameAsString()));
1340    Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1341                property->getPropertyAttributes()));
1342    Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
1343    if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1344      std::string TypeStr;
1345      Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1346      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1347      if (isSynthesized) {
1348        InstanceMethodTypes.push_back(TypeEncoding);
1349        InstanceMethodSels.push_back(getter->getSelector());
1350      }
1351      Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1352      Fields.push_back(TypeEncoding);
1353    } else {
1354      Fields.push_back(NULLPtr);
1355      Fields.push_back(NULLPtr);
1356    }
1357    if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1358      std::string TypeStr;
1359      Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1360      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1361      if (isSynthesized) {
1362        InstanceMethodTypes.push_back(TypeEncoding);
1363        InstanceMethodSels.push_back(setter->getSelector());
1364      }
1365      Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1366      Fields.push_back(TypeEncoding);
1367    } else {
1368      Fields.push_back(NULLPtr);
1369      Fields.push_back(NULLPtr);
1370    }
1371    Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1372  }
1373  llvm::ArrayType *PropertyArrayTy =
1374      llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1375  llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1376          Properties);
1377  llvm::Constant* PropertyListInitFields[] =
1378    {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1379
1380  llvm::Constant *PropertyListInit =
1381      llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
1382  return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1383          llvm::GlobalValue::InternalLinkage, PropertyListInit,
1384          ".objc_property_list");
1385}
1386
1387void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1388  ASTContext &Context = CGM.getContext();
1389
1390  // Get the superclass name.
1391  const ObjCInterfaceDecl * SuperClassDecl =
1392    OID->getClassInterface()->getSuperClass();
1393  std::string SuperClassName;
1394  if (SuperClassDecl) {
1395    SuperClassName = SuperClassDecl->getNameAsString();
1396    EmitClassRef(SuperClassName);
1397  }
1398
1399  // Get the class name
1400  ObjCInterfaceDecl *ClassDecl =
1401    const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1402  std::string ClassName = ClassDecl->getNameAsString();
1403  // Emit the symbol that is used to generate linker errors if this class is
1404  // referenced in other modules but not declared.
1405  std::string classSymbolName = "__objc_class_name_" + ClassName;
1406  if (llvm::GlobalVariable *symbol =
1407      TheModule.getGlobalVariable(classSymbolName)) {
1408    symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
1409  } else {
1410    new llvm::GlobalVariable(TheModule, LongTy, false,
1411    llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
1412    classSymbolName);
1413  }
1414
1415  // Get the size of instances.
1416  int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
1417
1418  // Collect information about instance variables.
1419  llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1420  llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1421  llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
1422
1423  std::vector<llvm::Constant*> IvarOffsetValues;
1424
1425  int superInstanceSize = !SuperClassDecl ? 0 :
1426    Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1427  // For non-fragile ivars, set the instance size to 0 - {the size of just this
1428  // class}.  The runtime will then set this to the correct value on load.
1429  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1430    instanceSize = 0 - (instanceSize - superInstanceSize);
1431  }
1432
1433  // Collect declared and synthesized ivars.
1434  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1435  CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1436
1437  for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1438      ObjCIvarDecl *IVD = OIvars[i];
1439      // Store the name
1440      IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
1441      // Get the type encoding for this ivar
1442      std::string TypeStr;
1443      Context.getObjCEncodingForType(IVD->getType(), TypeStr);
1444      IvarTypes.push_back(MakeConstantString(TypeStr));
1445      // Get the offset
1446      uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1447      uint64_t Offset = BaseOffset;
1448      if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1449        Offset = BaseOffset - superInstanceSize;
1450      }
1451      IvarOffsets.push_back(
1452          llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
1453      IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1454          false, llvm::GlobalValue::ExternalLinkage,
1455          llvm::ConstantInt::get(IntTy, BaseOffset),
1456          "__objc_ivar_offset_value_" + ClassName +"." +
1457          IVD->getNameAsString()));
1458  }
1459  llvm::Constant *IvarOffsetArrayInit =
1460      llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1461                  IvarOffsetValues.size()), IvarOffsetValues);
1462  llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1463          IvarOffsetArrayInit->getType(), false,
1464          llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1465          ".ivar.offsets");
1466
1467  // Collect information about instance methods
1468  llvm::SmallVector<Selector, 16> InstanceMethodSels;
1469  llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1470  for (ObjCImplementationDecl::instmeth_iterator
1471         iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
1472       iter != endIter ; iter++) {
1473    InstanceMethodSels.push_back((*iter)->getSelector());
1474    std::string TypeStr;
1475    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1476    InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1477  }
1478
1479  llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1480          InstanceMethodTypes);
1481
1482
1483  // Collect information about class methods
1484  llvm::SmallVector<Selector, 16> ClassMethodSels;
1485  llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1486  for (ObjCImplementationDecl::classmeth_iterator
1487         iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
1488       iter != endIter ; iter++) {
1489    ClassMethodSels.push_back((*iter)->getSelector());
1490    std::string TypeStr;
1491    Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1492    ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1493  }
1494  // Collect the names of referenced protocols
1495  llvm::SmallVector<std::string, 16> Protocols;
1496  const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1497  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1498       E = Protos.end(); I != E; ++I)
1499    Protocols.push_back((*I)->getNameAsString());
1500
1501
1502
1503  // Get the superclass pointer.
1504  llvm::Constant *SuperClass;
1505  if (!SuperClassName.empty()) {
1506    SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1507  } else {
1508    SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
1509  }
1510  // Empty vector used to construct empty method lists
1511  llvm::SmallVector<llvm::Constant*, 1>  empty;
1512  // Generate the method and instance variable lists
1513  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
1514      InstanceMethodSels, InstanceMethodTypes, false);
1515  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
1516      ClassMethodSels, ClassMethodTypes, true);
1517  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1518      IvarOffsets);
1519  // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
1520  // we emit a symbol containing the offset for each ivar in the class.  This
1521  // allows code compiled for the non-Fragile ABI to inherit from code compiled
1522  // for the legacy ABI, without causing problems.  The converse is also
1523  // possible, but causes all ivar accesses to be fragile.
1524  int i = 0;
1525  // Offset pointer for getting at the correct field in the ivar list when
1526  // setting up the alias.  These are: The base address for the global, the
1527  // ivar array (second field), the ivar in this list (set for each ivar), and
1528  // the offset (third field in ivar structure)
1529  const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1530  llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
1531      llvm::ConstantInt::get(IndexTy, 1), 0,
1532      llvm::ConstantInt::get(IndexTy, 2) };
1533
1534  for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1535      endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1536      const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1537          +(*iter)->getNameAsString();
1538      offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++);
1539      // Get the correct ivar field
1540      llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1541              IvarList, offsetPointerIndexes, 4);
1542      // Get the existing alias, if one exists.
1543      llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1544      if (offset) {
1545          offset->setInitializer(offsetValue);
1546          // If this is the real definition, change its linkage type so that
1547          // different modules will use this one, rather than their private
1548          // copy.
1549          offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1550      } else {
1551          // Add a new alias if there isn't one already.
1552          offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1553                  false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1554      }
1555  }
1556  //Generate metaclass for class methods
1557  llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
1558      NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
1559        empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
1560
1561  // Generate the class structure
1562  llvm::Constant *ClassStruct =
1563    GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
1564                           ClassName.c_str(), 0,
1565      llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
1566      MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1567      Properties);
1568
1569  // Resolve the class aliases, if they exist.
1570  if (ClassPtrAlias) {
1571    ClassPtrAlias->setAliasee(
1572        llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
1573    ClassPtrAlias = 0;
1574  }
1575  if (MetaClassPtrAlias) {
1576    MetaClassPtrAlias->setAliasee(
1577        llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
1578    MetaClassPtrAlias = 0;
1579  }
1580
1581  // Add class structure to list to be added to the symtab later
1582  ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
1583  Classes.push_back(ClassStruct);
1584}
1585
1586
1587llvm::Function *CGObjCGNU::ModuleInitFunction() {
1588  // Only emit an ObjC load function if no Objective-C stuff has been called
1589  if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1590      ExistingProtocols.empty() && TypedSelectors.empty() &&
1591      UntypedSelectors.empty())
1592    return NULL;
1593
1594  // Add all referenced protocols to a category.
1595  GenerateProtocolHolderCategory();
1596
1597  const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1598          SelectorTy->getElementType());
1599  const llvm::Type *SelStructPtrTy = SelectorTy;
1600  bool isSelOpaque = false;
1601  if (SelStructTy == 0) {
1602    SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1603                                        PtrToInt8Ty, NULL);
1604    SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
1605    isSelOpaque = true;
1606  }
1607
1608  // Name the ObjC types to make the IR a bit easier to read
1609  TheModule.addTypeName(".objc_selector", SelStructPtrTy);
1610  TheModule.addTypeName(".objc_id", IdTy);
1611  TheModule.addTypeName(".objc_imp", IMPTy);
1612
1613  std::vector<llvm::Constant*> Elements;
1614  llvm::Constant *Statics = NULLPtr;
1615  // Generate statics list:
1616  if (ConstantStrings.size()) {
1617    llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1618        ConstantStrings.size() + 1);
1619    ConstantStrings.push_back(NULLPtr);
1620
1621    llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1622    if (StringClass.empty()) StringClass = "NXConstantString";
1623    Elements.push_back(MakeConstantString(StringClass,
1624                ".objc_static_class_name"));
1625    Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
1626       ConstantStrings));
1627    llvm::StructType *StaticsListTy =
1628      llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
1629    llvm::Type *StaticsListPtrTy =
1630      llvm::PointerType::getUnqual(StaticsListTy);
1631    Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
1632    llvm::ArrayType *StaticsListArrayTy =
1633      llvm::ArrayType::get(StaticsListPtrTy, 2);
1634    Elements.clear();
1635    Elements.push_back(Statics);
1636    Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
1637    Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
1638    Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
1639  }
1640  // Array of classes, categories, and constant objects
1641  llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
1642      Classes.size() + Categories.size()  + 2);
1643  llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
1644                                                     LongTy, SelStructPtrTy,
1645                                                     llvm::Type::getInt16Ty(VMContext),
1646                                                     llvm::Type::getInt16Ty(VMContext),
1647                                                     ClassListTy, NULL);
1648
1649  Elements.clear();
1650  // Pointer to an array of selectors used in this module.
1651  std::vector<llvm::Constant*> Selectors;
1652  for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1653     iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1654     iter != iterEnd ; ++iter) {
1655    Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
1656    Elements.push_back(MakeConstantString(iter->first.second,
1657                                          ".objc_sel_types"));
1658    Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1659    Elements.clear();
1660  }
1661  for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1662      iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1663      iter != iterEnd; ++iter) {
1664    Elements.push_back(
1665        ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
1666    Elements.push_back(NULLPtr);
1667    Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1668    Elements.clear();
1669  }
1670  Elements.push_back(NULLPtr);
1671  Elements.push_back(NULLPtr);
1672  Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1673  Elements.clear();
1674  // Number of static selectors
1675  Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
1676  llvm::Constant *SelectorList = MakeGlobal(
1677          llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
1678          ".objc_selector_list");
1679  Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
1680    SelStructPtrTy));
1681
1682  // Now that all of the static selectors exist, create pointers to them.
1683  int index = 0;
1684  for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1685     iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1686     iter != iterEnd; ++iter) {
1687    llvm::Constant *Idxs[] = {Zeros[0],
1688      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
1689    llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
1690      true, llvm::GlobalValue::LinkOnceODRLinkage,
1691      llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1692      MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1693         iter->first.second));
1694    // If selectors are defined as an opaque type, cast the pointer to this
1695    // type.
1696    if (isSelOpaque) {
1697      SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1698        llvm::PointerType::getUnqual(SelectorTy));
1699    }
1700    (*iter).second->replaceAllUsesWith(SelPtr);
1701    (*iter).second->eraseFromParent();
1702  }
1703  for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1704      iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1705      iter != iterEnd; iter++) {
1706    llvm::Constant *Idxs[] = {Zeros[0],
1707      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
1708    llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
1709      true, llvm::GlobalValue::LinkOnceODRLinkage,
1710      llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1711      MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
1712    // If selectors are defined as an opaque type, cast the pointer to this
1713    // type.
1714    if (isSelOpaque) {
1715      SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1716        llvm::PointerType::getUnqual(SelectorTy));
1717    }
1718    (*iter).second->replaceAllUsesWith(SelPtr);
1719    (*iter).second->eraseFromParent();
1720  }
1721  // Number of classes defined.
1722  Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
1723        Classes.size()));
1724  // Number of categories defined
1725  Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
1726        Categories.size()));
1727  // Create an array of classes, then categories, then static object instances
1728  Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1729  //  NULL-terminated list of static object instances (mainly constant strings)
1730  Classes.push_back(Statics);
1731  Classes.push_back(NULLPtr);
1732  llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
1733  Elements.push_back(ClassList);
1734  // Construct the symbol table
1735  llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1736
1737  // The symbol table is contained in a module which has some version-checking
1738  // constants
1739  llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
1740      PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
1741  Elements.clear();
1742  // Runtime version used for compatibility checking.
1743  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1744    Elements.push_back(llvm::ConstantInt::get(LongTy,
1745        NonFragileRuntimeVersion));
1746  } else {
1747    Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
1748  }
1749  // sizeof(ModuleTy)
1750  llvm::TargetData td(&TheModule);
1751  Elements.push_back(llvm::ConstantInt::get(LongTy,
1752                     td.getTypeSizeInBits(ModuleTy)/8));
1753  //FIXME: Should be the path to the file where this module was declared
1754  Elements.push_back(NULLPtr);
1755  Elements.push_back(SymTab);
1756  llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1757
1758  // Create the load function calling the runtime entry point with the module
1759  // structure
1760  llvm::Function * LoadFunction = llvm::Function::Create(
1761      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1762      llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1763      &TheModule);
1764  llvm::BasicBlock *EntryBB =
1765      llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1766  CGBuilderTy Builder(VMContext);
1767  Builder.SetInsertPoint(EntryBB);
1768
1769  std::vector<const llvm::Type*> Params(1,
1770      llvm::PointerType::getUnqual(ModuleTy));
1771  llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1772        llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
1773  Builder.CreateCall(Register, Module);
1774  Builder.CreateRetVoid();
1775
1776  return LoadFunction;
1777}
1778
1779llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
1780                                          const ObjCContainerDecl *CD) {
1781  const ObjCCategoryImplDecl *OCD =
1782    dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
1783  std::string CategoryName = OCD ? OCD->getNameAsString() : "";
1784  std::string ClassName = CD->getName();
1785  std::string MethodName = OMD->getSelector().getAsString();
1786  bool isClassMethod = !OMD->isInstanceMethod();
1787
1788  CodeGenTypes &Types = CGM.getTypes();
1789  const llvm::FunctionType *MethodTy =
1790    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
1791  std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1792      MethodName, isClassMethod);
1793
1794  llvm::Function *Method
1795    = llvm::Function::Create(MethodTy,
1796                             llvm::GlobalValue::InternalLinkage,
1797                             FunctionName,
1798                             &TheModule);
1799  return Method;
1800}
1801
1802llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
1803  std::vector<const llvm::Type*> Params;
1804  const llvm::Type *BoolTy =
1805    CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1806  Params.push_back(IdTy);
1807  Params.push_back(SelectorTy);
1808  Params.push_back(IntTy);
1809  Params.push_back(BoolTy);
1810  // void objc_getProperty (id, SEL, int, bool)
1811  const llvm::FunctionType *FTy =
1812    llvm::FunctionType::get(IdTy, Params, false);
1813  return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1814                                                        "objc_getProperty"));
1815}
1816
1817llvm::Function *CGObjCGNU::GetPropertySetFunction() {
1818  std::vector<const llvm::Type*> Params;
1819  const llvm::Type *BoolTy =
1820    CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1821  Params.push_back(IdTy);
1822  Params.push_back(SelectorTy);
1823  Params.push_back(IntTy);
1824  Params.push_back(IdTy);
1825  Params.push_back(BoolTy);
1826  Params.push_back(BoolTy);
1827  // void objc_setProperty (id, SEL, int, id, bool, bool)
1828  const llvm::FunctionType *FTy =
1829    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1830  return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1831                                                        "objc_setProperty"));
1832}
1833
1834// FIXME. Implement this.
1835llvm::Function *CGObjCGNU::GetCopyStructFunction() {
1836  return 0;
1837}
1838
1839llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1840  CodeGen::CodeGenTypes &Types = CGM.getTypes();
1841  ASTContext &Ctx = CGM.getContext();
1842  // void objc_enumerationMutation (id)
1843  llvm::SmallVector<CanQualType,1> Params;
1844  Params.push_back(ASTIdTy);
1845  const llvm::FunctionType *FTy =
1846    Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
1847                                              FunctionType::ExtInfo()), false);
1848  return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
1849}
1850
1851void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1852                                          const Stmt &S) {
1853  // Pointer to the personality function
1854  llvm::Constant *Personality =
1855    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(VMContext),
1856          true),
1857        "__gnu_objc_personality_v0");
1858  Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
1859  std::vector<const llvm::Type*> Params;
1860  Params.push_back(PtrTy);
1861  llvm::Value *RethrowFn =
1862    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
1863          Params, false), "_Unwind_Resume");
1864
1865  bool isTry = isa<ObjCAtTryStmt>(S);
1866  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1867  llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1868  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1869  llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
1870  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1871  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1872  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1873
1874  // @synchronized()
1875  if (!isTry) {
1876    std::vector<const llvm::Type*> Args(1, IdTy);
1877    llvm::FunctionType *FTy =
1878      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
1879    llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1880    llvm::Value *SyncArg =
1881      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1882    SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1883    CGF.Builder.CreateCall(SyncEnter, SyncArg);
1884  }
1885
1886
1887  // Push an EH context entry, used for handling rethrows and jumps
1888  // through finally.
1889  CGF.PushCleanupBlock(FinallyBlock);
1890
1891  // Emit the statements in the @try {} block
1892  CGF.setInvokeDest(TryHandler);
1893
1894  CGF.EmitBlock(TryBlock);
1895  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1896                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1897
1898  // Jump to @finally if there is no exception
1899  CGF.EmitBranchThroughCleanup(FinallyEnd);
1900
1901  // Emit the handlers
1902  CGF.EmitBlock(TryHandler);
1903
1904  // Get the correct versions of the exception handling intrinsics
1905  llvm::Value *llvm_eh_exception =
1906    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
1907  llvm::Value *llvm_eh_selector =
1908    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
1909  llvm::Value *llvm_eh_typeid_for =
1910    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1911
1912  // Exception object
1913  llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1914  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1915
1916  llvm::SmallVector<llvm::Value*, 8> ESelArgs;
1917  llvm::SmallVector<std::pair<const VarDecl*, const Stmt*>, 8> Handlers;
1918
1919  ESelArgs.push_back(Exc);
1920  ESelArgs.push_back(Personality);
1921
1922  bool HasCatchAll = false;
1923  // Only @try blocks are allowed @catch blocks, but both can have @finally
1924  if (isTry) {
1925    if (cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
1926      const ObjCAtTryStmt &AtTry = cast<ObjCAtTryStmt>(S);
1927      CGF.setInvokeDest(CatchInCatch);
1928
1929      for (unsigned I = 0, N = AtTry.getNumCatchStmts(); I != N; ++I) {
1930        const ObjCAtCatchStmt *CatchStmt = AtTry.getCatchStmt(I);
1931        const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1932        Handlers.push_back(std::make_pair(CatchDecl,
1933                                          CatchStmt->getCatchBody()));
1934
1935        // @catch() and @catch(id) both catch any ObjC exception
1936        if (!CatchDecl || CatchDecl->getType()->isObjCIdType()
1937            || CatchDecl->getType()->isObjCQualifiedIdType()) {
1938          // Use i8* null here to signal this is a catch all, not a cleanup.
1939          ESelArgs.push_back(NULLPtr);
1940          HasCatchAll = true;
1941          // No further catches after this one will ever by reached
1942          break;
1943        }
1944
1945        // All other types should be Objective-C interface pointer types.
1946        const ObjCObjectPointerType *OPT =
1947          CatchDecl->getType()->getAs<ObjCObjectPointerType>();
1948        assert(OPT && "Invalid @catch type.");
1949        const ObjCInterfaceDecl *IDecl =
1950          OPT->getObjectType()->getInterface();
1951        assert(IDecl && "Invalid @catch type.");
1952        llvm::Value *EHType =
1953          MakeConstantString(IDecl->getNameAsString());
1954        ESelArgs.push_back(EHType);
1955      }
1956    }
1957  }
1958
1959  // We use a cleanup unless there was already a catch all.
1960  if (!HasCatchAll) {
1961    ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
1962    Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1963  }
1964
1965  // Find which handler was matched.
1966  llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
1967      ESelArgs.begin(), ESelArgs.end(), "selector");
1968
1969  for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
1970    const VarDecl *CatchParam = Handlers[i].first;
1971    const Stmt *CatchBody = Handlers[i].second;
1972
1973    llvm::BasicBlock *Next = 0;
1974
1975    // The last handler always matches.
1976    if (i + 1 != e) {
1977      assert(CatchParam && "Only last handler can be a catch all.");
1978
1979      // Test whether this block matches the type for the selector and branch
1980      // to Match if it does, or to the next BB if it doesn't.
1981      llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1982      Next = CGF.createBasicBlock("catch.next");
1983      llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
1984          CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1985      CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1986          Next);
1987
1988      CGF.EmitBlock(Match);
1989    }
1990
1991    if (CatchBody) {
1992      llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1993          CGF.ConvertType(CatchParam->getType()));
1994
1995      // Bind the catch parameter if it exists.
1996      if (CatchParam) {
1997        // CatchParam is a ParmVarDecl because of the grammar
1998        // construction used to handle this, but for codegen purposes
1999        // we treat this as a local decl.
2000        CGF.EmitLocalBlockVarDecl(*CatchParam);
2001        CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
2002      }
2003
2004      CGF.ObjCEHValueStack.push_back(ExcObject);
2005      CGF.EmitStmt(CatchBody);
2006      CGF.ObjCEHValueStack.pop_back();
2007
2008      CGF.EmitBranchThroughCleanup(FinallyEnd);
2009
2010      if (Next)
2011        CGF.EmitBlock(Next);
2012    } else {
2013      assert(!Next && "catchup should be last handler.");
2014
2015      CGF.Builder.CreateStore(Exc, RethrowPtr);
2016      CGF.EmitBranchThroughCleanup(FinallyRethrow);
2017    }
2018  }
2019  // The @finally block is a secondary landing pad for any exceptions thrown in
2020  // @catch() blocks
2021  CGF.EmitBlock(CatchInCatch);
2022  Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
2023  ESelArgs.clear();
2024  ESelArgs.push_back(Exc);
2025  ESelArgs.push_back(Personality);
2026  // If there is a @catch or @finally clause in outside of this one then we
2027  // need to make sure that we catch and rethrow it.
2028  if (PrevLandingPad) {
2029    ESelArgs.push_back(NULLPtr);
2030  } else {
2031    ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
2032  }
2033  CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
2034      "selector");
2035  CGF.Builder.CreateCall(llvm_eh_typeid_for,
2036      CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
2037  CGF.Builder.CreateStore(Exc, RethrowPtr);
2038  CGF.EmitBranchThroughCleanup(FinallyRethrow);
2039
2040  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2041
2042  CGF.setInvokeDest(PrevLandingPad);
2043
2044  CGF.EmitBlock(FinallyBlock);
2045
2046
2047  if (isTry) {
2048    if (const ObjCAtFinallyStmt* FinallyStmt =
2049        cast<ObjCAtTryStmt>(S).getFinallyStmt())
2050      CGF.EmitStmt(FinallyStmt->getFinallyBody());
2051  } else {
2052    // Emit 'objc_sync_exit(expr)' as finally's sole statement for
2053    // @synchronized.
2054    std::vector<const llvm::Type*> Args(1, IdTy);
2055    llvm::FunctionType *FTy =
2056      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
2057    llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
2058    llvm::Value *SyncArg =
2059      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2060    SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
2061    CGF.Builder.CreateCall(SyncExit, SyncArg);
2062  }
2063
2064  if (Info.SwitchBlock)
2065    CGF.EmitBlock(Info.SwitchBlock);
2066  if (Info.EndBlock)
2067    CGF.EmitBlock(Info.EndBlock);
2068
2069  // Branch around the rethrow code.
2070  CGF.EmitBranch(FinallyEnd);
2071
2072  CGF.EmitBlock(FinallyRethrow);
2073
2074  llvm::Value *ExceptionObject = CGF.Builder.CreateLoad(RethrowPtr);
2075  llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2076  if (!UnwindBB) {
2077    CGF.Builder.CreateCall(RethrowFn, ExceptionObject);
2078    // Exception always thrown, next instruction is never reached.
2079    CGF.Builder.CreateUnreachable();
2080  } else {
2081    // If there is a @catch block outside this scope, we invoke instead of
2082    // calling because we may return to this function.  This is very slow, but
2083    // some people still do it.  It would be nice to add an optimised path for
2084    // this.
2085    CGF.Builder.CreateInvoke(RethrowFn, UnwindBB, UnwindBB, &ExceptionObject,
2086        &ExceptionObject+1);
2087  }
2088
2089  CGF.EmitBlock(FinallyEnd);
2090}
2091
2092void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
2093                              const ObjCAtThrowStmt &S) {
2094  llvm::Value *ExceptionAsObject;
2095
2096  std::vector<const llvm::Type*> Args(1, IdTy);
2097  llvm::FunctionType *FTy =
2098    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
2099  llvm::Value *ThrowFn =
2100    CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
2101
2102  if (const Expr *ThrowExpr = S.getThrowExpr()) {
2103    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2104    ExceptionAsObject = Exception;
2105  } else {
2106    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2107           "Unexpected rethrow outside @catch block.");
2108    ExceptionAsObject = CGF.ObjCEHValueStack.back();
2109  }
2110  ExceptionAsObject =
2111      CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
2112
2113  // Note: This may have to be an invoke, if we want to support constructs like:
2114  // @try {
2115  //  @throw(obj);
2116  // }
2117  // @catch(id) ...
2118  //
2119  // This is effectively turning @throw into an incredibly-expensive goto, but
2120  // it may happen as a result of inlining followed by missed optimizations, or
2121  // as a result of stupidity.
2122  llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2123  if (!UnwindBB) {
2124    CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2125    CGF.Builder.CreateUnreachable();
2126  } else {
2127    CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2128        &ExceptionAsObject+1);
2129  }
2130  // Clear the insertion point to indicate we are in unreachable code.
2131  CGF.Builder.ClearInsertionPoint();
2132}
2133
2134llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
2135                                          llvm::Value *AddrWeakObj) {
2136  CGBuilderTy B = CGF.Builder;
2137  AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2138  return B.CreateCall(WeakReadFn, AddrWeakObj);
2139}
2140
2141void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2142                                   llvm::Value *src, llvm::Value *dst) {
2143  CGBuilderTy B = CGF.Builder;
2144  src = EnforceType(B, src, IdTy);
2145  dst = EnforceType(B, dst, PtrToIdTy);
2146  B.CreateCall2(WeakAssignFn, src, dst);
2147}
2148
2149void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2150                                     llvm::Value *src, llvm::Value *dst) {
2151  CGBuilderTy B = CGF.Builder;
2152  src = EnforceType(B, src, IdTy);
2153  dst = EnforceType(B, dst, PtrToIdTy);
2154  B.CreateCall2(GlobalAssignFn, src, dst);
2155}
2156
2157void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2158                                   llvm::Value *src, llvm::Value *dst,
2159                                   llvm::Value *ivarOffset) {
2160  CGBuilderTy B = CGF.Builder;
2161  src = EnforceType(B, src, IdTy);
2162  dst = EnforceType(B, dst, PtrToIdTy);
2163  B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
2164}
2165
2166void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2167                                         llvm::Value *src, llvm::Value *dst) {
2168  CGBuilderTy B = CGF.Builder;
2169  src = EnforceType(B, src, IdTy);
2170  dst = EnforceType(B, dst, PtrToIdTy);
2171  B.CreateCall2(StrongCastAssignFn, src, dst);
2172}
2173
2174void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
2175                                         llvm::Value *DestPtr,
2176                                         llvm::Value *SrcPtr,
2177                                         QualType Ty) {
2178  CGBuilderTy B = CGF.Builder;
2179  DestPtr = EnforceType(B, DestPtr, IdTy);
2180  SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2181
2182  std::pair<uint64_t, unsigned> TypeInfo = CGM.getContext().getTypeInfo(Ty);
2183  unsigned long size = TypeInfo.first/8;
2184  // FIXME: size_t
2185  llvm::Value *N = llvm::ConstantInt::get(LongTy, size);
2186
2187  B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, N);
2188}
2189
2190llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2191                              const ObjCInterfaceDecl *ID,
2192                              const ObjCIvarDecl *Ivar) {
2193  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2194    + '.' + Ivar->getNameAsString();
2195  // Emit the variable and initialize it with what we think the correct value
2196  // is.  This allows code compiled with non-fragile ivars to work correctly
2197  // when linked against code which isn't (most of the time).
2198  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2199  if (!IvarOffsetPointer) {
2200    uint64_t Offset;
2201    if (ObjCImplementationDecl *OID =
2202            CGM.getContext().getObjCImplementation(
2203              const_cast<ObjCInterfaceDecl *>(ID)))
2204      Offset = ComputeIvarBaseOffset(CGM, OID, Ivar);
2205    else
2206      Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2207
2208    llvm::ConstantInt *OffsetGuess =
2209      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
2210    // Don't emit the guess in non-PIC code because the linker will not be able
2211    // to replace it with the real version for a library.  In non-PIC code you
2212    // must compile with the fragile ABI if you want to use ivars from a
2213    // GCC-compiled class.
2214    if (CGM.getLangOptions().PICLevel) {
2215      llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2216            llvm::Type::getInt32Ty(VMContext), false,
2217            llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2218      IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2219            IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2220            IvarOffsetGV, Name);
2221    } else {
2222      IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2223              llvm::Type::getInt32PtrTy(VMContext), false,
2224              llvm::GlobalValue::ExternalLinkage, 0, Name);
2225    }
2226  }
2227  return IvarOffsetPointer;
2228}
2229
2230LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2231                                       QualType ObjectTy,
2232                                       llvm::Value *BaseValue,
2233                                       const ObjCIvarDecl *Ivar,
2234                                       unsigned CVRQualifiers) {
2235  const ObjCInterfaceDecl *ID =
2236    ObjectTy->getAs<ObjCObjectType>()->getInterface();
2237  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2238                                  EmitIvarOffset(CGF, ID, Ivar));
2239}
2240
2241static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2242                                                  const ObjCInterfaceDecl *OID,
2243                                                  const ObjCIvarDecl *OIVD) {
2244  llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
2245  Context.ShallowCollectObjCIvars(OID, Ivars);
2246  for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2247    if (OIVD == Ivars[k])
2248      return OID;
2249  }
2250
2251  // Otherwise check in the super class.
2252  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2253    return FindIvarInterface(Context, Super, OIVD);
2254
2255  return 0;
2256}
2257
2258llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2259                         const ObjCInterfaceDecl *Interface,
2260                         const ObjCIvarDecl *Ivar) {
2261  if (CGM.getLangOptions().ObjCNonFragileABI) {
2262    Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2263    return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2264                ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
2265  }
2266  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2267  return llvm::ConstantInt::get(LongTy, Offset, "ivar");
2268}
2269
2270CodeGen::CGObjCRuntime *
2271CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
2272  return new CGObjCGNU(CGM);
2273}
2274