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