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