CGObjCMac.cpp revision 9f89f2bc111339ee7fa0df3c2f18e39493b460c4
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
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 Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
15
16#include "CodeGenModule.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/AST/StmtObjC.h"
23#include "clang/Basic/LangOptions.h"
24
25#include "llvm/Intrinsics.h"
26#include "llvm/Module.h"
27#include "llvm/ADT/DenseSet.h"
28#include "llvm/Target/TargetData.h"
29#include <sstream>
30
31using namespace clang;
32using namespace CodeGen;
33
34// Common CGObjCRuntime functions, these don't belong here, but they
35// don't belong in CGObjCRuntime either so we will live with it for
36// now.
37
38static const llvm::StructType *
39GetConcreteClassStruct(CodeGen::CodeGenModule &CGM,
40                       const ObjCInterfaceDecl *OID) {
41  assert(!OID->isForwardDecl() && "Invalid interface decl!");
42  const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
43  return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
44}
45
46
47/// LookupFieldDeclForIvar - looks up a field decl in the laid out
48/// storage which matches this 'ivar'.
49///
50static const FieldDecl *LookupFieldDeclForIvar(ASTContext &Context,
51                                               const ObjCInterfaceDecl *OID,
52                                               const ObjCIvarDecl *OIVD,
53                                               const ObjCInterfaceDecl *&Found) {
54  assert(!OID->isForwardDecl() && "Invalid interface decl!");
55  const RecordDecl *RecordForDecl = Context.addRecordToClass(OID);
56  assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class");
57  DeclContext::lookup_const_result Lookup =
58    RecordForDecl->lookup(Context, OIVD->getDeclName());
59
60  if (Lookup.first != Lookup.second) {
61    Found = OID;
62    return cast<FieldDecl>(*Lookup.first);
63  }
64
65  // If lookup failed, try the superclass.
66  //
67  // FIXME: This is slow, we shouldn't need to do this.
68  const ObjCInterfaceDecl *Super = OID->getSuperClass();
69  assert(Super && "field decl not found!");
70  return LookupFieldDeclForIvar(Context, Super, OIVD, Found);
71}
72
73static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
74                                     const ObjCInterfaceDecl *OID,
75                                     const ObjCImplementationDecl *ID,
76                                     const ObjCIvarDecl *Ivar) {
77  assert(!OID->isForwardDecl() && "Invalid interface decl!");
78  const ObjCInterfaceDecl *Container;
79  const FieldDecl *Field =
80    LookupFieldDeclForIvar(CGM.getContext(), OID, Ivar, Container);
81  const llvm::StructType *STy =
82    GetConcreteClassStruct(CGM, Container);
83  const llvm::StructLayout *Layout =
84    CGM.getTargetData().getStructLayout(STy);
85  if (!Field->isBitField())
86    return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field)) * 8;
87
88  // FIXME. Must be a better way of getting a bitfield base offset.
89  CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
90  // FIXME: The "field no" for bitfields is something completely
91  // different; it is the offset in multiples of the base type size!
92  uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
93  const llvm::Type *Ty =
94    CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
95  Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
96  return Offset + BFI.Begin;
97}
98
99uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
100                                              const ObjCInterfaceDecl *OID,
101                                              const ObjCIvarDecl *Ivar) {
102  return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
103}
104
105uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
106                                              const ObjCImplementationDecl *OID,
107                                              const ObjCIvarDecl *Ivar) {
108  return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
109}
110
111LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
112                                               const ObjCInterfaceDecl *OID,
113                                               llvm::Value *BaseValue,
114                                               const ObjCIvarDecl *Ivar,
115                                               unsigned CVRQualifiers,
116                                               llvm::Value *Offset) {
117  // Compute (type*) ( (char *) BaseValue + Offset)
118  llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
119  QualType IvarTy = Ivar->getType();
120  const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
121  llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
122  V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
123  V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
124
125  if (Ivar->isBitField()) {
126    // We need to compute the bit offset for the bit-field, the offset
127    // is to the byte. Note, there is a subtle invariant here: we can
128    // only call this routine on non-sythesized ivars but we may be
129    // called for synthesized ivars. However, a synthesized ivar can
130    // never be a bit-field so this is safe.
131    uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
132
133    uint64_t BitFieldSize =
134      Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
135    return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
136                                IvarTy->isSignedIntegerType(),
137                                IvarTy.getCVRQualifiers()|CVRQualifiers);
138  }
139
140  LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
141                               CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
142  LValue::SetObjCIvar(LV, true);
143  return LV;
144}
145
146///
147
148namespace {
149
150  typedef std::vector<llvm::Constant*> ConstantVector;
151
152  // FIXME: We should find a nicer way to make the labels for
153  // metadata, string concatenation is lame.
154
155class ObjCCommonTypesHelper {
156protected:
157  CodeGen::CodeGenModule &CGM;
158
159public:
160  const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
161  const llvm::Type *Int8PtrTy;
162
163  /// ObjectPtrTy - LLVM type for object handles (typeof(id))
164  const llvm::Type *ObjectPtrTy;
165
166  /// PtrObjectPtrTy - LLVM type for id *
167  const llvm::Type *PtrObjectPtrTy;
168
169  /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
170  const llvm::Type *SelectorPtrTy;
171  /// ProtocolPtrTy - LLVM type for external protocol handles
172  /// (typeof(Protocol))
173  const llvm::Type *ExternalProtocolPtrTy;
174
175  // SuperCTy - clang type for struct objc_super.
176  QualType SuperCTy;
177  // SuperPtrCTy - clang type for struct objc_super *.
178  QualType SuperPtrCTy;
179
180  /// SuperTy - LLVM type for struct objc_super.
181  const llvm::StructType *SuperTy;
182  /// SuperPtrTy - LLVM type for struct objc_super *.
183  const llvm::Type *SuperPtrTy;
184
185  /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
186  /// in GCC parlance).
187  const llvm::StructType *PropertyTy;
188
189  /// PropertyListTy - LLVM type for struct objc_property_list
190  /// (_prop_list_t in GCC parlance).
191  const llvm::StructType *PropertyListTy;
192  /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
193  const llvm::Type *PropertyListPtrTy;
194
195  // MethodTy - LLVM type for struct objc_method.
196  const llvm::StructType *MethodTy;
197
198  /// CacheTy - LLVM type for struct objc_cache.
199  const llvm::Type *CacheTy;
200  /// CachePtrTy - LLVM type for struct objc_cache *.
201  const llvm::Type *CachePtrTy;
202
203  llvm::Constant *getGetPropertyFn() {
204    CodeGen::CodeGenTypes &Types = CGM.getTypes();
205    ASTContext &Ctx = CGM.getContext();
206    // id objc_getProperty (id, SEL, ptrdiff_t, bool)
207    llvm::SmallVector<QualType,16> Params;
208    QualType IdType = Ctx.getObjCIdType();
209    QualType SelType = Ctx.getObjCSelType();
210    Params.push_back(IdType);
211    Params.push_back(SelType);
212    Params.push_back(Ctx.LongTy);
213    Params.push_back(Ctx.BoolTy);
214    const llvm::FunctionType *FTy =
215      Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
216    return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
217  }
218
219  llvm::Constant *getSetPropertyFn() {
220    CodeGen::CodeGenTypes &Types = CGM.getTypes();
221    ASTContext &Ctx = CGM.getContext();
222    // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
223    llvm::SmallVector<QualType,16> Params;
224    QualType IdType = Ctx.getObjCIdType();
225    QualType SelType = Ctx.getObjCSelType();
226    Params.push_back(IdType);
227    Params.push_back(SelType);
228    Params.push_back(Ctx.LongTy);
229    Params.push_back(IdType);
230    Params.push_back(Ctx.BoolTy);
231    Params.push_back(Ctx.BoolTy);
232    const llvm::FunctionType *FTy =
233      Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
234    return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
235  }
236
237  llvm::Constant *getEnumerationMutationFn() {
238    // void objc_enumerationMutation (id)
239    std::vector<const llvm::Type*> Args;
240    Args.push_back(ObjectPtrTy);
241    llvm::FunctionType *FTy =
242      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
243    return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
244  }
245
246  /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
247  llvm::Constant *getGcReadWeakFn() {
248    // id objc_read_weak (id *)
249    std::vector<const llvm::Type*> Args;
250    Args.push_back(ObjectPtrTy->getPointerTo());
251    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
252    return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
253  }
254
255  /// GcAssignWeakFn -- LLVM objc_assign_weak function.
256  llvm::Constant *getGcAssignWeakFn() {
257    // id objc_assign_weak (id, id *)
258    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
259    Args.push_back(ObjectPtrTy->getPointerTo());
260    llvm::FunctionType *FTy =
261      llvm::FunctionType::get(ObjectPtrTy, Args, false);
262    return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
263  }
264
265  /// GcAssignGlobalFn -- LLVM objc_assign_global function.
266  llvm::Constant *getGcAssignGlobalFn() {
267    // id objc_assign_global(id, id *)
268    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
269    Args.push_back(ObjectPtrTy->getPointerTo());
270    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
271    return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
272  }
273
274  /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
275  llvm::Constant *getGcAssignIvarFn() {
276    // id objc_assign_ivar(id, id *)
277    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
278    Args.push_back(ObjectPtrTy->getPointerTo());
279    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
280    return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
281  }
282
283  /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
284  llvm::Constant *getGcAssignStrongCastFn() {
285    // id objc_assign_global(id, id *)
286    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
287    Args.push_back(ObjectPtrTy->getPointerTo());
288    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
289    return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
290  }
291
292  /// ExceptionThrowFn - LLVM objc_exception_throw function.
293  llvm::Constant *getExceptionThrowFn() {
294    // void objc_exception_throw(id)
295    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
296    llvm::FunctionType *FTy =
297      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
298    return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
299  }
300
301  /// SyncEnterFn - LLVM object_sync_enter function.
302  llvm::Constant *getSyncEnterFn() {
303    // void objc_sync_enter (id)
304    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
305    llvm::FunctionType *FTy =
306      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
307    return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
308  }
309
310  /// SyncExitFn - LLVM object_sync_exit function.
311  llvm::Constant *getSyncExitFn() {
312    // void objc_sync_exit (id)
313    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
314    llvm::FunctionType *FTy =
315    llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
316    return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
317  }
318
319  ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
320  ~ObjCCommonTypesHelper(){}
321};
322
323/// ObjCTypesHelper - Helper class that encapsulates lazy
324/// construction of varies types used during ObjC generation.
325class ObjCTypesHelper : public ObjCCommonTypesHelper {
326private:
327
328  llvm::Constant *getMessageSendFn() {
329    // id objc_msgSend (id, SEL, ...)
330    std::vector<const llvm::Type*> Params;
331    Params.push_back(ObjectPtrTy);
332    Params.push_back(SelectorPtrTy);
333    return
334      CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
335                                                        Params, true),
336                                "objc_msgSend");
337  }
338
339  llvm::Constant *getMessageSendStretFn() {
340    // id objc_msgSend_stret (id, SEL, ...)
341    std::vector<const llvm::Type*> Params;
342    Params.push_back(ObjectPtrTy);
343    Params.push_back(SelectorPtrTy);
344    return
345      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
346                                                        Params, true),
347                                "objc_msgSend_stret");
348
349  }
350
351  llvm::Constant *getMessageSendFpretFn() {
352    // FIXME: This should be long double on x86_64?
353    // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
354    std::vector<const llvm::Type*> Params;
355    Params.push_back(ObjectPtrTy);
356    Params.push_back(SelectorPtrTy);
357    return
358      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
359                                                        Params,
360                                                        true),
361                                "objc_msgSend_fpret");
362
363  }
364
365  llvm::Constant *getMessageSendSuperFn() {
366    // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
367    std::vector<const llvm::Type*> Params;
368    Params.push_back(SuperPtrTy);
369    Params.push_back(SelectorPtrTy);
370    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
371                                                             Params, true),
372                                     "objc_msgSendSuper");
373  }
374  llvm::Constant *getMessageSendSuperStretFn() {
375    // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
376    //                              SEL op, ...)
377    std::vector<const llvm::Type*> Params;
378    Params.push_back(Int8PtrTy);
379    Params.push_back(SuperPtrTy);
380    Params.push_back(SelectorPtrTy);
381    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
382                                                             Params, true),
383                                     "objc_msgSendSuper_stret");
384  }
385
386  llvm::Constant *getMessageSendSuperFpretFn() {
387    // There is no objc_msgSendSuper_fpret? How can that work?
388    return getMessageSendSuperFn();
389  }
390
391public:
392  /// SymtabTy - LLVM type for struct objc_symtab.
393  const llvm::StructType *SymtabTy;
394  /// SymtabPtrTy - LLVM type for struct objc_symtab *.
395  const llvm::Type *SymtabPtrTy;
396  /// ModuleTy - LLVM type for struct objc_module.
397  const llvm::StructType *ModuleTy;
398
399  /// ProtocolTy - LLVM type for struct objc_protocol.
400  const llvm::StructType *ProtocolTy;
401  /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
402  const llvm::Type *ProtocolPtrTy;
403  /// ProtocolExtensionTy - LLVM type for struct
404  /// objc_protocol_extension.
405  const llvm::StructType *ProtocolExtensionTy;
406  /// ProtocolExtensionTy - LLVM type for struct
407  /// objc_protocol_extension *.
408  const llvm::Type *ProtocolExtensionPtrTy;
409  /// MethodDescriptionTy - LLVM type for struct
410  /// objc_method_description.
411  const llvm::StructType *MethodDescriptionTy;
412  /// MethodDescriptionListTy - LLVM type for struct
413  /// objc_method_description_list.
414  const llvm::StructType *MethodDescriptionListTy;
415  /// MethodDescriptionListPtrTy - LLVM type for struct
416  /// objc_method_description_list *.
417  const llvm::Type *MethodDescriptionListPtrTy;
418  /// ProtocolListTy - LLVM type for struct objc_property_list.
419  const llvm::Type *ProtocolListTy;
420  /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
421  const llvm::Type *ProtocolListPtrTy;
422  /// CategoryTy - LLVM type for struct objc_category.
423  const llvm::StructType *CategoryTy;
424  /// ClassTy - LLVM type for struct objc_class.
425  const llvm::StructType *ClassTy;
426  /// ClassPtrTy - LLVM type for struct objc_class *.
427  const llvm::Type *ClassPtrTy;
428  /// ClassExtensionTy - LLVM type for struct objc_class_ext.
429  const llvm::StructType *ClassExtensionTy;
430  /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
431  const llvm::Type *ClassExtensionPtrTy;
432  // IvarTy - LLVM type for struct objc_ivar.
433  const llvm::StructType *IvarTy;
434  /// IvarListTy - LLVM type for struct objc_ivar_list.
435  const llvm::Type *IvarListTy;
436  /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
437  const llvm::Type *IvarListPtrTy;
438  /// MethodListTy - LLVM type for struct objc_method_list.
439  const llvm::Type *MethodListTy;
440  /// MethodListPtrTy - LLVM type for struct objc_method_list *.
441  const llvm::Type *MethodListPtrTy;
442
443  /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
444  const llvm::Type *ExceptionDataTy;
445
446  /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
447  llvm::Constant *getExceptionTryEnterFn() {
448    std::vector<const llvm::Type*> Params;
449    Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
450    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
451                                                             Params, false),
452                                     "objc_exception_try_enter");
453  }
454
455  /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
456  llvm::Constant *getExceptionTryExitFn() {
457    std::vector<const llvm::Type*> Params;
458    Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
459    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
460                                                             Params, false),
461                                     "objc_exception_try_exit");
462  }
463
464  /// ExceptionExtractFn - LLVM objc_exception_extract function.
465  llvm::Constant *getExceptionExtractFn() {
466    std::vector<const llvm::Type*> Params;
467    Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
468    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
469                                                             Params, false),
470                                     "objc_exception_extract");
471
472  }
473
474  /// ExceptionMatchFn - LLVM objc_exception_match function.
475  llvm::Constant *getExceptionMatchFn() {
476    std::vector<const llvm::Type*> Params;
477    Params.push_back(ClassPtrTy);
478    Params.push_back(ObjectPtrTy);
479   return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
480                                                            Params, false),
481                                    "objc_exception_match");
482
483  }
484
485  /// SetJmpFn - LLVM _setjmp function.
486  llvm::Constant *getSetJmpFn() {
487    std::vector<const llvm::Type*> Params;
488    Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
489    return
490      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
491                                                        Params, false),
492                                "_setjmp");
493
494  }
495
496public:
497  ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
498  ~ObjCTypesHelper() {}
499
500
501  llvm::Constant *getSendFn(bool IsSuper) {
502    return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
503  }
504
505  llvm::Constant *getSendStretFn(bool IsSuper) {
506    return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
507  }
508
509  llvm::Constant *getSendFpretFn(bool IsSuper) {
510    return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
511  }
512};
513
514/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
515/// modern abi
516class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
517public:
518
519  // MethodListnfABITy - LLVM for struct _method_list_t
520  const llvm::StructType *MethodListnfABITy;
521
522  // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
523  const llvm::Type *MethodListnfABIPtrTy;
524
525  // ProtocolnfABITy = LLVM for struct _protocol_t
526  const llvm::StructType *ProtocolnfABITy;
527
528  // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
529  const llvm::Type *ProtocolnfABIPtrTy;
530
531  // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
532  const llvm::StructType *ProtocolListnfABITy;
533
534  // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
535  const llvm::Type *ProtocolListnfABIPtrTy;
536
537  // ClassnfABITy - LLVM for struct _class_t
538  const llvm::StructType *ClassnfABITy;
539
540  // ClassnfABIPtrTy - LLVM for struct _class_t*
541  const llvm::Type *ClassnfABIPtrTy;
542
543  // IvarnfABITy - LLVM for struct _ivar_t
544  const llvm::StructType *IvarnfABITy;
545
546  // IvarListnfABITy - LLVM for struct _ivar_list_t
547  const llvm::StructType *IvarListnfABITy;
548
549  // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
550  const llvm::Type *IvarListnfABIPtrTy;
551
552  // ClassRonfABITy - LLVM for struct _class_ro_t
553  const llvm::StructType *ClassRonfABITy;
554
555  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
556  const llvm::Type *ImpnfABITy;
557
558  // CategorynfABITy - LLVM for struct _category_t
559  const llvm::StructType *CategorynfABITy;
560
561  // New types for nonfragile abi messaging.
562
563  // MessageRefTy - LLVM for:
564  // struct _message_ref_t {
565  //   IMP messenger;
566  //   SEL name;
567  // };
568  const llvm::StructType *MessageRefTy;
569  // MessageRefCTy - clang type for struct _message_ref_t
570  QualType MessageRefCTy;
571
572  // MessageRefPtrTy - LLVM for struct _message_ref_t*
573  const llvm::Type *MessageRefPtrTy;
574  // MessageRefCPtrTy - clang type for struct _message_ref_t*
575  QualType MessageRefCPtrTy;
576
577  // MessengerTy - Type of the messenger (shown as IMP above)
578  const llvm::FunctionType *MessengerTy;
579
580  // SuperMessageRefTy - LLVM for:
581  // struct _super_message_ref_t {
582  //   SUPER_IMP messenger;
583  //   SEL name;
584  // };
585  const llvm::StructType *SuperMessageRefTy;
586
587  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
588  const llvm::Type *SuperMessageRefPtrTy;
589
590  llvm::Constant *getMessageSendFixupFn() {
591    // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
592    std::vector<const llvm::Type*> Params;
593    Params.push_back(ObjectPtrTy);
594    Params.push_back(MessageRefPtrTy);
595    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
596                                                             Params, true),
597                                     "objc_msgSend_fixup");
598  }
599
600  llvm::Constant *getMessageSendFpretFixupFn() {
601    // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
602    std::vector<const llvm::Type*> Params;
603    Params.push_back(ObjectPtrTy);
604    Params.push_back(MessageRefPtrTy);
605    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
606                                                             Params, true),
607                                     "objc_msgSend_fpret_fixup");
608  }
609
610  llvm::Constant *getMessageSendStretFixupFn() {
611    // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
612    std::vector<const llvm::Type*> Params;
613    Params.push_back(ObjectPtrTy);
614    Params.push_back(MessageRefPtrTy);
615    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
616                                                             Params, true),
617                                     "objc_msgSend_stret_fixup");
618  }
619
620  llvm::Constant *getMessageSendIdFixupFn() {
621    // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
622    std::vector<const llvm::Type*> Params;
623    Params.push_back(ObjectPtrTy);
624    Params.push_back(MessageRefPtrTy);
625    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
626                                                             Params, true),
627                                     "objc_msgSendId_fixup");
628  }
629
630  llvm::Constant *getMessageSendIdStretFixupFn() {
631    // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
632    std::vector<const llvm::Type*> Params;
633    Params.push_back(ObjectPtrTy);
634    Params.push_back(MessageRefPtrTy);
635    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
636                                                             Params, true),
637                                     "objc_msgSendId_stret_fixup");
638  }
639  llvm::Constant *getMessageSendSuper2FixupFn() {
640    // id objc_msgSendSuper2_fixup (struct objc_super *,
641    //                              struct _super_message_ref_t*, ...)
642    std::vector<const llvm::Type*> Params;
643    Params.push_back(SuperPtrTy);
644    Params.push_back(SuperMessageRefPtrTy);
645    return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
646                                                              Params, true),
647                                      "objc_msgSendSuper2_fixup");
648  }
649
650  llvm::Constant *getMessageSendSuper2StretFixupFn() {
651    // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
652    //                                   struct _super_message_ref_t*, ...)
653    std::vector<const llvm::Type*> Params;
654    Params.push_back(SuperPtrTy);
655    Params.push_back(SuperMessageRefPtrTy);
656    return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
657                                                              Params, true),
658                                      "objc_msgSendSuper2_stret_fixup");
659  }
660
661
662
663  /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
664  /// exception personality function.
665  llvm::Value *getEHPersonalityPtr() {
666    llvm::Constant *Personality =
667      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
668                                              std::vector<const llvm::Type*>(),
669                                                        true),
670                              "__objc_personality_v0");
671    return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
672  }
673
674  llvm::Constant *getUnwindResumeOrRethrowFn() {
675    std::vector<const llvm::Type*> Params;
676    Params.push_back(Int8PtrTy);
677    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
678                                                             Params, false),
679                                     "_Unwind_Resume_or_Rethrow");
680  }
681
682  llvm::Constant *getObjCEndCatchFn() {
683    std::vector<const llvm::Type*> Params;
684    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
685                                                             Params, false),
686                                     "objc_end_catch");
687
688  }
689
690  llvm::Constant *getObjCBeginCatchFn() {
691    std::vector<const llvm::Type*> Params;
692    Params.push_back(Int8PtrTy);
693    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
694                                                             Params, false),
695                                     "objc_begin_catch");
696  }
697
698  const llvm::StructType *EHTypeTy;
699  const llvm::Type *EHTypePtrTy;
700
701  ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
702  ~ObjCNonFragileABITypesHelper(){}
703};
704
705class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
706public:
707  // FIXME - accessibility
708  class GC_IVAR {
709  public:
710    unsigned int ivar_bytepos;
711    unsigned int ivar_size;
712    GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
713
714    // Allow sorting based on byte pos.
715    bool operator<(const GC_IVAR &b) const {
716      return ivar_bytepos < b.ivar_bytepos;
717    }
718  };
719
720  class SKIP_SCAN {
721    public:
722    unsigned int skip;
723    unsigned int scan;
724    SKIP_SCAN() : skip(0), scan(0) {}
725  };
726
727protected:
728  CodeGen::CodeGenModule &CGM;
729  // FIXME! May not be needing this after all.
730  unsigned ObjCABI;
731
732  // gc ivar layout bitmap calculation helper caches.
733  llvm::SmallVector<GC_IVAR, 16> SkipIvars;
734  llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
735
736  /// LazySymbols - Symbols to generate a lazy reference for. See
737  /// DefinedSymbols and FinishModule().
738  std::set<IdentifierInfo*> LazySymbols;
739
740  /// DefinedSymbols - External symbols which are defined by this
741  /// module. The symbols in this list and LazySymbols are used to add
742  /// special linker symbols which ensure that Objective-C modules are
743  /// linked properly.
744  std::set<IdentifierInfo*> DefinedSymbols;
745
746  /// ClassNames - uniqued class names.
747  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
748
749  /// MethodVarNames - uniqued method variable names.
750  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
751
752  /// MethodVarTypes - uniqued method type signatures. We have to use
753  /// a StringMap here because have no other unique reference.
754  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
755
756  /// MethodDefinitions - map of methods which have been defined in
757  /// this translation unit.
758  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
759
760  /// PropertyNames - uniqued method variable names.
761  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
762
763  /// ClassReferences - uniqued class references.
764  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
765
766  /// SelectorReferences - uniqued selector references.
767  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
768
769  /// Protocols - Protocols for which an objc_protocol structure has
770  /// been emitted. Forward declarations are handled by creating an
771  /// empty structure whose initializer is filled in when/if defined.
772  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
773
774  /// DefinedProtocols - Protocols which have actually been
775  /// defined. We should not need this, see FIXME in GenerateProtocol.
776  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
777
778  /// DefinedClasses - List of defined classes.
779  std::vector<llvm::GlobalValue*> DefinedClasses;
780
781  /// DefinedCategories - List of defined categories.
782  std::vector<llvm::GlobalValue*> DefinedCategories;
783
784  /// UsedGlobals - List of globals to pack into the llvm.used metadata
785  /// to prevent them from being clobbered.
786  std::vector<llvm::GlobalVariable*> UsedGlobals;
787
788  /// GetNameForMethod - Return a name for the given method.
789  /// \param[out] NameOut - The return value.
790  void GetNameForMethod(const ObjCMethodDecl *OMD,
791                        const ObjCContainerDecl *CD,
792                        std::string &NameOut);
793
794  /// GetMethodVarName - Return a unique constant for the given
795  /// selector's name. The return value has type char *.
796  llvm::Constant *GetMethodVarName(Selector Sel);
797  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
798  llvm::Constant *GetMethodVarName(const std::string &Name);
799
800  /// GetMethodVarType - Return a unique constant for the given
801  /// selector's name. The return value has type char *.
802
803  // FIXME: This is a horrible name.
804  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
805  llvm::Constant *GetMethodVarType(const FieldDecl *D);
806
807  /// GetPropertyName - Return a unique constant for the given
808  /// name. The return value has type char *.
809  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
810
811  // FIXME: This can be dropped once string functions are unified.
812  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
813                                        const Decl *Container);
814
815  /// GetClassName - Return a unique constant for the given selector's
816  /// name. The return value has type char *.
817  llvm::Constant *GetClassName(IdentifierInfo *Ident);
818
819  /// BuildIvarLayout - Builds ivar layout bitmap for the class
820  /// implementation for the __strong or __weak case.
821  ///
822  llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
823                                  bool ForStrongLayout);
824
825  void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
826                           const llvm::StructLayout *Layout,
827                           const RecordDecl *RD,
828                           const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
829                           unsigned int BytePos, bool ForStrongLayout,
830                           bool &HasUnion);
831
832  /// GetIvarLayoutName - Returns a unique constant for the given
833  /// ivar layout bitmap.
834  llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
835                                    const ObjCCommonTypesHelper &ObjCTypes);
836
837  /// EmitPropertyList - Emit the given property list. The return
838  /// value has type PropertyListPtrTy.
839  llvm::Constant *EmitPropertyList(const std::string &Name,
840                                   const Decl *Container,
841                                   const ObjCContainerDecl *OCD,
842                                   const ObjCCommonTypesHelper &ObjCTypes);
843
844  /// GetProtocolRef - Return a reference to the internal protocol
845  /// description, creating an empty one if it has not been
846  /// defined. The return value has type ProtocolPtrTy.
847  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
848
849  /// GetFieldBaseOffset - return's field byte offset.
850  uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
851                              const llvm::StructLayout *Layout,
852                              const FieldDecl *Field);
853
854  /// CreateMetadataVar - Create a global variable with internal
855  /// linkage for use by the Objective-C runtime.
856  ///
857  /// This is a convenience wrapper which not only creates the
858  /// variable, but also sets the section and alignment and adds the
859  /// global to the UsedGlobals list.
860  ///
861  /// \param Name - The variable name.
862  /// \param Init - The variable initializer; this is also used to
863  /// define the type of the variable.
864  /// \param Section - The section the variable should go into, or 0.
865  /// \param Align - The alignment for the variable, or 0.
866  /// \param AddToUsed - Whether the variable should be added to
867  /// "llvm.used".
868  llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
869                                          llvm::Constant *Init,
870                                          const char *Section,
871                                          unsigned Align,
872                                          bool AddToUsed);
873
874  /// GetNamedIvarList - Return the list of ivars in the interface
875  /// itself (not including super classes and not including unnamed
876  /// bitfields).
877  ///
878  /// For the non-fragile ABI, this also includes synthesized property
879  /// ivars.
880  void GetNamedIvarList(const ObjCInterfaceDecl *OID,
881                        llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
882
883public:
884  CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
885  { }
886
887  virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
888
889  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
890                                         const ObjCContainerDecl *CD=0);
891
892  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
893
894  /// GetOrEmitProtocol - Get the protocol object for the given
895  /// declaration, emitting it if necessary. The return value has type
896  /// ProtocolPtrTy.
897  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
898
899  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
900  /// object for the given declaration, emitting it if needed. These
901  /// forward references will be filled in with empty bodies if no
902  /// definition is seen. The return value has type ProtocolPtrTy.
903  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
904};
905
906class CGObjCMac : public CGObjCCommonMac {
907private:
908  ObjCTypesHelper ObjCTypes;
909  /// EmitImageInfo - Emit the image info marker used to encode some module
910  /// level information.
911  void EmitImageInfo();
912
913  /// EmitModuleInfo - Another marker encoding module level
914  /// information.
915  void EmitModuleInfo();
916
917  /// EmitModuleSymols - Emit module symbols, the list of defined
918  /// classes and categories. The result has type SymtabPtrTy.
919  llvm::Constant *EmitModuleSymbols();
920
921  /// FinishModule - Write out global data structures at the end of
922  /// processing a translation unit.
923  void FinishModule();
924
925  /// EmitClassExtension - Generate the class extension structure used
926  /// to store the weak ivar layout and properties. The return value
927  /// has type ClassExtensionPtrTy.
928  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
929
930  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
931  /// for the given class.
932  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
933                            const ObjCInterfaceDecl *ID);
934
935  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
936                                  QualType ResultType,
937                                  Selector Sel,
938                                  llvm::Value *Arg0,
939                                  QualType Arg0Ty,
940                                  bool IsSuper,
941                                  const CallArgList &CallArgs);
942
943  /// EmitIvarList - Emit the ivar list for the given
944  /// implementation. If ForClass is true the list of class ivars
945  /// (i.e. metaclass ivars) is emitted, otherwise the list of
946  /// interface ivars will be emitted. The return value has type
947  /// IvarListPtrTy.
948  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
949                               bool ForClass);
950
951  /// EmitMetaClass - Emit a forward reference to the class structure
952  /// for the metaclass of the given interface. The return value has
953  /// type ClassPtrTy.
954  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
955
956  /// EmitMetaClass - Emit a class structure for the metaclass of the
957  /// given implementation. The return value has type ClassPtrTy.
958  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
959                                llvm::Constant *Protocols,
960                                const ConstantVector &Methods);
961
962  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
963
964  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
965
966  /// EmitMethodList - Emit the method list for the given
967  /// implementation. The return value has type MethodListPtrTy.
968  llvm::Constant *EmitMethodList(const std::string &Name,
969                                 const char *Section,
970                                 const ConstantVector &Methods);
971
972  /// EmitMethodDescList - Emit a method description list for a list of
973  /// method declarations.
974  ///  - TypeName: The name for the type containing the methods.
975  ///  - IsProtocol: True iff these methods are for a protocol.
976  ///  - ClassMethds: True iff these are class methods.
977  ///  - Required: When true, only "required" methods are
978  ///    listed. Similarly, when false only "optional" methods are
979  ///    listed. For classes this should always be true.
980  ///  - begin, end: The method list to output.
981  ///
982  /// The return value has type MethodDescriptionListPtrTy.
983  llvm::Constant *EmitMethodDescList(const std::string &Name,
984                                     const char *Section,
985                                     const ConstantVector &Methods);
986
987  /// GetOrEmitProtocol - Get the protocol object for the given
988  /// declaration, emitting it if necessary. The return value has type
989  /// ProtocolPtrTy.
990  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
991
992  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
993  /// object for the given declaration, emitting it if needed. These
994  /// forward references will be filled in with empty bodies if no
995  /// definition is seen. The return value has type ProtocolPtrTy.
996  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
997
998  /// EmitProtocolExtension - Generate the protocol extension
999  /// structure used to store optional instance and class methods, and
1000  /// protocol properties. The return value has type
1001  /// ProtocolExtensionPtrTy.
1002  llvm::Constant *
1003  EmitProtocolExtension(const ObjCProtocolDecl *PD,
1004                        const ConstantVector &OptInstanceMethods,
1005                        const ConstantVector &OptClassMethods);
1006
1007  /// EmitProtocolList - Generate the list of referenced
1008  /// protocols. The return value has type ProtocolListPtrTy.
1009  llvm::Constant *EmitProtocolList(const std::string &Name,
1010                                   ObjCProtocolDecl::protocol_iterator begin,
1011                                   ObjCProtocolDecl::protocol_iterator end);
1012
1013  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1014  /// for the given selector.
1015  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
1016
1017  public:
1018  CGObjCMac(CodeGen::CodeGenModule &cgm);
1019
1020  virtual llvm::Function *ModuleInitFunction();
1021
1022  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1023                                              QualType ResultType,
1024                                              Selector Sel,
1025                                              llvm::Value *Receiver,
1026                                              bool IsClassMessage,
1027                                              const CallArgList &CallArgs);
1028
1029  virtual CodeGen::RValue
1030  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1031                           QualType ResultType,
1032                           Selector Sel,
1033                           const ObjCInterfaceDecl *Class,
1034                           bool isCategoryImpl,
1035                           llvm::Value *Receiver,
1036                           bool IsClassMessage,
1037                           const CallArgList &CallArgs);
1038
1039  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
1040                                const ObjCInterfaceDecl *ID);
1041
1042  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
1043
1044  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
1045
1046  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
1047
1048  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
1049                                           const ObjCProtocolDecl *PD);
1050
1051  virtual llvm::Constant *GetPropertyGetFunction();
1052  virtual llvm::Constant *GetPropertySetFunction();
1053  virtual llvm::Constant *EnumerationMutationFunction();
1054
1055  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1056                                         const Stmt &S);
1057  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1058                             const ObjCAtThrowStmt &S);
1059  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1060                                         llvm::Value *AddrWeakObj);
1061  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1062                                  llvm::Value *src, llvm::Value *dst);
1063  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1064                                    llvm::Value *src, llvm::Value *dest);
1065  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1066                                  llvm::Value *src, llvm::Value *dest);
1067  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1068                                        llvm::Value *src, llvm::Value *dest);
1069
1070  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1071                                      QualType ObjectTy,
1072                                      llvm::Value *BaseValue,
1073                                      const ObjCIvarDecl *Ivar,
1074                                      unsigned CVRQualifiers);
1075  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1076                                      const ObjCInterfaceDecl *Interface,
1077                                      const ObjCIvarDecl *Ivar);
1078};
1079
1080class CGObjCNonFragileABIMac : public CGObjCCommonMac {
1081private:
1082  ObjCNonFragileABITypesHelper ObjCTypes;
1083  llvm::GlobalVariable* ObjCEmptyCacheVar;
1084  llvm::GlobalVariable* ObjCEmptyVtableVar;
1085
1086  /// SuperClassReferences - uniqued super class references.
1087  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1088
1089  /// MetaClassReferences - uniqued meta class references.
1090  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
1091
1092  /// EHTypeReferences - uniqued class ehtype references.
1093  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
1094
1095  /// FinishNonFragileABIModule - Write out global data structures at the end of
1096  /// processing a translation unit.
1097  void FinishNonFragileABIModule();
1098
1099  llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1100                                unsigned InstanceStart,
1101                                unsigned InstanceSize,
1102                                const ObjCImplementationDecl *ID);
1103  llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1104                                            llvm::Constant *IsAGV,
1105                                            llvm::Constant *SuperClassGV,
1106                                            llvm::Constant *ClassRoGV,
1107                                            bool HiddenVisibility);
1108
1109  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1110
1111  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1112
1113  /// EmitMethodList - Emit the method list for the given
1114  /// implementation. The return value has type MethodListnfABITy.
1115  llvm::Constant *EmitMethodList(const std::string &Name,
1116                                 const char *Section,
1117                                 const ConstantVector &Methods);
1118  /// EmitIvarList - Emit the ivar list for the given
1119  /// implementation. If ForClass is true the list of class ivars
1120  /// (i.e. metaclass ivars) is emitted, otherwise the list of
1121  /// interface ivars will be emitted. The return value has type
1122  /// IvarListnfABIPtrTy.
1123  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
1124
1125  llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
1126                                    const ObjCIvarDecl *Ivar,
1127                                    unsigned long int offset);
1128
1129  /// GetOrEmitProtocol - Get the protocol object for the given
1130  /// declaration, emitting it if necessary. The return value has type
1131  /// ProtocolPtrTy.
1132  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1133
1134  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1135  /// object for the given declaration, emitting it if needed. These
1136  /// forward references will be filled in with empty bodies if no
1137  /// definition is seen. The return value has type ProtocolPtrTy.
1138  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1139
1140  /// EmitProtocolList - Generate the list of referenced
1141  /// protocols. The return value has type ProtocolListPtrTy.
1142  llvm::Constant *EmitProtocolList(const std::string &Name,
1143                                   ObjCProtocolDecl::protocol_iterator begin,
1144                                   ObjCProtocolDecl::protocol_iterator end);
1145
1146  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1147                                  QualType ResultType,
1148                                  Selector Sel,
1149                                  llvm::Value *Receiver,
1150                                  QualType Arg0Ty,
1151                                  bool IsSuper,
1152                                  const CallArgList &CallArgs);
1153
1154  /// GetClassGlobal - Return the global variable for the Objective-C
1155  /// class of the given name.
1156  llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1157
1158  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1159  /// for the given class reference.
1160  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
1161                            const ObjCInterfaceDecl *ID);
1162
1163  /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1164  /// for the given super class reference.
1165  llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1166                            const ObjCInterfaceDecl *ID);
1167
1168  /// EmitMetaClassRef - Return a Value * of the address of _class_t
1169  /// meta-data
1170  llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1171                                const ObjCInterfaceDecl *ID);
1172
1173  /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1174  /// the given ivar.
1175  ///
1176  llvm::GlobalVariable * ObjCIvarOffsetVariable(
1177                              const ObjCInterfaceDecl *ID,
1178                              const ObjCIvarDecl *Ivar);
1179
1180  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1181  /// for the given selector.
1182  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
1183
1184  /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
1185  /// interface. The return value has type EHTypePtrTy.
1186  llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1187                                  bool ForDefinition);
1188
1189  const char *getMetaclassSymbolPrefix() const {
1190    return "OBJC_METACLASS_$_";
1191  }
1192
1193  const char *getClassSymbolPrefix() const {
1194    return "OBJC_CLASS_$_";
1195  }
1196
1197  void GetClassSizeInfo(const ObjCImplementationDecl *OID,
1198                        uint32_t &InstanceStart,
1199                        uint32_t &InstanceSize);
1200
1201public:
1202  CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
1203  // FIXME. All stubs for now!
1204  virtual llvm::Function *ModuleInitFunction();
1205
1206  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1207                                              QualType ResultType,
1208                                              Selector Sel,
1209                                              llvm::Value *Receiver,
1210                                              bool IsClassMessage,
1211                                              const CallArgList &CallArgs);
1212
1213  virtual CodeGen::RValue
1214  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1215                           QualType ResultType,
1216                           Selector Sel,
1217                           const ObjCInterfaceDecl *Class,
1218                           bool isCategoryImpl,
1219                           llvm::Value *Receiver,
1220                           bool IsClassMessage,
1221                           const CallArgList &CallArgs);
1222
1223  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
1224                                const ObjCInterfaceDecl *ID);
1225
1226  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
1227    { return EmitSelector(Builder, Sel); }
1228
1229  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
1230
1231  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
1232  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
1233                                           const ObjCProtocolDecl *PD);
1234
1235  virtual llvm::Constant *GetPropertyGetFunction() {
1236    return ObjCTypes.getGetPropertyFn();
1237  }
1238  virtual llvm::Constant *GetPropertySetFunction() {
1239    return ObjCTypes.getSetPropertyFn();
1240  }
1241  virtual llvm::Constant *EnumerationMutationFunction() {
1242    return ObjCTypes.getEnumerationMutationFn();
1243  }
1244
1245  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1246                                         const Stmt &S);
1247  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1248                             const ObjCAtThrowStmt &S);
1249  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1250                                         llvm::Value *AddrWeakObj);
1251  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1252                                  llvm::Value *src, llvm::Value *dst);
1253  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1254                                    llvm::Value *src, llvm::Value *dest);
1255  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1256                                  llvm::Value *src, llvm::Value *dest);
1257  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1258                                        llvm::Value *src, llvm::Value *dest);
1259  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1260                                      QualType ObjectTy,
1261                                      llvm::Value *BaseValue,
1262                                      const ObjCIvarDecl *Ivar,
1263                                      unsigned CVRQualifiers);
1264  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1265                                      const ObjCInterfaceDecl *Interface,
1266                                      const ObjCIvarDecl *Ivar);
1267};
1268
1269} // end anonymous namespace
1270
1271/* *** Helper Functions *** */
1272
1273/// getConstantGEP() - Help routine to construct simple GEPs.
1274static llvm::Constant *getConstantGEP(llvm::Constant *C,
1275                                      unsigned idx0,
1276                                      unsigned idx1) {
1277  llvm::Value *Idxs[] = {
1278    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1279    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1280  };
1281  return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1282}
1283
1284/// hasObjCExceptionAttribute - Return true if this class or any super
1285/// class has the __objc_exception__ attribute.
1286static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
1287  if (OID->hasAttr<ObjCExceptionAttr>())
1288    return true;
1289  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1290    return hasObjCExceptionAttribute(Super);
1291  return false;
1292}
1293
1294/* *** CGObjCMac Public Interface *** */
1295
1296CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1297                                                    ObjCTypes(cgm)
1298{
1299  ObjCABI = 1;
1300  EmitImageInfo();
1301}
1302
1303/// GetClass - Return a reference to the class for the given interface
1304/// decl.
1305llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
1306                                 const ObjCInterfaceDecl *ID) {
1307  return EmitClassRef(Builder, ID);
1308}
1309
1310/// GetSelector - Return the pointer to the unique'd string for this selector.
1311llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
1312  return EmitSelector(Builder, Sel);
1313}
1314
1315/// Generate a constant CFString object.
1316/*
1317   struct __builtin_CFString {
1318     const int *isa; // point to __CFConstantStringClassReference
1319     int flags;
1320     const char *str;
1321     long length;
1322   };
1323*/
1324
1325llvm::Constant *CGObjCCommonMac::GenerateConstantString(
1326  const ObjCStringLiteral *SL) {
1327  return CGM.GetAddrOfConstantCFString(SL->getString());
1328}
1329
1330/// Generates a message send where the super is the receiver.  This is
1331/// a message send to self with special delivery semantics indicating
1332/// which class's method should be called.
1333CodeGen::RValue
1334CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1335                                    QualType ResultType,
1336                                    Selector Sel,
1337                                    const ObjCInterfaceDecl *Class,
1338                                    bool isCategoryImpl,
1339                                    llvm::Value *Receiver,
1340                                    bool IsClassMessage,
1341                                    const CodeGen::CallArgList &CallArgs) {
1342  // Create and init a super structure; this is a (receiver, class)
1343  // pair we will pass to objc_msgSendSuper.
1344  llvm::Value *ObjCSuper =
1345    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1346  llvm::Value *ReceiverAsObject =
1347    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1348  CGF.Builder.CreateStore(ReceiverAsObject,
1349                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
1350
1351  // If this is a class message the metaclass is passed as the target.
1352  llvm::Value *Target;
1353  if (IsClassMessage) {
1354    if (isCategoryImpl) {
1355      // Message sent to 'super' in a class method defined in a category
1356      // implementation requires an odd treatment.
1357      // If we are in a class method, we must retrieve the
1358      // _metaclass_ for the current class, pointed at by
1359      // the class's "isa" pointer.  The following assumes that
1360      // isa" is the first ivar in a class (which it must be).
1361      Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1362      Target = CGF.Builder.CreateStructGEP(Target, 0);
1363      Target = CGF.Builder.CreateLoad(Target);
1364    }
1365    else {
1366      llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1367      llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1368      llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1369      Target = Super;
1370   }
1371  } else {
1372    Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1373  }
1374  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1375  // and ObjCTypes types.
1376  const llvm::Type *ClassTy =
1377    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
1378  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
1379  CGF.Builder.CreateStore(Target,
1380                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1381
1382  return EmitMessageSend(CGF, ResultType, Sel,
1383                         ObjCSuper, ObjCTypes.SuperPtrCTy,
1384                         true, CallArgs);
1385}
1386
1387/// Generate code for a message send expression.
1388CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1389                                               QualType ResultType,
1390                                               Selector Sel,
1391                                               llvm::Value *Receiver,
1392                                               bool IsClassMessage,
1393                                               const CallArgList &CallArgs) {
1394  return EmitMessageSend(CGF, ResultType, Sel,
1395                         Receiver, CGF.getContext().getObjCIdType(),
1396                         false, CallArgs);
1397}
1398
1399CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1400                                           QualType ResultType,
1401                                           Selector Sel,
1402                                           llvm::Value *Arg0,
1403                                           QualType Arg0Ty,
1404                                           bool IsSuper,
1405                                           const CallArgList &CallArgs) {
1406  CallArgList ActualArgs;
1407  if (!IsSuper)
1408    Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
1409  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1410  ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1411                                                               Sel)),
1412                                      CGF.getContext().getObjCSelType()));
1413  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1414
1415  CodeGenTypes &Types = CGM.getTypes();
1416  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1417  // FIXME. vararg flag must be true when this API is used for 64bit code gen.
1418  const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
1419
1420  llvm::Constant *Fn;
1421  if (CGM.ReturnTypeUsesSret(FnInfo)) {
1422    Fn = ObjCTypes.getSendStretFn(IsSuper);
1423  } else if (ResultType->isFloatingType()) {
1424    // FIXME: Sadly, this is wrong. This actually depends on the
1425    // architecture. This happens to be right for x86-32 though.
1426    Fn = ObjCTypes.getSendFpretFn(IsSuper);
1427  } else {
1428    Fn = ObjCTypes.getSendFn(IsSuper);
1429  }
1430  Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
1431  return CGF.EmitCall(FnInfo, Fn, ActualArgs);
1432}
1433
1434llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
1435                                            const ObjCProtocolDecl *PD) {
1436  // FIXME: I don't understand why gcc generates this, or where it is
1437  // resolved. Investigate. Its also wasteful to look this up over and
1438  // over.
1439  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1440
1441  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1442                                        ObjCTypes.ExternalProtocolPtrTy);
1443}
1444
1445void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
1446  // FIXME: We shouldn't need this, the protocol decl should contain
1447  // enough information to tell us whether this was a declaration or a
1448  // definition.
1449  DefinedProtocols.insert(PD->getIdentifier());
1450
1451  // If we have generated a forward reference to this protocol, emit
1452  // it now. Otherwise do nothing, the protocol objects are lazily
1453  // emitted.
1454  if (Protocols.count(PD->getIdentifier()))
1455    GetOrEmitProtocol(PD);
1456}
1457
1458llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
1459  if (DefinedProtocols.count(PD->getIdentifier()))
1460    return GetOrEmitProtocol(PD);
1461  return GetOrEmitProtocolRef(PD);
1462}
1463
1464/*
1465     // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1466  struct _objc_protocol {
1467    struct _objc_protocol_extension *isa;
1468    char *protocol_name;
1469    struct _objc_protocol_list *protocol_list;
1470    struct _objc__method_prototype_list *instance_methods;
1471    struct _objc__method_prototype_list *class_methods
1472  };
1473
1474  See EmitProtocolExtension().
1475*/
1476llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1477  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1478
1479  // Early exit if a defining object has already been generated.
1480  if (Entry && Entry->hasInitializer())
1481    return Entry;
1482
1483  // FIXME: I don't understand why gcc generates this, or where it is
1484  // resolved. Investigate. Its also wasteful to look this up over and
1485  // over.
1486  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1487
1488  const char *ProtocolName = PD->getNameAsCString();
1489
1490  // Construct method lists.
1491  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1492  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1493  for (ObjCProtocolDecl::instmeth_iterator
1494         i = PD->instmeth_begin(CGM.getContext()),
1495         e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
1496    ObjCMethodDecl *MD = *i;
1497    llvm::Constant *C = GetMethodDescriptionConstant(MD);
1498    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1499      OptInstanceMethods.push_back(C);
1500    } else {
1501      InstanceMethods.push_back(C);
1502    }
1503  }
1504
1505  for (ObjCProtocolDecl::classmeth_iterator
1506         i = PD->classmeth_begin(CGM.getContext()),
1507         e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
1508    ObjCMethodDecl *MD = *i;
1509    llvm::Constant *C = GetMethodDescriptionConstant(MD);
1510    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1511      OptClassMethods.push_back(C);
1512    } else {
1513      ClassMethods.push_back(C);
1514    }
1515  }
1516
1517  std::vector<llvm::Constant*> Values(5);
1518  Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
1519  Values[1] = GetClassName(PD->getIdentifier());
1520  Values[2] =
1521    EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
1522                     PD->protocol_begin(),
1523                     PD->protocol_end());
1524  Values[3] =
1525    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1526                          + PD->getNameAsString(),
1527                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1528                       InstanceMethods);
1529  Values[4] =
1530    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1531                            + PD->getNameAsString(),
1532                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1533                       ClassMethods);
1534  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1535                                                   Values);
1536
1537  if (Entry) {
1538    // Already created, fix the linkage and update the initializer.
1539    Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
1540    Entry->setInitializer(Init);
1541  } else {
1542    Entry =
1543      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1544                               llvm::GlobalValue::InternalLinkage,
1545                               Init,
1546                               std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1547                               &CGM.getModule());
1548    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1549    Entry->setAlignment(4);
1550    UsedGlobals.push_back(Entry);
1551    // FIXME: Is this necessary? Why only for protocol?
1552    Entry->setAlignment(4);
1553  }
1554
1555  return Entry;
1556}
1557
1558llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
1559  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1560
1561  if (!Entry) {
1562    // We use the initializer as a marker of whether this is a forward
1563    // reference or not. At module finalization we add the empty
1564    // contents for protocols which were referenced but never defined.
1565    Entry =
1566      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1567                               llvm::GlobalValue::ExternalLinkage,
1568                               0,
1569                               "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
1570                               &CGM.getModule());
1571    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1572    Entry->setAlignment(4);
1573    UsedGlobals.push_back(Entry);
1574    // FIXME: Is this necessary? Why only for protocol?
1575    Entry->setAlignment(4);
1576  }
1577
1578  return Entry;
1579}
1580
1581/*
1582  struct _objc_protocol_extension {
1583    uint32_t size;
1584    struct objc_method_description_list *optional_instance_methods;
1585    struct objc_method_description_list *optional_class_methods;
1586    struct objc_property_list *instance_properties;
1587  };
1588*/
1589llvm::Constant *
1590CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1591                                 const ConstantVector &OptInstanceMethods,
1592                                 const ConstantVector &OptClassMethods) {
1593  uint64_t Size =
1594    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
1595  std::vector<llvm::Constant*> Values(4);
1596  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1597  Values[1] =
1598    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1599                           + PD->getNameAsString(),
1600                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1601                       OptInstanceMethods);
1602  Values[2] =
1603    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1604                          + PD->getNameAsString(),
1605                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1606                       OptClassMethods);
1607  Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1608                                   PD->getNameAsString(),
1609                               0, PD, ObjCTypes);
1610
1611  // Return null if no extension bits are used.
1612  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1613      Values[3]->isNullValue())
1614    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1615
1616  llvm::Constant *Init =
1617    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1618
1619  // No special section, but goes in llvm.used
1620  return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1621                           Init,
1622                           0, 0, true);
1623}
1624
1625/*
1626  struct objc_protocol_list {
1627    struct objc_protocol_list *next;
1628    long count;
1629    Protocol *list[];
1630  };
1631*/
1632llvm::Constant *
1633CGObjCMac::EmitProtocolList(const std::string &Name,
1634                            ObjCProtocolDecl::protocol_iterator begin,
1635                            ObjCProtocolDecl::protocol_iterator end) {
1636  std::vector<llvm::Constant*> ProtocolRefs;
1637
1638  for (; begin != end; ++begin)
1639    ProtocolRefs.push_back(GetProtocolRef(*begin));
1640
1641  // Just return null for empty protocol lists
1642  if (ProtocolRefs.empty())
1643    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1644
1645  // This list is null terminated.
1646  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1647
1648  std::vector<llvm::Constant*> Values(3);
1649  // This field is only used by the runtime.
1650  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1651  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1652  Values[2] =
1653    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1654                                                  ProtocolRefs.size()),
1655                             ProtocolRefs);
1656
1657  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1658  llvm::GlobalVariable *GV =
1659    CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1660                      4, false);
1661  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1662}
1663
1664/*
1665  struct _objc_property {
1666    const char * const name;
1667    const char * const attributes;
1668  };
1669
1670  struct _objc_property_list {
1671    uint32_t entsize; // sizeof (struct _objc_property)
1672    uint32_t prop_count;
1673    struct _objc_property[prop_count];
1674  };
1675*/
1676llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1677                                      const Decl *Container,
1678                                      const ObjCContainerDecl *OCD,
1679                                      const ObjCCommonTypesHelper &ObjCTypes) {
1680  std::vector<llvm::Constant*> Properties, Prop(2);
1681  for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1682       E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
1683    const ObjCPropertyDecl *PD = *I;
1684    Prop[0] = GetPropertyName(PD->getIdentifier());
1685    Prop[1] = GetPropertyTypeString(PD, Container);
1686    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1687                                                   Prop));
1688  }
1689
1690  // Return null for empty list.
1691  if (Properties.empty())
1692    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1693
1694  unsigned PropertySize =
1695    CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
1696  std::vector<llvm::Constant*> Values(3);
1697  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1698  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1699  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1700                                             Properties.size());
1701  Values[2] = llvm::ConstantArray::get(AT, Properties);
1702  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1703
1704  llvm::GlobalVariable *GV =
1705    CreateMetadataVar(Name, Init,
1706                      (ObjCABI == 2) ? "__DATA, __objc_const" :
1707                      "__OBJC,__property,regular,no_dead_strip",
1708                      (ObjCABI == 2) ? 8 : 4,
1709                      true);
1710  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
1711}
1712
1713/*
1714  struct objc_method_description_list {
1715    int count;
1716    struct objc_method_description list[];
1717  };
1718*/
1719llvm::Constant *
1720CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1721  std::vector<llvm::Constant*> Desc(2);
1722  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1723                                           ObjCTypes.SelectorPtrTy);
1724  Desc[1] = GetMethodVarType(MD);
1725  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1726                                   Desc);
1727}
1728
1729llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1730                                              const char *Section,
1731                                              const ConstantVector &Methods) {
1732  // Return null for empty list.
1733  if (Methods.empty())
1734    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1735
1736  std::vector<llvm::Constant*> Values(2);
1737  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1738  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1739                                             Methods.size());
1740  Values[1] = llvm::ConstantArray::get(AT, Methods);
1741  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1742
1743  llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
1744  return llvm::ConstantExpr::getBitCast(GV,
1745                                        ObjCTypes.MethodDescriptionListPtrTy);
1746}
1747
1748/*
1749  struct _objc_category {
1750    char *category_name;
1751    char *class_name;
1752    struct _objc_method_list *instance_methods;
1753    struct _objc_method_list *class_methods;
1754    struct _objc_protocol_list *protocols;
1755    uint32_t size; // <rdar://4585769>
1756    struct _objc_property_list *instance_properties;
1757  };
1758 */
1759void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1760  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
1761
1762  // FIXME: This is poor design, the OCD should have a pointer to the
1763  // category decl. Additionally, note that Category can be null for
1764  // the @implementation w/o an @interface case. Sema should just
1765  // create one for us as it does for @implementation so everyone else
1766  // can live life under a clear blue sky.
1767  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
1768  const ObjCCategoryDecl *Category =
1769    Interface->FindCategoryDeclaration(OCD->getIdentifier());
1770  std::string ExtName(Interface->getNameAsString() + "_" +
1771                      OCD->getNameAsString());
1772
1773  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1774  for (ObjCCategoryImplDecl::instmeth_iterator
1775         i = OCD->instmeth_begin(CGM.getContext()),
1776         e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
1777    // Instance methods should always be defined.
1778    InstanceMethods.push_back(GetMethodConstant(*i));
1779  }
1780  for (ObjCCategoryImplDecl::classmeth_iterator
1781         i = OCD->classmeth_begin(CGM.getContext()),
1782         e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
1783    // Class methods should always be defined.
1784    ClassMethods.push_back(GetMethodConstant(*i));
1785  }
1786
1787  std::vector<llvm::Constant*> Values(7);
1788  Values[0] = GetClassName(OCD->getIdentifier());
1789  Values[1] = GetClassName(Interface->getIdentifier());
1790  LazySymbols.insert(Interface->getIdentifier());
1791  Values[2] =
1792    EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1793                   ExtName,
1794                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1795                   InstanceMethods);
1796  Values[3] =
1797    EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1798                   "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1799                   ClassMethods);
1800  if (Category) {
1801    Values[4] =
1802      EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1803                       Category->protocol_begin(),
1804                       Category->protocol_end());
1805  } else {
1806    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1807  }
1808  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1809
1810  // If there is no category @interface then there can be no properties.
1811  if (Category) {
1812    Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
1813                                 OCD, Category, ObjCTypes);
1814  } else {
1815    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1816  }
1817
1818  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1819                                                   Values);
1820
1821  llvm::GlobalVariable *GV =
1822    CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1823                      "__OBJC,__category,regular,no_dead_strip",
1824                      4, true);
1825  DefinedCategories.push_back(GV);
1826}
1827
1828// FIXME: Get from somewhere?
1829enum ClassFlags {
1830  eClassFlags_Factory              = 0x00001,
1831  eClassFlags_Meta                 = 0x00002,
1832  // <rdr://5142207>
1833  eClassFlags_HasCXXStructors      = 0x02000,
1834  eClassFlags_Hidden               = 0x20000,
1835  eClassFlags_ABI2_Hidden          = 0x00010,
1836  eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
1837};
1838
1839/*
1840  struct _objc_class {
1841    Class isa;
1842    Class super_class;
1843    const char *name;
1844    long version;
1845    long info;
1846    long instance_size;
1847    struct _objc_ivar_list *ivars;
1848    struct _objc_method_list *methods;
1849    struct _objc_cache *cache;
1850    struct _objc_protocol_list *protocols;
1851    // Objective-C 1.0 extensions (<rdr://4585769>)
1852    const char *ivar_layout;
1853    struct _objc_class_ext *ext;
1854  };
1855
1856  See EmitClassExtension();
1857 */
1858void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
1859  DefinedSymbols.insert(ID->getIdentifier());
1860
1861  std::string ClassName = ID->getNameAsString();
1862  // FIXME: Gross
1863  ObjCInterfaceDecl *Interface =
1864    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1865  llvm::Constant *Protocols =
1866    EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
1867                     Interface->protocol_begin(),
1868                     Interface->protocol_end());
1869  unsigned Flags = eClassFlags_Factory;
1870  unsigned Size =
1871    CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
1872
1873  // FIXME: Set CXX-structors flag.
1874  if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
1875    Flags |= eClassFlags_Hidden;
1876
1877  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1878  for (ObjCImplementationDecl::instmeth_iterator
1879         i = ID->instmeth_begin(CGM.getContext()),
1880         e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
1881    // Instance methods should always be defined.
1882    InstanceMethods.push_back(GetMethodConstant(*i));
1883  }
1884  for (ObjCImplementationDecl::classmeth_iterator
1885         i = ID->classmeth_begin(CGM.getContext()),
1886         e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
1887    // Class methods should always be defined.
1888    ClassMethods.push_back(GetMethodConstant(*i));
1889  }
1890
1891  for (ObjCImplementationDecl::propimpl_iterator
1892         i = ID->propimpl_begin(CGM.getContext()),
1893         e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
1894    ObjCPropertyImplDecl *PID = *i;
1895
1896    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1897      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1898
1899      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1900        if (llvm::Constant *C = GetMethodConstant(MD))
1901          InstanceMethods.push_back(C);
1902      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1903        if (llvm::Constant *C = GetMethodConstant(MD))
1904          InstanceMethods.push_back(C);
1905    }
1906  }
1907
1908  std::vector<llvm::Constant*> Values(12);
1909  Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
1910  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
1911    // Record a reference to the super class.
1912    LazySymbols.insert(Super->getIdentifier());
1913
1914    Values[ 1] =
1915      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1916                                     ObjCTypes.ClassPtrTy);
1917  } else {
1918    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1919  }
1920  Values[ 2] = GetClassName(ID->getIdentifier());
1921  // Version is always 0.
1922  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1923  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1924  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1925  Values[ 6] = EmitIvarList(ID, false);
1926  Values[ 7] =
1927    EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
1928                   "__OBJC,__inst_meth,regular,no_dead_strip",
1929                   InstanceMethods);
1930  // cache is always NULL.
1931  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1932  Values[ 9] = Protocols;
1933  Values[10] = BuildIvarLayout(ID, true);
1934  Values[11] = EmitClassExtension(ID);
1935  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1936                                                   Values);
1937
1938  llvm::GlobalVariable *GV =
1939    CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1940                      "__OBJC,__class,regular,no_dead_strip",
1941                      4, true);
1942  DefinedClasses.push_back(GV);
1943}
1944
1945llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1946                                         llvm::Constant *Protocols,
1947                                         const ConstantVector &Methods) {
1948  unsigned Flags = eClassFlags_Meta;
1949  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
1950
1951  if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
1952    Flags |= eClassFlags_Hidden;
1953
1954  std::vector<llvm::Constant*> Values(12);
1955  // The isa for the metaclass is the root of the hierarchy.
1956  const ObjCInterfaceDecl *Root = ID->getClassInterface();
1957  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1958    Root = Super;
1959  Values[ 0] =
1960    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1961                                   ObjCTypes.ClassPtrTy);
1962  // The super class for the metaclass is emitted as the name of the
1963  // super class. The runtime fixes this up to point to the
1964  // *metaclass* for the super class.
1965  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1966    Values[ 1] =
1967      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1968                                     ObjCTypes.ClassPtrTy);
1969  } else {
1970    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1971  }
1972  Values[ 2] = GetClassName(ID->getIdentifier());
1973  // Version is always 0.
1974  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1975  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1976  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1977  Values[ 6] = EmitIvarList(ID, true);
1978  Values[ 7] =
1979    EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
1980                   "__OBJC,__cls_meth,regular,no_dead_strip",
1981                   Methods);
1982  // cache is always NULL.
1983  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1984  Values[ 9] = Protocols;
1985  // ivar_layout for metaclass is always NULL.
1986  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1987  // The class extension is always unused for metaclasses.
1988  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1989  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1990                                                   Values);
1991
1992  std::string Name("\01L_OBJC_METACLASS_");
1993  Name += ID->getNameAsCString();
1994
1995  // Check for a forward reference.
1996  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1997  if (GV) {
1998    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1999           "Forward metaclass reference has incorrect type.");
2000    GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2001    GV->setInitializer(Init);
2002  } else {
2003    GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2004                                  llvm::GlobalValue::InternalLinkage,
2005                                  Init, Name,
2006                                  &CGM.getModule());
2007  }
2008  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
2009  GV->setAlignment(4);
2010  UsedGlobals.push_back(GV);
2011
2012  return GV;
2013}
2014
2015llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
2016  std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
2017
2018  // FIXME: Should we look these up somewhere other than the
2019  // module. Its a bit silly since we only generate these while
2020  // processing an implementation, so exactly one pointer would work
2021  // if know when we entered/exitted an implementation block.
2022
2023  // Check for an existing forward reference.
2024  // Previously, metaclass with internal linkage may have been defined.
2025  // pass 'true' as 2nd argument so it is returned.
2026  if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
2027    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2028           "Forward metaclass reference has incorrect type.");
2029    return GV;
2030  } else {
2031    // Generate as an external reference to keep a consistent
2032    // module. This will be patched up when we emit the metaclass.
2033    return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2034                                    llvm::GlobalValue::ExternalLinkage,
2035                                    0,
2036                                    Name,
2037                                    &CGM.getModule());
2038  }
2039}
2040
2041/*
2042  struct objc_class_ext {
2043    uint32_t size;
2044    const char *weak_ivar_layout;
2045    struct _objc_property_list *properties;
2046  };
2047*/
2048llvm::Constant *
2049CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2050  uint64_t Size =
2051    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
2052
2053  std::vector<llvm::Constant*> Values(3);
2054  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
2055  Values[1] = BuildIvarLayout(ID, false);
2056  Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
2057                               ID, ID->getClassInterface(), ObjCTypes);
2058
2059  // Return null if no extension bits are used.
2060  if (Values[1]->isNullValue() && Values[2]->isNullValue())
2061    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2062
2063  llvm::Constant *Init =
2064    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
2065  return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
2066                           Init, "__OBJC,__class_ext,regular,no_dead_strip",
2067                           4, true);
2068}
2069
2070/// getInterfaceDeclForIvar - Get the interface declaration node where
2071/// this ivar is declared in.
2072/// FIXME. Ideally, this info should be in the ivar node. But currently
2073/// it is not and prevailing wisdom is that ASTs should not have more
2074/// info than is absolutely needed, even though this info reflects the
2075/// source language.
2076///
2077static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2078                                  const ObjCInterfaceDecl *OI,
2079                                  const ObjCIvarDecl *IVD,
2080                                  ASTContext &Context) {
2081  if (!OI)
2082    return 0;
2083  assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2084  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2085       E = OI->ivar_end(); I != E; ++I)
2086    if ((*I)->getIdentifier() == IVD->getIdentifier())
2087      return OI;
2088  // look into properties.
2089  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2090       E = OI->prop_end(Context); I != E; ++I) {
2091    ObjCPropertyDecl *PDecl = (*I);
2092    if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2093      if (IV->getIdentifier() == IVD->getIdentifier())
2094        return OI;
2095  }
2096  return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
2097}
2098
2099/*
2100  struct objc_ivar {
2101    char *ivar_name;
2102    char *ivar_type;
2103    int ivar_offset;
2104  };
2105
2106  struct objc_ivar_list {
2107    int ivar_count;
2108    struct objc_ivar list[count];
2109  };
2110 */
2111llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
2112                                        bool ForClass) {
2113  std::vector<llvm::Constant*> Ivars, Ivar(3);
2114
2115  // When emitting the root class GCC emits ivar entries for the
2116  // actual class structure. It is not clear if we need to follow this
2117  // behavior; for now lets try and get away with not doing it. If so,
2118  // the cleanest solution would be to make up an ObjCInterfaceDecl
2119  // for the class.
2120  if (ForClass)
2121    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2122
2123  ObjCInterfaceDecl *OID =
2124    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
2125
2126  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2127  GetNamedIvarList(OID, OIvars);
2128
2129  for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2130    ObjCIvarDecl *IVD = OIvars[i];
2131    Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2132    Ivar[1] = GetMethodVarType(IVD);
2133    Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
2134                                     ComputeIvarBaseOffset(CGM, OID, IVD));
2135    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
2136  }
2137
2138  // Return null for empty list.
2139  if (Ivars.empty())
2140    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2141
2142  std::vector<llvm::Constant*> Values(2);
2143  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2144  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2145                                             Ivars.size());
2146  Values[1] = llvm::ConstantArray::get(AT, Ivars);
2147  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2148
2149  llvm::GlobalVariable *GV;
2150  if (ForClass)
2151    GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
2152                           Init, "__OBJC,__class_vars,regular,no_dead_strip",
2153                           4, true);
2154  else
2155    GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2156                           + ID->getNameAsString(),
2157                           Init, "__OBJC,__instance_vars,regular,no_dead_strip",
2158                           4, true);
2159  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
2160}
2161
2162/*
2163  struct objc_method {
2164    SEL method_name;
2165    char *method_types;
2166    void *method;
2167  };
2168
2169  struct objc_method_list {
2170    struct objc_method_list *obsolete;
2171    int count;
2172    struct objc_method methods_list[count];
2173  };
2174*/
2175
2176/// GetMethodConstant - Return a struct objc_method constant for the
2177/// given method if it has been defined. The result is null if the
2178/// method has not been defined. The return value has type MethodPtrTy.
2179llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
2180  // FIXME: Use DenseMap::lookup
2181  llvm::Function *Fn = MethodDefinitions[MD];
2182  if (!Fn)
2183    return 0;
2184
2185  std::vector<llvm::Constant*> Method(3);
2186  Method[0] =
2187    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2188                                   ObjCTypes.SelectorPtrTy);
2189  Method[1] = GetMethodVarType(MD);
2190  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2191  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2192}
2193
2194llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2195                                          const char *Section,
2196                                          const ConstantVector &Methods) {
2197  // Return null for empty list.
2198  if (Methods.empty())
2199    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2200
2201  std::vector<llvm::Constant*> Values(3);
2202  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2203  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2204  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2205                                             Methods.size());
2206  Values[2] = llvm::ConstantArray::get(AT, Methods);
2207  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2208
2209  llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
2210  return llvm::ConstantExpr::getBitCast(GV,
2211                                        ObjCTypes.MethodListPtrTy);
2212}
2213
2214llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
2215                                                const ObjCContainerDecl *CD) {
2216  std::string Name;
2217  GetNameForMethod(OMD, CD, Name);
2218
2219  CodeGenTypes &Types = CGM.getTypes();
2220  const llvm::FunctionType *MethodTy =
2221    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
2222  llvm::Function *Method =
2223    llvm::Function::Create(MethodTy,
2224                           llvm::GlobalValue::InternalLinkage,
2225                           Name,
2226                           &CGM.getModule());
2227  MethodDefinitions.insert(std::make_pair(OMD, Method));
2228
2229  return Method;
2230}
2231
2232/// GetFieldBaseOffset - return the field's byte offset.
2233uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2234                                             const llvm::StructLayout *Layout,
2235                                             const FieldDecl *Field) {
2236  // Is this a C struct?
2237  if (!OI)
2238    return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2239  return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
2240}
2241
2242llvm::GlobalVariable *
2243CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2244                                   llvm::Constant *Init,
2245                                   const char *Section,
2246                                   unsigned Align,
2247                                   bool AddToUsed) {
2248  const llvm::Type *Ty = Init->getType();
2249  llvm::GlobalVariable *GV =
2250    new llvm::GlobalVariable(Ty, false,
2251                             llvm::GlobalValue::InternalLinkage,
2252                             Init,
2253                             Name,
2254                             &CGM.getModule());
2255  if (Section)
2256    GV->setSection(Section);
2257  if (Align)
2258    GV->setAlignment(Align);
2259  if (AddToUsed)
2260    UsedGlobals.push_back(GV);
2261  return GV;
2262}
2263
2264llvm::Function *CGObjCMac::ModuleInitFunction() {
2265  // Abuse this interface function as a place to finalize.
2266  FinishModule();
2267
2268  return NULL;
2269}
2270
2271llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
2272  return ObjCTypes.getGetPropertyFn();
2273}
2274
2275llvm::Constant *CGObjCMac::GetPropertySetFunction() {
2276  return ObjCTypes.getSetPropertyFn();
2277}
2278
2279llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
2280  return ObjCTypes.getEnumerationMutationFn();
2281}
2282
2283/*
2284
2285Objective-C setjmp-longjmp (sjlj) Exception Handling
2286--
2287
2288The basic framework for a @try-catch-finally is as follows:
2289{
2290  objc_exception_data d;
2291  id _rethrow = null;
2292  bool _call_try_exit = true;
2293
2294  objc_exception_try_enter(&d);
2295  if (!setjmp(d.jmp_buf)) {
2296    ... try body ...
2297  } else {
2298    // exception path
2299    id _caught = objc_exception_extract(&d);
2300
2301    // enter new try scope for handlers
2302    if (!setjmp(d.jmp_buf)) {
2303      ... match exception and execute catch blocks ...
2304
2305      // fell off end, rethrow.
2306      _rethrow = _caught;
2307      ... jump-through-finally to finally_rethrow ...
2308    } else {
2309      // exception in catch block
2310      _rethrow = objc_exception_extract(&d);
2311      _call_try_exit = false;
2312      ... jump-through-finally to finally_rethrow ...
2313    }
2314  }
2315  ... jump-through-finally to finally_end ...
2316
2317finally:
2318  if (_call_try_exit)
2319    objc_exception_try_exit(&d);
2320
2321  ... finally block ....
2322  ... dispatch to finally destination ...
2323
2324finally_rethrow:
2325  objc_exception_throw(_rethrow);
2326
2327finally_end:
2328}
2329
2330This framework differs slightly from the one gcc uses, in that gcc
2331uses _rethrow to determine if objc_exception_try_exit should be called
2332and if the object should be rethrown. This breaks in the face of
2333throwing nil and introduces unnecessary branches.
2334
2335We specialize this framework for a few particular circumstances:
2336
2337 - If there are no catch blocks, then we avoid emitting the second
2338   exception handling context.
2339
2340 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2341   e)) we avoid emitting the code to rethrow an uncaught exception.
2342
2343 - FIXME: If there is no @finally block we can do a few more
2344   simplifications.
2345
2346Rethrows and Jumps-Through-Finally
2347--
2348
2349Support for implicit rethrows and jumping through the finally block is
2350handled by storing the current exception-handling context in
2351ObjCEHStack.
2352
2353In order to implement proper @finally semantics, we support one basic
2354mechanism for jumping through the finally block to an arbitrary
2355destination. Constructs which generate exits from a @try or @catch
2356block use this mechanism to implement the proper semantics by chaining
2357jumps, as necessary.
2358
2359This mechanism works like the one used for indirect goto: we
2360arbitrarily assign an ID to each destination and store the ID for the
2361destination in a variable prior to entering the finally block. At the
2362end of the finally block we simply create a switch to the proper
2363destination.
2364
2365Code gen for @synchronized(expr) stmt;
2366Effectively generating code for:
2367objc_sync_enter(expr);
2368@try stmt @finally { objc_sync_exit(expr); }
2369*/
2370
2371void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2372                                          const Stmt &S) {
2373  bool isTry = isa<ObjCAtTryStmt>(S);
2374  // Create various blocks we refer to for handling @finally.
2375  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
2376  llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
2377  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2378  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2379  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
2380
2381  // For @synchronized, call objc_sync_enter(sync.expr). The
2382  // evaluation of the expression must occur before we enter the
2383  // @synchronized. We can safely avoid a temp here because jumps into
2384  // @synchronized are illegal & this will dominate uses.
2385  llvm::Value *SyncArg = 0;
2386  if (!isTry) {
2387    SyncArg =
2388      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2389    SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
2390    CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
2391  }
2392
2393  // Push an EH context entry, used for handling rethrows and jumps
2394  // through finally.
2395  CGF.PushCleanupBlock(FinallyBlock);
2396
2397  CGF.ObjCEHValueStack.push_back(0);
2398
2399  // Allocate memory for the exception data and rethrow pointer.
2400  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2401                                                    "exceptiondata.ptr");
2402  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2403                                                 "_rethrow");
2404  llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2405                                                     "_call_try_exit");
2406  CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2407
2408  // Enter a new try block and call setjmp.
2409  CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
2410  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2411                                                       "jmpbufarray");
2412  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2413  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
2414                                                     JmpBufPtr, "result");
2415
2416  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2417  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
2418  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
2419                           TryHandler, TryBlock);
2420
2421  // Emit the @try block.
2422  CGF.EmitBlock(TryBlock);
2423  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2424                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
2425  CGF.EmitBranchThroughCleanup(FinallyEnd);
2426
2427  // Emit the "exception in @try" block.
2428  CGF.EmitBlock(TryHandler);
2429
2430  // Retrieve the exception object.  We may emit multiple blocks but
2431  // nothing can cross this so the value is already in SSA form.
2432  llvm::Value *Caught =
2433    CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2434                           ExceptionData, "caught");
2435  CGF.ObjCEHValueStack.back() = Caught;
2436  if (!isTry)
2437  {
2438    CGF.Builder.CreateStore(Caught, RethrowPtr);
2439    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2440    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2441  }
2442  else if (const ObjCAtCatchStmt* CatchStmt =
2443           cast<ObjCAtTryStmt>(S).getCatchStmts())
2444  {
2445    // Enter a new exception try block (in case a @catch block throws
2446    // an exception).
2447    CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
2448
2449    llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
2450                                                       JmpBufPtr, "result");
2451    llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
2452
2453    llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2454    llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
2455    CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
2456
2457    CGF.EmitBlock(CatchBlock);
2458
2459    // Handle catch list. As a special case we check if everything is
2460    // matched and avoid generating code for falling off the end if
2461    // so.
2462    bool AllMatched = false;
2463    for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
2464      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
2465
2466      const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
2467      const PointerType *PT = 0;
2468
2469      // catch(...) always matches.
2470      if (!CatchParam) {
2471        AllMatched = true;
2472      } else {
2473        PT = CatchParam->getType()->getAsPointerType();
2474
2475        // catch(id e) always matches.
2476        // FIXME: For the time being we also match id<X>; this should
2477        // be rejected by Sema instead.
2478        if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
2479            CatchParam->getType()->isObjCQualifiedIdType())
2480          AllMatched = true;
2481      }
2482
2483      if (AllMatched) {
2484        if (CatchParam) {
2485          CGF.EmitLocalBlockVarDecl(*CatchParam);
2486          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
2487          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
2488        }
2489
2490        CGF.EmitStmt(CatchStmt->getCatchBody());
2491        CGF.EmitBranchThroughCleanup(FinallyEnd);
2492        break;
2493      }
2494
2495      assert(PT && "Unexpected non-pointer type in @catch");
2496      QualType T = PT->getPointeeType();
2497      const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
2498      assert(ObjCType && "Catch parameter must have Objective-C type!");
2499
2500      // Check if the @catch block matches the exception object.
2501      llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2502
2503      llvm::Value *Match =
2504        CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2505                                Class, Caught, "match");
2506
2507      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
2508
2509      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
2510                               MatchedBlock, NextCatchBlock);
2511
2512      // Emit the @catch block.
2513      CGF.EmitBlock(MatchedBlock);
2514      CGF.EmitLocalBlockVarDecl(*CatchParam);
2515      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
2516
2517      llvm::Value *Tmp =
2518        CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
2519                                  "tmp");
2520      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
2521
2522      CGF.EmitStmt(CatchStmt->getCatchBody());
2523      CGF.EmitBranchThroughCleanup(FinallyEnd);
2524
2525      CGF.EmitBlock(NextCatchBlock);
2526    }
2527
2528    if (!AllMatched) {
2529      // None of the handlers caught the exception, so store it to be
2530      // rethrown at the end of the @finally block.
2531      CGF.Builder.CreateStore(Caught, RethrowPtr);
2532      CGF.EmitBranchThroughCleanup(FinallyRethrow);
2533    }
2534
2535    // Emit the exception handler for the @catch blocks.
2536    CGF.EmitBlock(CatchHandler);
2537    CGF.Builder.CreateStore(
2538                    CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2539                                           ExceptionData),
2540                            RethrowPtr);
2541    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2542    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2543  } else {
2544    CGF.Builder.CreateStore(Caught, RethrowPtr);
2545    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2546    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2547  }
2548
2549  // Pop the exception-handling stack entry. It is important to do
2550  // this now, because the code in the @finally block is not in this
2551  // context.
2552  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2553
2554  CGF.ObjCEHValueStack.pop_back();
2555
2556  // Emit the @finally block.
2557  CGF.EmitBlock(FinallyBlock);
2558  llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2559
2560  CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2561
2562  CGF.EmitBlock(FinallyExit);
2563  CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
2564
2565  CGF.EmitBlock(FinallyNoExit);
2566  if (isTry) {
2567    if (const ObjCAtFinallyStmt* FinallyStmt =
2568          cast<ObjCAtTryStmt>(S).getFinallyStmt())
2569      CGF.EmitStmt(FinallyStmt->getFinallyBody());
2570  } else {
2571    // Emit objc_sync_exit(expr); as finally's sole statement for
2572    // @synchronized.
2573    CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
2574  }
2575
2576  // Emit the switch block
2577  if (Info.SwitchBlock)
2578    CGF.EmitBlock(Info.SwitchBlock);
2579  if (Info.EndBlock)
2580    CGF.EmitBlock(Info.EndBlock);
2581
2582  CGF.EmitBlock(FinallyRethrow);
2583  CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
2584                         CGF.Builder.CreateLoad(RethrowPtr));
2585  CGF.Builder.CreateUnreachable();
2586
2587  CGF.EmitBlock(FinallyEnd);
2588}
2589
2590void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
2591                              const ObjCAtThrowStmt &S) {
2592  llvm::Value *ExceptionAsObject;
2593
2594  if (const Expr *ThrowExpr = S.getThrowExpr()) {
2595    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2596    ExceptionAsObject =
2597      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2598  } else {
2599    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2600           "Unexpected rethrow outside @catch block.");
2601    ExceptionAsObject = CGF.ObjCEHValueStack.back();
2602  }
2603
2604  CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
2605  CGF.Builder.CreateUnreachable();
2606
2607  // Clear the insertion point to indicate we are in unreachable code.
2608  CGF.Builder.ClearInsertionPoint();
2609}
2610
2611/// EmitObjCWeakRead - Code gen for loading value of a __weak
2612/// object: objc_read_weak (id *src)
2613///
2614llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
2615                                          llvm::Value *AddrWeakObj)
2616{
2617  const llvm::Type* DestTy =
2618      cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
2619  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
2620  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
2621                                                  AddrWeakObj, "weakread");
2622  read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
2623  return read_weak;
2624}
2625
2626/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2627/// objc_assign_weak (id src, id *dst)
2628///
2629void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2630                                   llvm::Value *src, llvm::Value *dst)
2631{
2632  const llvm::Type * SrcTy = src->getType();
2633  if (!isa<llvm::PointerType>(SrcTy)) {
2634    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2635    assert(Size <= 8 && "does not support size > 8");
2636    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2637    : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2638    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2639  }
2640  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2641  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2642  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
2643                          src, dst, "weakassign");
2644  return;
2645}
2646
2647/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2648/// objc_assign_global (id src, id *dst)
2649///
2650void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2651                                     llvm::Value *src, llvm::Value *dst)
2652{
2653  const llvm::Type * SrcTy = src->getType();
2654  if (!isa<llvm::PointerType>(SrcTy)) {
2655    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2656    assert(Size <= 8 && "does not support size > 8");
2657    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2658    : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2659    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2660  }
2661  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2662  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2663  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
2664                          src, dst, "globalassign");
2665  return;
2666}
2667
2668/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2669/// objc_assign_ivar (id src, id *dst)
2670///
2671void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2672                                   llvm::Value *src, llvm::Value *dst)
2673{
2674  const llvm::Type * SrcTy = src->getType();
2675  if (!isa<llvm::PointerType>(SrcTy)) {
2676    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2677    assert(Size <= 8 && "does not support size > 8");
2678    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2679    : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2680    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2681  }
2682  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2683  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2684  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
2685                          src, dst, "assignivar");
2686  return;
2687}
2688
2689/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2690/// objc_assign_strongCast (id src, id *dst)
2691///
2692void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2693                                         llvm::Value *src, llvm::Value *dst)
2694{
2695  const llvm::Type * SrcTy = src->getType();
2696  if (!isa<llvm::PointerType>(SrcTy)) {
2697    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2698    assert(Size <= 8 && "does not support size > 8");
2699    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2700                      : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2701    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2702  }
2703  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2704  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2705  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
2706                          src, dst, "weakassign");
2707  return;
2708}
2709
2710/// EmitObjCValueForIvar - Code Gen for ivar reference.
2711///
2712LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2713                                       QualType ObjectTy,
2714                                       llvm::Value *BaseValue,
2715                                       const ObjCIvarDecl *Ivar,
2716                                       unsigned CVRQualifiers) {
2717  const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2718  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2719                                  EmitIvarOffset(CGF, ID, Ivar));
2720}
2721
2722llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2723                                       const ObjCInterfaceDecl *Interface,
2724                                       const ObjCIvarDecl *Ivar) {
2725  uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
2726  return llvm::ConstantInt::get(
2727                            CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2728                            Offset);
2729}
2730
2731/* *** Private Interface *** */
2732
2733/// EmitImageInfo - Emit the image info marker used to encode some module
2734/// level information.
2735///
2736/// See: <rdr://4810609&4810587&4810587>
2737/// struct IMAGE_INFO {
2738///   unsigned version;
2739///   unsigned flags;
2740/// };
2741enum ImageInfoFlags {
2742  eImageInfo_FixAndContinue      = (1 << 0), // FIXME: Not sure what
2743                                             // this implies.
2744  eImageInfo_GarbageCollected    = (1 << 1),
2745  eImageInfo_GCOnly              = (1 << 2),
2746  eImageInfo_OptimizedByDyld     = (1 << 3), // FIXME: When is this set.
2747
2748  // A flag indicating that the module has no instances of an
2749  // @synthesize of a superclass variable. <rdar://problem/6803242>
2750  eImageInfo_CorrectedSynthesize = (1 << 4)
2751};
2752
2753void CGObjCMac::EmitImageInfo() {
2754  unsigned version = 0; // Version is unused?
2755  unsigned flags = 0;
2756
2757  // FIXME: Fix and continue?
2758  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2759    flags |= eImageInfo_GarbageCollected;
2760  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2761    flags |= eImageInfo_GCOnly;
2762
2763  // We never allow @synthesize of a superclass property.
2764  flags |= eImageInfo_CorrectedSynthesize;
2765
2766  // Emitted as int[2];
2767  llvm::Constant *values[2] = {
2768    llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2769    llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2770  };
2771  llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
2772
2773  const char *Section;
2774  if (ObjCABI == 1)
2775    Section = "__OBJC, __image_info,regular";
2776  else
2777    Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
2778  llvm::GlobalVariable *GV =
2779    CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2780                      llvm::ConstantArray::get(AT, values, 2),
2781                      Section,
2782                      0,
2783                      true);
2784  GV->setConstant(true);
2785}
2786
2787
2788// struct objc_module {
2789//   unsigned long version;
2790//   unsigned long size;
2791//   const char *name;
2792//   Symtab symtab;
2793// };
2794
2795// FIXME: Get from somewhere
2796static const int ModuleVersion = 7;
2797
2798void CGObjCMac::EmitModuleInfo() {
2799  uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
2800
2801  std::vector<llvm::Constant*> Values(4);
2802  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2803  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
2804  // This used to be the filename, now it is unused. <rdr://4327263>
2805  Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
2806  Values[3] = EmitModuleSymbols();
2807  CreateMetadataVar("\01L_OBJC_MODULES",
2808                    llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2809                    "__OBJC,__module_info,regular,no_dead_strip",
2810                    4, true);
2811}
2812
2813llvm::Constant *CGObjCMac::EmitModuleSymbols() {
2814  unsigned NumClasses = DefinedClasses.size();
2815  unsigned NumCategories = DefinedCategories.size();
2816
2817  // Return null if no symbols were defined.
2818  if (!NumClasses && !NumCategories)
2819    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2820
2821  std::vector<llvm::Constant*> Values(5);
2822  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2823  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2824  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2825  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2826
2827  // The runtime expects exactly the list of defined classes followed
2828  // by the list of defined categories, in a single array.
2829  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
2830  for (unsigned i=0; i<NumClasses; i++)
2831    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2832                                                ObjCTypes.Int8PtrTy);
2833  for (unsigned i=0; i<NumCategories; i++)
2834    Symbols[NumClasses + i] =
2835      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2836                                     ObjCTypes.Int8PtrTy);
2837
2838  Values[4] =
2839    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2840                                                  NumClasses + NumCategories),
2841                             Symbols);
2842
2843  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2844
2845  llvm::GlobalVariable *GV =
2846    CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2847                      "__OBJC,__symbols,regular,no_dead_strip",
2848                      4, true);
2849  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2850}
2851
2852llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
2853                                     const ObjCInterfaceDecl *ID) {
2854  LazySymbols.insert(ID->getIdentifier());
2855
2856  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2857
2858  if (!Entry) {
2859    llvm::Constant *Casted =
2860      llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2861                                     ObjCTypes.ClassPtrTy);
2862    Entry =
2863      CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2864                        "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2865                        4, true);
2866  }
2867
2868  return Builder.CreateLoad(Entry, false, "tmp");
2869}
2870
2871llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
2872  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2873
2874  if (!Entry) {
2875    llvm::Constant *Casted =
2876      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2877                                     ObjCTypes.SelectorPtrTy);
2878    Entry =
2879      CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2880                        "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2881                        4, true);
2882  }
2883
2884  return Builder.CreateLoad(Entry, false, "tmp");
2885}
2886
2887llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
2888  llvm::GlobalVariable *&Entry = ClassNames[Ident];
2889
2890  if (!Entry)
2891    Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2892                              llvm::ConstantArray::get(Ident->getName()),
2893                              "__TEXT,__cstring,cstring_literals",
2894                              1, true);
2895
2896  return getConstantGEP(Entry, 0, 0);
2897}
2898
2899/// GetIvarLayoutName - Returns a unique constant for the given
2900/// ivar layout bitmap.
2901llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2902                                      const ObjCCommonTypesHelper &ObjCTypes) {
2903  return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2904}
2905
2906void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2907                              const llvm::StructLayout *Layout,
2908                              const RecordDecl *RD,
2909                             const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
2910                              unsigned int BytePos, bool ForStrongLayout,
2911                              bool &HasUnion) {
2912  bool IsUnion = (RD && RD->isUnion());
2913  uint64_t MaxUnionIvarSize = 0;
2914  uint64_t MaxSkippedUnionIvarSize = 0;
2915  FieldDecl *MaxField = 0;
2916  FieldDecl *MaxSkippedField = 0;
2917  FieldDecl *LastFieldBitfield = 0;
2918
2919  unsigned base = 0;
2920  if (RecFields.empty())
2921    return;
2922  if (IsUnion)
2923    base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
2924  unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2925  unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2926
2927  llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2928
2929  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2930    FieldDecl *Field = RecFields[i];
2931    // Skip over unnamed or bitfields
2932    if (!Field->getIdentifier() || Field->isBitField()) {
2933      LastFieldBitfield = Field;
2934      continue;
2935    }
2936    LastFieldBitfield = 0;
2937    QualType FQT = Field->getType();
2938    if (FQT->isRecordType() || FQT->isUnionType()) {
2939      if (FQT->isUnionType())
2940        HasUnion = true;
2941      else
2942        assert(FQT->isRecordType() &&
2943               "only union/record is supported for ivar layout bitmap");
2944
2945      const RecordType *RT = FQT->getAsRecordType();
2946      const RecordDecl *RD = RT->getDecl();
2947      // FIXME - Find a more efficient way of passing records down.
2948      TmpRecFields.append(RD->field_begin(CGM.getContext()),
2949                          RD->field_end(CGM.getContext()));
2950      const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2951      const llvm::StructLayout *RecLayout =
2952        CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2953
2954      BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
2955                          BytePos + GetFieldBaseOffset(OI, Layout, Field),
2956                          ForStrongLayout, HasUnion);
2957      TmpRecFields.clear();
2958      continue;
2959    }
2960
2961    if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2962      const ConstantArrayType *CArray =
2963                                 dyn_cast_or_null<ConstantArrayType>(Array);
2964      uint64_t ElCount = CArray->getSize().getZExtValue();
2965      assert(CArray && "only array with know element size is supported");
2966      FQT = CArray->getElementType();
2967      while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2968        const ConstantArrayType *CArray =
2969                                 dyn_cast_or_null<ConstantArrayType>(Array);
2970        ElCount *= CArray->getSize().getZExtValue();
2971        FQT = CArray->getElementType();
2972      }
2973
2974      assert(!FQT->isUnionType() &&
2975             "layout for array of unions not supported");
2976      if (FQT->isRecordType()) {
2977        int OldIndex = IvarsInfo.size() - 1;
2978        int OldSkIndex = SkipIvars.size() -1;
2979
2980        // FIXME - Use a common routine with the above!
2981        const RecordType *RT = FQT->getAsRecordType();
2982        const RecordDecl *RD = RT->getDecl();
2983        // FIXME - Find a more efficiant way of passing records down.
2984        TmpRecFields.append(RD->field_begin(CGM.getContext()),
2985                            RD->field_end(CGM.getContext()));
2986        const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2987        const llvm::StructLayout *RecLayout =
2988        CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2989
2990        BuildAggrIvarLayout(0, RecLayout, RD,
2991                            TmpRecFields,
2992                            BytePos + GetFieldBaseOffset(OI, Layout, Field),
2993                            ForStrongLayout, HasUnion);
2994        TmpRecFields.clear();
2995
2996        // Replicate layout information for each array element. Note that
2997        // one element is already done.
2998        uint64_t ElIx = 1;
2999        for (int FirstIndex = IvarsInfo.size() - 1,
3000                 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
3001          uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
3002          for (int i = OldIndex+1; i <= FirstIndex; ++i)
3003          {
3004            GC_IVAR gcivar;
3005            gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3006            gcivar.ivar_size = IvarsInfo[i].ivar_size;
3007            IvarsInfo.push_back(gcivar);
3008          }
3009
3010          for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
3011            GC_IVAR skivar;
3012            skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3013            skivar.ivar_size = SkipIvars[i].ivar_size;
3014            SkipIvars.push_back(skivar);
3015          }
3016        }
3017        continue;
3018      }
3019    }
3020    // At this point, we are done with Record/Union and array there of.
3021    // For other arrays we are down to its element type.
3022    QualType::GCAttrTypes GCAttr = QualType::GCNone;
3023    do {
3024      if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3025        GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3026        break;
3027      }
3028      else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
3029        GCAttr = QualType::Strong;
3030        break;
3031      }
3032      else if (const PointerType *PT = FQT->getAsPointerType()) {
3033        FQT = PT->getPointeeType();
3034      }
3035      else {
3036        break;
3037      }
3038    } while (true);
3039
3040    if ((ForStrongLayout && GCAttr == QualType::Strong)
3041        || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3042      if (IsUnion)
3043      {
3044        uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3045                                 / WordSizeInBits;
3046        if (UnionIvarSize > MaxUnionIvarSize)
3047        {
3048          MaxUnionIvarSize = UnionIvarSize;
3049          MaxField = Field;
3050        }
3051      }
3052      else
3053      {
3054        GC_IVAR gcivar;
3055        gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3056        gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3057                           WordSizeInBits;
3058        IvarsInfo.push_back(gcivar);
3059      }
3060    }
3061    else if ((ForStrongLayout &&
3062              (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3063             || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3064      if (IsUnion)
3065      {
3066        uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3067        if (UnionIvarSize > MaxSkippedUnionIvarSize)
3068        {
3069          MaxSkippedUnionIvarSize = UnionIvarSize;
3070          MaxSkippedField = Field;
3071        }
3072      }
3073      else
3074      {
3075        GC_IVAR skivar;
3076        skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3077        skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3078                           ByteSizeInBits;
3079        SkipIvars.push_back(skivar);
3080      }
3081    }
3082  }
3083  if (LastFieldBitfield) {
3084    // Last field was a bitfield. Must update skip info.
3085    GC_IVAR skivar;
3086    skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3087                                                       LastFieldBitfield);
3088    Expr *BitWidth = LastFieldBitfield->getBitWidth();
3089    uint64_t BitFieldSize =
3090      BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
3091    skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3092                         + ((BitFieldSize % ByteSizeInBits) != 0);
3093    SkipIvars.push_back(skivar);
3094  }
3095
3096  if (MaxField) {
3097    GC_IVAR gcivar;
3098    gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3099    gcivar.ivar_size = MaxUnionIvarSize;
3100    IvarsInfo.push_back(gcivar);
3101  }
3102
3103  if (MaxSkippedField) {
3104    GC_IVAR skivar;
3105    skivar.ivar_bytepos = BytePos +
3106                          GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3107    skivar.ivar_size = MaxSkippedUnionIvarSize;
3108    SkipIvars.push_back(skivar);
3109  }
3110}
3111
3112/// BuildIvarLayout - Builds ivar layout bitmap for the class
3113/// implementation for the __strong or __weak case.
3114/// The layout map displays which words in ivar list must be skipped
3115/// and which must be scanned by GC (see below). String is built of bytes.
3116/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3117/// of words to skip and right nibble is count of words to scan. So, each
3118/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3119/// represented by a 0x00 byte which also ends the string.
3120/// 1. when ForStrongLayout is true, following ivars are scanned:
3121/// - id, Class
3122/// - object *
3123/// - __strong anything
3124///
3125/// 2. When ForStrongLayout is false, following ivars are scanned:
3126/// - __weak anything
3127///
3128llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
3129                                      const ObjCImplementationDecl *OMD,
3130                                      bool ForStrongLayout) {
3131  bool hasUnion = false;
3132
3133  unsigned int WordsToScan, WordsToSkip;
3134  const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3135  if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3136    return llvm::Constant::getNullValue(PtrTy);
3137
3138  llvm::SmallVector<FieldDecl*, 32> RecFields;
3139  const ObjCInterfaceDecl *OI = OMD->getClassInterface();
3140  CGM.getContext().CollectObjCIvars(OI, RecFields);
3141  if (RecFields.empty())
3142    return llvm::Constant::getNullValue(PtrTy);
3143
3144  SkipIvars.clear();
3145  IvarsInfo.clear();
3146
3147  const llvm::StructLayout *Layout =
3148    CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
3149  BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, hasUnion);
3150  if (IvarsInfo.empty())
3151    return llvm::Constant::getNullValue(PtrTy);
3152
3153  // Sort on byte position in case we encounterred a union nested in
3154  // the ivar list.
3155  if (hasUnion && !IvarsInfo.empty())
3156    std::sort(IvarsInfo.begin(), IvarsInfo.end());
3157  if (hasUnion && !SkipIvars.empty())
3158    std::sort(SkipIvars.begin(), SkipIvars.end());
3159
3160  // Build the string of skip/scan nibbles
3161  llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
3162  unsigned int WordSize =
3163    CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
3164  if (IvarsInfo[0].ivar_bytepos == 0) {
3165    WordsToSkip = 0;
3166    WordsToScan = IvarsInfo[0].ivar_size;
3167  }
3168  else {
3169    WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3170    WordsToScan = IvarsInfo[0].ivar_size;
3171  }
3172  for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
3173  {
3174    unsigned int TailPrevGCObjC =
3175      IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3176    if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3177    {
3178      // consecutive 'scanned' object pointers.
3179      WordsToScan += IvarsInfo[i].ivar_size;
3180    }
3181    else
3182    {
3183      // Skip over 'gc'able object pointer which lay over each other.
3184      if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3185        continue;
3186      // Must skip over 1 or more words. We save current skip/scan values
3187      //  and start a new pair.
3188      SKIP_SCAN SkScan;
3189      SkScan.skip = WordsToSkip;
3190      SkScan.scan = WordsToScan;
3191      SkipScanIvars.push_back(SkScan);
3192
3193      // Skip the hole.
3194      SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3195      SkScan.scan = 0;
3196      SkipScanIvars.push_back(SkScan);
3197      WordsToSkip = 0;
3198      WordsToScan = IvarsInfo[i].ivar_size;
3199    }
3200  }
3201  if (WordsToScan > 0)
3202  {
3203    SKIP_SCAN SkScan;
3204    SkScan.skip = WordsToSkip;
3205    SkScan.scan = WordsToScan;
3206    SkipScanIvars.push_back(SkScan);
3207  }
3208
3209  bool BytesSkipped = false;
3210  if (!SkipIvars.empty())
3211  {
3212    unsigned int LastIndex = SkipIvars.size()-1;
3213    int LastByteSkipped =
3214          SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3215    LastIndex = IvarsInfo.size()-1;
3216    int LastByteScanned =
3217          IvarsInfo[LastIndex].ivar_bytepos +
3218          IvarsInfo[LastIndex].ivar_size * WordSize;
3219    BytesSkipped = (LastByteSkipped > LastByteScanned);
3220    // Compute number of bytes to skip at the tail end of the last ivar scanned.
3221    if (BytesSkipped)
3222    {
3223      unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
3224      SKIP_SCAN SkScan;
3225      SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3226      SkScan.scan = 0;
3227      SkipScanIvars.push_back(SkScan);
3228    }
3229  }
3230  // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3231  // as 0xMN.
3232  int SkipScan = SkipScanIvars.size()-1;
3233  for (int i = 0; i <= SkipScan; i++)
3234  {
3235    if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3236        && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3237      // 0xM0 followed by 0x0N detected.
3238      SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3239      for (int j = i+1; j < SkipScan; j++)
3240        SkipScanIvars[j] = SkipScanIvars[j+1];
3241      --SkipScan;
3242    }
3243  }
3244
3245  // Generate the string.
3246  std::string BitMap;
3247  for (int i = 0; i <= SkipScan; i++)
3248  {
3249    unsigned char byte;
3250    unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3251    unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3252    unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
3253    unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
3254
3255    if (skip_small > 0 || skip_big > 0)
3256      BytesSkipped = true;
3257    // first skip big.
3258    for (unsigned int ix = 0; ix < skip_big; ix++)
3259      BitMap += (unsigned char)(0xf0);
3260
3261    // next (skip small, scan)
3262    if (skip_small)
3263    {
3264      byte = skip_small << 4;
3265      if (scan_big > 0)
3266      {
3267        byte |= 0xf;
3268        --scan_big;
3269      }
3270      else if (scan_small)
3271      {
3272        byte |= scan_small;
3273        scan_small = 0;
3274      }
3275      BitMap += byte;
3276    }
3277    // next scan big
3278    for (unsigned int ix = 0; ix < scan_big; ix++)
3279      BitMap += (unsigned char)(0x0f);
3280    // last scan small
3281    if (scan_small)
3282    {
3283      byte = scan_small;
3284      BitMap += byte;
3285    }
3286  }
3287  // null terminate string.
3288  unsigned char zero = 0;
3289  BitMap += zero;
3290
3291  if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3292    printf("\n%s ivar layout for class '%s': ",
3293           ForStrongLayout ? "strong" : "weak",
3294           OMD->getClassInterface()->getNameAsCString());
3295    const unsigned char *s = (unsigned char*)BitMap.c_str();
3296    for (unsigned i = 0; i < BitMap.size(); i++)
3297      if (!(s[i] & 0xf0))
3298        printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3299      else
3300        printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
3301    printf("\n");
3302  }
3303
3304  // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3305  // final layout.
3306  if (ForStrongLayout && !BytesSkipped)
3307    return llvm::Constant::getNullValue(PtrTy);
3308  llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3309                                      llvm::ConstantArray::get(BitMap.c_str()),
3310                                      "__TEXT,__cstring,cstring_literals",
3311                                      1, true);
3312    return getConstantGEP(Entry, 0, 0);
3313}
3314
3315llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
3316  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3317
3318  // FIXME: Avoid std::string copying.
3319  if (!Entry)
3320    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3321                              llvm::ConstantArray::get(Sel.getAsString()),
3322                              "__TEXT,__cstring,cstring_literals",
3323                              1, true);
3324
3325  return getConstantGEP(Entry, 0, 0);
3326}
3327
3328// FIXME: Merge into a single cstring creation function.
3329llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
3330  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3331}
3332
3333// FIXME: Merge into a single cstring creation function.
3334llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
3335  return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3336}
3337
3338llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
3339  std::string TypeStr;
3340  CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3341
3342  llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3343
3344  if (!Entry)
3345    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3346                              llvm::ConstantArray::get(TypeStr),
3347                              "__TEXT,__cstring,cstring_literals",
3348                              1, true);
3349
3350  return getConstantGEP(Entry, 0, 0);
3351}
3352
3353llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
3354  std::string TypeStr;
3355  CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3356                                                TypeStr);
3357
3358  llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3359
3360  if (!Entry)
3361    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3362                              llvm::ConstantArray::get(TypeStr),
3363                              "__TEXT,__cstring,cstring_literals",
3364                              1, true);
3365
3366  return getConstantGEP(Entry, 0, 0);
3367}
3368
3369// FIXME: Merge into a single cstring creation function.
3370llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
3371  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3372
3373  if (!Entry)
3374    Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3375                              llvm::ConstantArray::get(Ident->getName()),
3376                              "__TEXT,__cstring,cstring_literals",
3377                              1, true);
3378
3379  return getConstantGEP(Entry, 0, 0);
3380}
3381
3382// FIXME: Merge into a single cstring creation function.
3383// FIXME: This Decl should be more precise.
3384llvm::Constant *
3385  CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3386                                         const Decl *Container) {
3387  std::string TypeStr;
3388  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
3389  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3390}
3391
3392void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3393                                       const ObjCContainerDecl *CD,
3394                                       std::string &NameOut) {
3395  NameOut = '\01';
3396  NameOut += (D->isInstanceMethod() ? '-' : '+');
3397  NameOut += '[';
3398  assert (CD && "Missing container decl in GetNameForMethod");
3399  NameOut += CD->getNameAsString();
3400  if (const ObjCCategoryImplDecl *CID =
3401      dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3402    NameOut += '(';
3403    NameOut += CID->getNameAsString();
3404    NameOut+= ')';
3405  }
3406  NameOut += ' ';
3407  NameOut += D->getSelector().getAsString();
3408  NameOut += ']';
3409}
3410
3411void CGObjCMac::FinishModule() {
3412  EmitModuleInfo();
3413
3414  // Emit the dummy bodies for any protocols which were referenced but
3415  // never defined.
3416  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3417         i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3418    if (i->second->hasInitializer())
3419      continue;
3420
3421    std::vector<llvm::Constant*> Values(5);
3422    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3423    Values[1] = GetClassName(i->first);
3424    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3425    Values[3] = Values[4] =
3426      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3427    i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3428    i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3429                                                        Values));
3430  }
3431
3432  std::vector<llvm::Constant*> Used;
3433  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3434         e = UsedGlobals.end(); i != e; ++i) {
3435    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3436  }
3437
3438  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3439  llvm::GlobalValue *GV =
3440    new llvm::GlobalVariable(AT, false,
3441                             llvm::GlobalValue::AppendingLinkage,
3442                             llvm::ConstantArray::get(AT, Used),
3443                             "llvm.used",
3444                             &CGM.getModule());
3445
3446  GV->setSection("llvm.metadata");
3447
3448  // Add assembler directives to add lazy undefined symbol references
3449  // for classes which are referenced but not defined. This is
3450  // important for correct linker interaction.
3451
3452  // FIXME: Uh, this isn't particularly portable.
3453  std::stringstream s;
3454
3455  if (!CGM.getModule().getModuleInlineAsm().empty())
3456    s << "\n";
3457
3458  for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3459         e = LazySymbols.end(); i != e; ++i) {
3460    s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3461  }
3462  for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3463         e = DefinedSymbols.end(); i != e; ++i) {
3464    s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
3465      << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3466  }
3467
3468  CGM.getModule().appendModuleInlineAsm(s.str());
3469}
3470
3471CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
3472  : CGObjCCommonMac(cgm),
3473  ObjCTypes(cgm)
3474{
3475  ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
3476  ObjCABI = 2;
3477}
3478
3479/* *** */
3480
3481ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3482: CGM(cgm)
3483{
3484  CodeGen::CodeGenTypes &Types = CGM.getTypes();
3485  ASTContext &Ctx = CGM.getContext();
3486
3487  ShortTy = Types.ConvertType(Ctx.ShortTy);
3488  IntTy = Types.ConvertType(Ctx.IntTy);
3489  LongTy = Types.ConvertType(Ctx.LongTy);
3490  LongLongTy = Types.ConvertType(Ctx.LongLongTy);
3491  Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3492
3493  ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
3494  PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
3495  SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
3496
3497  // FIXME: It would be nice to unify this with the opaque type, so
3498  // that the IR comes out a bit cleaner.
3499  const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3500  ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
3501
3502  // I'm not sure I like this. The implicit coordination is a bit
3503  // gross. We should solve this in a reasonable fashion because this
3504  // is a pretty common task (match some runtime data structure with
3505  // an LLVM data structure).
3506
3507  // FIXME: This is leaked.
3508  // FIXME: Merge with rewriter code?
3509
3510  // struct _objc_super {
3511  //   id self;
3512  //   Class cls;
3513  // }
3514  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3515                                      SourceLocation(),
3516                                      &Ctx.Idents.get("_objc_super"));
3517  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3518                                     Ctx.getObjCIdType(), 0, false));
3519  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3520                                     Ctx.getObjCClassType(), 0, false));
3521  RD->completeDefinition(Ctx);
3522
3523  SuperCTy = Ctx.getTagDeclType(RD);
3524  SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3525
3526  SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
3527  SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3528
3529  // struct _prop_t {
3530  //   char *name;
3531  //   char *attributes;
3532  // }
3533  PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
3534  CGM.getModule().addTypeName("struct._prop_t",
3535                              PropertyTy);
3536
3537  // struct _prop_list_t {
3538  //   uint32_t entsize;      // sizeof(struct _prop_t)
3539  //   uint32_t count_of_properties;
3540  //   struct _prop_t prop_list[count_of_properties];
3541  // }
3542  PropertyListTy = llvm::StructType::get(IntTy,
3543                                         IntTy,
3544                                         llvm::ArrayType::get(PropertyTy, 0),
3545                                         NULL);
3546  CGM.getModule().addTypeName("struct._prop_list_t",
3547                              PropertyListTy);
3548  // struct _prop_list_t *
3549  PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3550
3551  // struct _objc_method {
3552  //   SEL _cmd;
3553  //   char *method_type;
3554  //   char *_imp;
3555  // }
3556  MethodTy = llvm::StructType::get(SelectorPtrTy,
3557                                   Int8PtrTy,
3558                                   Int8PtrTy,
3559                                   NULL);
3560  CGM.getModule().addTypeName("struct._objc_method", MethodTy);
3561
3562  // struct _objc_cache *
3563  CacheTy = llvm::OpaqueType::get();
3564  CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3565  CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
3566}
3567
3568ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3569  : ObjCCommonTypesHelper(cgm)
3570{
3571  // struct _objc_method_description {
3572  //   SEL name;
3573  //   char *types;
3574  // }
3575  MethodDescriptionTy =
3576    llvm::StructType::get(SelectorPtrTy,
3577                          Int8PtrTy,
3578                          NULL);
3579  CGM.getModule().addTypeName("struct._objc_method_description",
3580                              MethodDescriptionTy);
3581
3582  // struct _objc_method_description_list {
3583  //   int count;
3584  //   struct _objc_method_description[1];
3585  // }
3586  MethodDescriptionListTy =
3587    llvm::StructType::get(IntTy,
3588                          llvm::ArrayType::get(MethodDescriptionTy, 0),
3589                          NULL);
3590  CGM.getModule().addTypeName("struct._objc_method_description_list",
3591                              MethodDescriptionListTy);
3592
3593  // struct _objc_method_description_list *
3594  MethodDescriptionListPtrTy =
3595    llvm::PointerType::getUnqual(MethodDescriptionListTy);
3596
3597  // Protocol description structures
3598
3599  // struct _objc_protocol_extension {
3600  //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
3601  //   struct _objc_method_description_list *optional_instance_methods;
3602  //   struct _objc_method_description_list *optional_class_methods;
3603  //   struct _objc_property_list *instance_properties;
3604  // }
3605  ProtocolExtensionTy =
3606    llvm::StructType::get(IntTy,
3607                          MethodDescriptionListPtrTy,
3608                          MethodDescriptionListPtrTy,
3609                          PropertyListPtrTy,
3610                          NULL);
3611  CGM.getModule().addTypeName("struct._objc_protocol_extension",
3612                              ProtocolExtensionTy);
3613
3614  // struct _objc_protocol_extension *
3615  ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3616
3617  // Handle recursive construction of Protocol and ProtocolList types
3618
3619  llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3620  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3621
3622  const llvm::Type *T =
3623    llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3624                          LongTy,
3625                          llvm::ArrayType::get(ProtocolTyHolder, 0),
3626                          NULL);
3627  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3628
3629  // struct _objc_protocol {
3630  //   struct _objc_protocol_extension *isa;
3631  //   char *protocol_name;
3632  //   struct _objc_protocol **_objc_protocol_list;
3633  //   struct _objc_method_description_list *instance_methods;
3634  //   struct _objc_method_description_list *class_methods;
3635  // }
3636  T = llvm::StructType::get(ProtocolExtensionPtrTy,
3637                            Int8PtrTy,
3638                            llvm::PointerType::getUnqual(ProtocolListTyHolder),
3639                            MethodDescriptionListPtrTy,
3640                            MethodDescriptionListPtrTy,
3641                            NULL);
3642  cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3643
3644  ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3645  CGM.getModule().addTypeName("struct._objc_protocol_list",
3646                              ProtocolListTy);
3647  // struct _objc_protocol_list *
3648  ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3649
3650  ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
3651  CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
3652  ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
3653
3654  // Class description structures
3655
3656  // struct _objc_ivar {
3657  //   char *ivar_name;
3658  //   char *ivar_type;
3659  //   int  ivar_offset;
3660  // }
3661  IvarTy = llvm::StructType::get(Int8PtrTy,
3662                                 Int8PtrTy,
3663                                 IntTy,
3664                                 NULL);
3665  CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3666
3667  // struct _objc_ivar_list *
3668  IvarListTy = llvm::OpaqueType::get();
3669  CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3670  IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3671
3672  // struct _objc_method_list *
3673  MethodListTy = llvm::OpaqueType::get();
3674  CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3675  MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3676
3677  // struct _objc_class_extension *
3678  ClassExtensionTy =
3679    llvm::StructType::get(IntTy,
3680                          Int8PtrTy,
3681                          PropertyListPtrTy,
3682                          NULL);
3683  CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3684  ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3685
3686  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3687
3688  // struct _objc_class {
3689  //   Class isa;
3690  //   Class super_class;
3691  //   char *name;
3692  //   long version;
3693  //   long info;
3694  //   long instance_size;
3695  //   struct _objc_ivar_list *ivars;
3696  //   struct _objc_method_list *methods;
3697  //   struct _objc_cache *cache;
3698  //   struct _objc_protocol_list *protocols;
3699  //   char *ivar_layout;
3700  //   struct _objc_class_ext *ext;
3701  // };
3702  T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3703                            llvm::PointerType::getUnqual(ClassTyHolder),
3704                            Int8PtrTy,
3705                            LongTy,
3706                            LongTy,
3707                            LongTy,
3708                            IvarListPtrTy,
3709                            MethodListPtrTy,
3710                            CachePtrTy,
3711                            ProtocolListPtrTy,
3712                            Int8PtrTy,
3713                            ClassExtensionPtrTy,
3714                            NULL);
3715  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3716
3717  ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3718  CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3719  ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3720
3721  // struct _objc_category {
3722  //   char *category_name;
3723  //   char *class_name;
3724  //   struct _objc_method_list *instance_method;
3725  //   struct _objc_method_list *class_method;
3726  //   uint32_t size;  // sizeof(struct _objc_category)
3727  //   struct _objc_property_list *instance_properties;// category's @property
3728  // }
3729  CategoryTy = llvm::StructType::get(Int8PtrTy,
3730                                     Int8PtrTy,
3731                                     MethodListPtrTy,
3732                                     MethodListPtrTy,
3733                                     ProtocolListPtrTy,
3734                                     IntTy,
3735                                     PropertyListPtrTy,
3736                                     NULL);
3737  CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3738
3739  // Global metadata structures
3740
3741  // struct _objc_symtab {
3742  //   long sel_ref_cnt;
3743  //   SEL *refs;
3744  //   short cls_def_cnt;
3745  //   short cat_def_cnt;
3746  //   char *defs[cls_def_cnt + cat_def_cnt];
3747  // }
3748  SymtabTy = llvm::StructType::get(LongTy,
3749                                   SelectorPtrTy,
3750                                   ShortTy,
3751                                   ShortTy,
3752                                   llvm::ArrayType::get(Int8PtrTy, 0),
3753                                   NULL);
3754  CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3755  SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3756
3757  // struct _objc_module {
3758  //   long version;
3759  //   long size;   // sizeof(struct _objc_module)
3760  //   char *name;
3761  //   struct _objc_symtab* symtab;
3762  //  }
3763  ModuleTy =
3764    llvm::StructType::get(LongTy,
3765                          LongTy,
3766                          Int8PtrTy,
3767                          SymtabPtrTy,
3768                          NULL);
3769  CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
3770
3771
3772  // FIXME: This is the size of the setjmp buffer and should be
3773  // target specific. 18 is what's used on 32-bit X86.
3774  uint64_t SetJmpBufferSize = 18;
3775
3776  // Exceptions
3777  const llvm::Type *StackPtrTy =
3778    llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
3779
3780  ExceptionDataTy =
3781    llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3782                                               SetJmpBufferSize),
3783                          StackPtrTy, NULL);
3784  CGM.getModule().addTypeName("struct._objc_exception_data",
3785                              ExceptionDataTy);
3786
3787}
3788
3789ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
3790: ObjCCommonTypesHelper(cgm)
3791{
3792  // struct _method_list_t {
3793  //   uint32_t entsize;  // sizeof(struct _objc_method)
3794  //   uint32_t method_count;
3795  //   struct _objc_method method_list[method_count];
3796  // }
3797  MethodListnfABITy = llvm::StructType::get(IntTy,
3798                                            IntTy,
3799                                            llvm::ArrayType::get(MethodTy, 0),
3800                                            NULL);
3801  CGM.getModule().addTypeName("struct.__method_list_t",
3802                              MethodListnfABITy);
3803  // struct method_list_t *
3804  MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
3805
3806  // struct _protocol_t {
3807  //   id isa;  // NULL
3808  //   const char * const protocol_name;
3809  //   const struct _protocol_list_t * protocol_list; // super protocols
3810  //   const struct method_list_t * const instance_methods;
3811  //   const struct method_list_t * const class_methods;
3812  //   const struct method_list_t *optionalInstanceMethods;
3813  //   const struct method_list_t *optionalClassMethods;
3814  //   const struct _prop_list_t * properties;
3815  //   const uint32_t size;  // sizeof(struct _protocol_t)
3816  //   const uint32_t flags;  // = 0
3817  // }
3818
3819  // Holder for struct _protocol_list_t *
3820  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3821
3822  ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3823                                          Int8PtrTy,
3824                                          llvm::PointerType::getUnqual(
3825                                            ProtocolListTyHolder),
3826                                          MethodListnfABIPtrTy,
3827                                          MethodListnfABIPtrTy,
3828                                          MethodListnfABIPtrTy,
3829                                          MethodListnfABIPtrTy,
3830                                          PropertyListPtrTy,
3831                                          IntTy,
3832                                          IntTy,
3833                                          NULL);
3834  CGM.getModule().addTypeName("struct._protocol_t",
3835                              ProtocolnfABITy);
3836
3837  // struct _protocol_t*
3838  ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
3839
3840  // struct _protocol_list_t {
3841  //   long protocol_count;   // Note, this is 32/64 bit
3842  //   struct _protocol_t *[protocol_count];
3843  // }
3844  ProtocolListnfABITy = llvm::StructType::get(LongTy,
3845                                              llvm::ArrayType::get(
3846                                                ProtocolnfABIPtrTy, 0),
3847                                              NULL);
3848  CGM.getModule().addTypeName("struct._objc_protocol_list",
3849                              ProtocolListnfABITy);
3850  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3851                                                      ProtocolListnfABITy);
3852
3853  // struct _objc_protocol_list*
3854  ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
3855
3856  // struct _ivar_t {
3857  //   unsigned long int *offset;  // pointer to ivar offset location
3858  //   char *name;
3859  //   char *type;
3860  //   uint32_t alignment;
3861  //   uint32_t size;
3862  // }
3863  IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3864                                      Int8PtrTy,
3865                                      Int8PtrTy,
3866                                      IntTy,
3867                                      IntTy,
3868                                      NULL);
3869  CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3870
3871  // struct _ivar_list_t {
3872  //   uint32 entsize;  // sizeof(struct _ivar_t)
3873  //   uint32 count;
3874  //   struct _iver_t list[count];
3875  // }
3876  IvarListnfABITy = llvm::StructType::get(IntTy,
3877                                          IntTy,
3878                                          llvm::ArrayType::get(
3879                                                               IvarnfABITy, 0),
3880                                          NULL);
3881  CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3882
3883  IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
3884
3885  // struct _class_ro_t {
3886  //   uint32_t const flags;
3887  //   uint32_t const instanceStart;
3888  //   uint32_t const instanceSize;
3889  //   uint32_t const reserved;  // only when building for 64bit targets
3890  //   const uint8_t * const ivarLayout;
3891  //   const char *const name;
3892  //   const struct _method_list_t * const baseMethods;
3893  //   const struct _objc_protocol_list *const baseProtocols;
3894  //   const struct _ivar_list_t *const ivars;
3895  //   const uint8_t * const weakIvarLayout;
3896  //   const struct _prop_list_t * const properties;
3897  // }
3898
3899  // FIXME. Add 'reserved' field in 64bit abi mode!
3900  ClassRonfABITy = llvm::StructType::get(IntTy,
3901                                         IntTy,
3902                                         IntTy,
3903                                         Int8PtrTy,
3904                                         Int8PtrTy,
3905                                         MethodListnfABIPtrTy,
3906                                         ProtocolListnfABIPtrTy,
3907                                         IvarListnfABIPtrTy,
3908                                         Int8PtrTy,
3909                                         PropertyListPtrTy,
3910                                         NULL);
3911  CGM.getModule().addTypeName("struct._class_ro_t",
3912                              ClassRonfABITy);
3913
3914  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3915  std::vector<const llvm::Type*> Params;
3916  Params.push_back(ObjectPtrTy);
3917  Params.push_back(SelectorPtrTy);
3918  ImpnfABITy = llvm::PointerType::getUnqual(
3919                          llvm::FunctionType::get(ObjectPtrTy, Params, false));
3920
3921  // struct _class_t {
3922  //   struct _class_t *isa;
3923  //   struct _class_t * const superclass;
3924  //   void *cache;
3925  //   IMP *vtable;
3926  //   struct class_ro_t *ro;
3927  // }
3928
3929  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3930  ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3931                                       llvm::PointerType::getUnqual(ClassTyHolder),
3932                                       CachePtrTy,
3933                                       llvm::PointerType::getUnqual(ImpnfABITy),
3934                                       llvm::PointerType::getUnqual(
3935                                                                ClassRonfABITy),
3936                                       NULL);
3937  CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3938
3939  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3940                                                                ClassnfABITy);
3941
3942  // LLVM for struct _class_t *
3943  ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3944
3945  // struct _category_t {
3946  //   const char * const name;
3947  //   struct _class_t *const cls;
3948  //   const struct _method_list_t * const instance_methods;
3949  //   const struct _method_list_t * const class_methods;
3950  //   const struct _protocol_list_t * const protocols;
3951  //   const struct _prop_list_t * const properties;
3952  // }
3953  CategorynfABITy = llvm::StructType::get(Int8PtrTy,
3954                                          ClassnfABIPtrTy,
3955                                          MethodListnfABIPtrTy,
3956                                          MethodListnfABIPtrTy,
3957                                          ProtocolListnfABIPtrTy,
3958                                          PropertyListPtrTy,
3959                                          NULL);
3960  CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
3961
3962  // New types for nonfragile abi messaging.
3963  CodeGen::CodeGenTypes &Types = CGM.getTypes();
3964  ASTContext &Ctx = CGM.getContext();
3965
3966  // MessageRefTy - LLVM for:
3967  // struct _message_ref_t {
3968  //   IMP messenger;
3969  //   SEL name;
3970  // };
3971
3972  // First the clang type for struct _message_ref_t
3973  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3974                                      SourceLocation(),
3975                                      &Ctx.Idents.get("_message_ref_t"));
3976  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3977                                     Ctx.VoidPtrTy, 0, false));
3978  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3979                                     Ctx.getObjCSelType(), 0, false));
3980  RD->completeDefinition(Ctx);
3981
3982  MessageRefCTy = Ctx.getTagDeclType(RD);
3983  MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3984  MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
3985
3986  // MessageRefPtrTy - LLVM for struct _message_ref_t*
3987  MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3988
3989  // SuperMessageRefTy - LLVM for:
3990  // struct _super_message_ref_t {
3991  //   SUPER_IMP messenger;
3992  //   SEL name;
3993  // };
3994  SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3995                                            SelectorPtrTy,
3996                                            NULL);
3997  CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3998
3999  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4000  SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4001
4002
4003  // struct objc_typeinfo {
4004  //   const void** vtable; // objc_ehtype_vtable + 2
4005  //   const char*  name;    // c++ typeinfo string
4006  //   Class        cls;
4007  // };
4008  EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4009                                   Int8PtrTy,
4010                                   ClassnfABIPtrTy,
4011                                   NULL);
4012  CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
4013  EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
4014}
4015
4016llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4017  FinishNonFragileABIModule();
4018
4019  return NULL;
4020}
4021
4022void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4023  // nonfragile abi has no module definition.
4024
4025  // Build list of all implemented classe addresses in array
4026  // L_OBJC_LABEL_CLASS_$.
4027  // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4028  // list of 'nonlazy' implementations (defined as those with a +load{}
4029  // method!!).
4030  unsigned NumClasses = DefinedClasses.size();
4031  if (NumClasses) {
4032    std::vector<llvm::Constant*> Symbols(NumClasses);
4033    for (unsigned i=0; i<NumClasses; i++)
4034      Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4035                                                  ObjCTypes.Int8PtrTy);
4036    llvm::Constant* Init =
4037      llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4038                                                    NumClasses),
4039                               Symbols);
4040
4041    llvm::GlobalVariable *GV =
4042      new llvm::GlobalVariable(Init->getType(), false,
4043                               llvm::GlobalValue::InternalLinkage,
4044                               Init,
4045                               "\01L_OBJC_LABEL_CLASS_$",
4046                               &CGM.getModule());
4047    GV->setAlignment(8);
4048    GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4049    UsedGlobals.push_back(GV);
4050  }
4051
4052  // Build list of all implemented category addresses in array
4053  // L_OBJC_LABEL_CATEGORY_$.
4054  // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4055  // list of 'nonlazy' category implementations (defined as those with a +load{}
4056  // method!!).
4057  unsigned NumCategory = DefinedCategories.size();
4058  if (NumCategory) {
4059    std::vector<llvm::Constant*> Symbols(NumCategory);
4060    for (unsigned i=0; i<NumCategory; i++)
4061      Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4062                                                  ObjCTypes.Int8PtrTy);
4063    llvm::Constant* Init =
4064      llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4065                                                    NumCategory),
4066                               Symbols);
4067
4068    llvm::GlobalVariable *GV =
4069      new llvm::GlobalVariable(Init->getType(), false,
4070                               llvm::GlobalValue::InternalLinkage,
4071                               Init,
4072                               "\01L_OBJC_LABEL_CATEGORY_$",
4073                               &CGM.getModule());
4074    GV->setAlignment(8);
4075    GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4076    UsedGlobals.push_back(GV);
4077  }
4078
4079  //  static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4080  // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4081  std::vector<llvm::Constant*> Values(2);
4082  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
4083  unsigned int flags = 0;
4084  // FIXME: Fix and continue?
4085  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4086    flags |= eImageInfo_GarbageCollected;
4087  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4088    flags |= eImageInfo_GCOnly;
4089  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4090  llvm::Constant* Init = llvm::ConstantArray::get(
4091                                      llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4092                                      Values);
4093  llvm::GlobalVariable *IMGV =
4094    new llvm::GlobalVariable(Init->getType(), false,
4095                             llvm::GlobalValue::InternalLinkage,
4096                             Init,
4097                             "\01L_OBJC_IMAGE_INFO",
4098                             &CGM.getModule());
4099  IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4100  IMGV->setConstant(true);
4101  UsedGlobals.push_back(IMGV);
4102
4103  std::vector<llvm::Constant*> Used;
4104
4105  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4106       e = UsedGlobals.end(); i != e; ++i) {
4107    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4108  }
4109
4110  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4111  llvm::GlobalValue *GV =
4112  new llvm::GlobalVariable(AT, false,
4113                           llvm::GlobalValue::AppendingLinkage,
4114                           llvm::ConstantArray::get(AT, Used),
4115                           "llvm.used",
4116                           &CGM.getModule());
4117
4118  GV->setSection("llvm.metadata");
4119
4120}
4121
4122// Metadata flags
4123enum MetaDataDlags {
4124  CLS = 0x0,
4125  CLS_META = 0x1,
4126  CLS_ROOT = 0x2,
4127  OBJC2_CLS_HIDDEN = 0x10,
4128  CLS_EXCEPTION = 0x20
4129};
4130/// BuildClassRoTInitializer - generate meta-data for:
4131/// struct _class_ro_t {
4132///   uint32_t const flags;
4133///   uint32_t const instanceStart;
4134///   uint32_t const instanceSize;
4135///   uint32_t const reserved;  // only when building for 64bit targets
4136///   const uint8_t * const ivarLayout;
4137///   const char *const name;
4138///   const struct _method_list_t * const baseMethods;
4139///   const struct _protocol_list_t *const baseProtocols;
4140///   const struct _ivar_list_t *const ivars;
4141///   const uint8_t * const weakIvarLayout;
4142///   const struct _prop_list_t * const properties;
4143/// }
4144///
4145llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4146                                                unsigned flags,
4147                                                unsigned InstanceStart,
4148                                                unsigned InstanceSize,
4149                                                const ObjCImplementationDecl *ID) {
4150  std::string ClassName = ID->getNameAsString();
4151  std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4152  Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4153  Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4154  Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4155  // FIXME. For 64bit targets add 0 here.
4156  Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4157                                  : BuildIvarLayout(ID, true);
4158  Values[ 4] = GetClassName(ID->getIdentifier());
4159  // const struct _method_list_t * const baseMethods;
4160  std::vector<llvm::Constant*> Methods;
4161  std::string MethodListName("\01l_OBJC_$_");
4162  if (flags & CLS_META) {
4163    MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4164    for (ObjCImplementationDecl::classmeth_iterator
4165           i = ID->classmeth_begin(CGM.getContext()),
4166           e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
4167      // Class methods should always be defined.
4168      Methods.push_back(GetMethodConstant(*i));
4169    }
4170  } else {
4171    MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4172    for (ObjCImplementationDecl::instmeth_iterator
4173           i = ID->instmeth_begin(CGM.getContext()),
4174           e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
4175      // Instance methods should always be defined.
4176      Methods.push_back(GetMethodConstant(*i));
4177    }
4178    for (ObjCImplementationDecl::propimpl_iterator
4179           i = ID->propimpl_begin(CGM.getContext()),
4180           e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
4181      ObjCPropertyImplDecl *PID = *i;
4182
4183      if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4184        ObjCPropertyDecl *PD = PID->getPropertyDecl();
4185
4186        if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4187          if (llvm::Constant *C = GetMethodConstant(MD))
4188            Methods.push_back(C);
4189        if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4190          if (llvm::Constant *C = GetMethodConstant(MD))
4191            Methods.push_back(C);
4192      }
4193    }
4194  }
4195  Values[ 5] = EmitMethodList(MethodListName,
4196               "__DATA, __objc_const", Methods);
4197
4198  const ObjCInterfaceDecl *OID = ID->getClassInterface();
4199  assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4200  Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4201                                + OID->getNameAsString(),
4202                                OID->protocol_begin(),
4203                                OID->protocol_end());
4204
4205  if (flags & CLS_META)
4206    Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4207  else
4208    Values[ 7] = EmitIvarList(ID);
4209  Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4210                                  : BuildIvarLayout(ID, false);
4211  if (flags & CLS_META)
4212    Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4213  else
4214    Values[ 9] =
4215      EmitPropertyList(
4216                       "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4217                       ID, ID->getClassInterface(), ObjCTypes);
4218  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4219                                                   Values);
4220  llvm::GlobalVariable *CLASS_RO_GV =
4221  new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4222                           llvm::GlobalValue::InternalLinkage,
4223                           Init,
4224                           (flags & CLS_META) ?
4225                           std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4226                           std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4227                           &CGM.getModule());
4228  CLASS_RO_GV->setAlignment(
4229    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
4230  CLASS_RO_GV->setSection("__DATA, __objc_const");
4231  return CLASS_RO_GV;
4232
4233}
4234
4235/// BuildClassMetaData - This routine defines that to-level meta-data
4236/// for the given ClassName for:
4237/// struct _class_t {
4238///   struct _class_t *isa;
4239///   struct _class_t * const superclass;
4240///   void *cache;
4241///   IMP *vtable;
4242///   struct class_ro_t *ro;
4243/// }
4244///
4245llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4246                                                std::string &ClassName,
4247                                                llvm::Constant *IsAGV,
4248                                                llvm::Constant *SuperClassGV,
4249                                                llvm::Constant *ClassRoGV,
4250                                                bool HiddenVisibility) {
4251  std::vector<llvm::Constant*> Values(5);
4252  Values[0] = IsAGV;
4253  Values[1] = SuperClassGV
4254                ? SuperClassGV
4255                : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
4256  Values[2] = ObjCEmptyCacheVar;  // &ObjCEmptyCacheVar
4257  Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4258  Values[4] = ClassRoGV;                 // &CLASS_RO_GV
4259  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4260                                                   Values);
4261  llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4262  GV->setInitializer(Init);
4263  GV->setSection("__DATA, __objc_data");
4264  GV->setAlignment(
4265    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
4266  if (HiddenVisibility)
4267    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4268  return GV;
4269}
4270
4271void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
4272                                              uint32_t &InstanceStart,
4273                                              uint32_t &InstanceSize) {
4274  // Find first and last (non-padding) ivars in this interface.
4275
4276  // FIXME: Use iterator.
4277  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4278  GetNamedIvarList(OID->getClassInterface(), OIvars);
4279
4280  if (OIvars.empty()) {
4281    InstanceStart = InstanceSize = 0;
4282    return;
4283  }
4284
4285  const ObjCIvarDecl *First = OIvars.front();
4286  const ObjCIvarDecl *Last = OIvars.back();
4287
4288  InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4289  const llvm::Type *FieldTy =
4290    CGM.getTypes().ConvertTypeForMem(Last->getType());
4291  unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4292// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4293// with gcc-4.2). We postpone this for now.
4294#if 0
4295  if (Last->isBitField()) {
4296    Expr *BitWidth = Last->getBitWidth();
4297    uint64_t BitFieldSize =
4298      BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
4299    Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4300  }
4301#endif
4302  InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
4303}
4304
4305void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4306  std::string ClassName = ID->getNameAsString();
4307  if (!ObjCEmptyCacheVar) {
4308    ObjCEmptyCacheVar = new llvm::GlobalVariable(
4309                                            ObjCTypes.CacheTy,
4310                                            false,
4311                                            llvm::GlobalValue::ExternalLinkage,
4312                                            0,
4313                                            "_objc_empty_cache",
4314                                            &CGM.getModule());
4315
4316    ObjCEmptyVtableVar = new llvm::GlobalVariable(
4317                            ObjCTypes.ImpnfABITy,
4318                            false,
4319                            llvm::GlobalValue::ExternalLinkage,
4320                            0,
4321                            "_objc_empty_vtable",
4322                            &CGM.getModule());
4323  }
4324  assert(ID->getClassInterface() &&
4325         "CGObjCNonFragileABIMac::GenerateClass - class is 0");
4326  // FIXME: Is this correct (that meta class size is never computed)?
4327  uint32_t InstanceStart =
4328    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4329  uint32_t InstanceSize = InstanceStart;
4330  uint32_t flags = CLS_META;
4331  std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4332  std::string ObjCClassName(getClassSymbolPrefix());
4333
4334  llvm::GlobalVariable *SuperClassGV, *IsAGV;
4335
4336  bool classIsHidden =
4337    CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
4338  if (classIsHidden)
4339    flags |= OBJC2_CLS_HIDDEN;
4340  if (!ID->getClassInterface()->getSuperClass()) {
4341    // class is root
4342    flags |= CLS_ROOT;
4343    SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4344    IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
4345  } else {
4346    // Has a root. Current class is not a root.
4347    const ObjCInterfaceDecl *Root = ID->getClassInterface();
4348    while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4349      Root = Super;
4350    IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
4351    // work on super class metadata symbol.
4352    std::string SuperClassName =
4353      ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
4354    SuperClassGV = GetClassGlobal(SuperClassName);
4355  }
4356  llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4357                                                               InstanceStart,
4358                                                               InstanceSize,ID);
4359  std::string TClassName = ObjCMetaClassName + ClassName;
4360  llvm::GlobalVariable *MetaTClass =
4361    BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4362                       classIsHidden);
4363
4364  // Metadata for the class
4365  flags = CLS;
4366  if (classIsHidden)
4367    flags |= OBJC2_CLS_HIDDEN;
4368
4369  if (hasObjCExceptionAttribute(ID->getClassInterface()))
4370    flags |= CLS_EXCEPTION;
4371
4372  if (!ID->getClassInterface()->getSuperClass()) {
4373    flags |= CLS_ROOT;
4374    SuperClassGV = 0;
4375  } else {
4376    // Has a root. Current class is not a root.
4377    std::string RootClassName =
4378      ID->getClassInterface()->getSuperClass()->getNameAsString();
4379    SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
4380  }
4381  GetClassSizeInfo(ID, InstanceStart, InstanceSize);
4382  CLASS_RO_GV = BuildClassRoTInitializer(flags,
4383                                         InstanceStart,
4384                                         InstanceSize,
4385                                         ID);
4386
4387  TClassName = ObjCClassName + ClassName;
4388  llvm::GlobalVariable *ClassMD =
4389    BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4390                       classIsHidden);
4391  DefinedClasses.push_back(ClassMD);
4392
4393  // Force the definition of the EHType if necessary.
4394  if (flags & CLS_EXCEPTION)
4395    GetInterfaceEHType(ID->getClassInterface(), true);
4396}
4397
4398/// GenerateProtocolRef - This routine is called to generate code for
4399/// a protocol reference expression; as in:
4400/// @code
4401///   @protocol(Proto1);
4402/// @endcode
4403/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4404/// which will hold address of the protocol meta-data.
4405///
4406llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4407                                            const ObjCProtocolDecl *PD) {
4408
4409  // This routine is called for @protocol only. So, we must build definition
4410  // of protocol's meta-data (not a reference to it!)
4411  //
4412  llvm::Constant *Init =  llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
4413                                        ObjCTypes.ExternalProtocolPtrTy);
4414
4415  std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4416  ProtocolName += PD->getNameAsCString();
4417
4418  llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4419  if (PTGV)
4420    return Builder.CreateLoad(PTGV, false, "tmp");
4421  PTGV = new llvm::GlobalVariable(
4422                                Init->getType(), false,
4423                                llvm::GlobalValue::WeakAnyLinkage,
4424                                Init,
4425                                ProtocolName,
4426                                &CGM.getModule());
4427  PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4428  PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4429  UsedGlobals.push_back(PTGV);
4430  return Builder.CreateLoad(PTGV, false, "tmp");
4431}
4432
4433/// GenerateCategory - Build metadata for a category implementation.
4434/// struct _category_t {
4435///   const char * const name;
4436///   struct _class_t *const cls;
4437///   const struct _method_list_t * const instance_methods;
4438///   const struct _method_list_t * const class_methods;
4439///   const struct _protocol_list_t * const protocols;
4440///   const struct _prop_list_t * const properties;
4441/// }
4442///
4443void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4444{
4445  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
4446  const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4447  std::string ExtCatName(Prefix + Interface->getNameAsString()+
4448                      "_$_" + OCD->getNameAsString());
4449  std::string ExtClassName(getClassSymbolPrefix() +
4450                           Interface->getNameAsString());
4451
4452  std::vector<llvm::Constant*> Values(6);
4453  Values[0] = GetClassName(OCD->getIdentifier());
4454  // meta-class entry symbol
4455  llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
4456  Values[1] = ClassGV;
4457  std::vector<llvm::Constant*> Methods;
4458  std::string MethodListName(Prefix);
4459  MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4460    "_$_" + OCD->getNameAsString();
4461
4462  for (ObjCCategoryImplDecl::instmeth_iterator
4463         i = OCD->instmeth_begin(CGM.getContext()),
4464         e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
4465    // Instance methods should always be defined.
4466    Methods.push_back(GetMethodConstant(*i));
4467  }
4468
4469  Values[2] = EmitMethodList(MethodListName,
4470                             "__DATA, __objc_const",
4471                             Methods);
4472
4473  MethodListName = Prefix;
4474  MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4475    OCD->getNameAsString();
4476  Methods.clear();
4477  for (ObjCCategoryImplDecl::classmeth_iterator
4478         i = OCD->classmeth_begin(CGM.getContext()),
4479         e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
4480    // Class methods should always be defined.
4481    Methods.push_back(GetMethodConstant(*i));
4482  }
4483
4484  Values[3] = EmitMethodList(MethodListName,
4485                             "__DATA, __objc_const",
4486                             Methods);
4487  const ObjCCategoryDecl *Category =
4488    Interface->FindCategoryDeclaration(OCD->getIdentifier());
4489  if (Category) {
4490    std::string ExtName(Interface->getNameAsString() + "_$_" +
4491                        OCD->getNameAsString());
4492    Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4493                                 + Interface->getNameAsString() + "_$_"
4494                                 + Category->getNameAsString(),
4495                                 Category->protocol_begin(),
4496                                 Category->protocol_end());
4497    Values[5] =
4498      EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4499                       OCD, Category, ObjCTypes);
4500  }
4501  else {
4502    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4503    Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4504  }
4505
4506  llvm::Constant *Init =
4507    llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4508                              Values);
4509  llvm::GlobalVariable *GCATV
4510    = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4511                               false,
4512                               llvm::GlobalValue::InternalLinkage,
4513                               Init,
4514                               ExtCatName,
4515                               &CGM.getModule());
4516  GCATV->setAlignment(
4517    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
4518  GCATV->setSection("__DATA, __objc_const");
4519  UsedGlobals.push_back(GCATV);
4520  DefinedCategories.push_back(GCATV);
4521}
4522
4523/// GetMethodConstant - Return a struct objc_method constant for the
4524/// given method if it has been defined. The result is null if the
4525/// method has not been defined. The return value has type MethodPtrTy.
4526llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4527                                                    const ObjCMethodDecl *MD) {
4528  // FIXME: Use DenseMap::lookup
4529  llvm::Function *Fn = MethodDefinitions[MD];
4530  if (!Fn)
4531    return 0;
4532
4533  std::vector<llvm::Constant*> Method(3);
4534  Method[0] =
4535  llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4536                                 ObjCTypes.SelectorPtrTy);
4537  Method[1] = GetMethodVarType(MD);
4538  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4539  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4540}
4541
4542/// EmitMethodList - Build meta-data for method declarations
4543/// struct _method_list_t {
4544///   uint32_t entsize;  // sizeof(struct _objc_method)
4545///   uint32_t method_count;
4546///   struct _objc_method method_list[method_count];
4547/// }
4548///
4549llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4550                                              const std::string &Name,
4551                                              const char *Section,
4552                                              const ConstantVector &Methods) {
4553  // Return null for empty list.
4554  if (Methods.empty())
4555    return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4556
4557  std::vector<llvm::Constant*> Values(3);
4558  // sizeof(struct _objc_method)
4559  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4560  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4561  // method_count
4562  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4563  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4564                                             Methods.size());
4565  Values[2] = llvm::ConstantArray::get(AT, Methods);
4566  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4567
4568  llvm::GlobalVariable *GV =
4569    new llvm::GlobalVariable(Init->getType(), false,
4570                             llvm::GlobalValue::InternalLinkage,
4571                             Init,
4572                             Name,
4573                             &CGM.getModule());
4574  GV->setAlignment(
4575    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4576  GV->setSection(Section);
4577  UsedGlobals.push_back(GV);
4578  return llvm::ConstantExpr::getBitCast(GV,
4579                                        ObjCTypes.MethodListnfABIPtrTy);
4580}
4581
4582/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4583/// the given ivar.
4584///
4585llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4586                              const ObjCInterfaceDecl *ID,
4587                              const ObjCIvarDecl *Ivar) {
4588  std::string Name = "OBJC_IVAR_$_" +
4589    getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4590    '.' + Ivar->getNameAsString();
4591  llvm::GlobalVariable *IvarOffsetGV =
4592    CGM.getModule().getGlobalVariable(Name);
4593  if (!IvarOffsetGV)
4594    IvarOffsetGV =
4595      new llvm::GlobalVariable(ObjCTypes.LongTy,
4596                               false,
4597                               llvm::GlobalValue::ExternalLinkage,
4598                               0,
4599                               Name,
4600                               &CGM.getModule());
4601  return IvarOffsetGV;
4602}
4603
4604llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
4605                                              const ObjCInterfaceDecl *ID,
4606                                              const ObjCIvarDecl *Ivar,
4607                                              unsigned long int Offset) {
4608  llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4609  IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4610                                                      Offset));
4611  IvarOffsetGV->setAlignment(
4612    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
4613
4614  // FIXME: This matches gcc, but shouldn't the visibility be set on
4615  // the use as well (i.e., in ObjCIvarOffsetVariable).
4616  if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4617      Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4618      CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
4619    IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4620  else
4621    IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
4622  IvarOffsetGV->setSection("__DATA, __objc_const");
4623  return IvarOffsetGV;
4624}
4625
4626/// EmitIvarList - Emit the ivar list for the given
4627/// implementation. The return value has type
4628/// IvarListnfABIPtrTy.
4629///  struct _ivar_t {
4630///   unsigned long int *offset;  // pointer to ivar offset location
4631///   char *name;
4632///   char *type;
4633///   uint32_t alignment;
4634///   uint32_t size;
4635/// }
4636/// struct _ivar_list_t {
4637///   uint32 entsize;  // sizeof(struct _ivar_t)
4638///   uint32 count;
4639///   struct _iver_t list[count];
4640/// }
4641///
4642
4643void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4644                              llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4645  for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4646         E = OID->ivar_end(); I != E; ++I) {
4647    // Ignore unnamed bit-fields.
4648    if (!(*I)->getDeclName())
4649      continue;
4650
4651     Res.push_back(*I);
4652  }
4653
4654  for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4655         E = OID->prop_end(CGM.getContext()); I != E; ++I)
4656    if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4657      Res.push_back(IV);
4658}
4659
4660llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4661                                            const ObjCImplementationDecl *ID) {
4662
4663  std::vector<llvm::Constant*> Ivars, Ivar(5);
4664
4665  const ObjCInterfaceDecl *OID = ID->getClassInterface();
4666  assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4667
4668  // FIXME. Consolidate this with similar code in GenerateClass.
4669
4670  // Collect declared and synthesized ivars in a small vector.
4671  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4672  GetNamedIvarList(OID, OIvars);
4673
4674  for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4675    ObjCIvarDecl *IVD = OIvars[i];
4676    Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
4677                                ComputeIvarBaseOffset(CGM, ID, IVD));
4678    Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4679    Ivar[2] = GetMethodVarType(IVD);
4680    const llvm::Type *FieldTy =
4681      CGM.getTypes().ConvertTypeForMem(IVD->getType());
4682    unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4683    unsigned Align = CGM.getContext().getPreferredTypeAlign(
4684                       IVD->getType().getTypePtr()) >> 3;
4685    Align = llvm::Log2_32(Align);
4686    Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
4687    // NOTE. Size of a bitfield does not match gcc's, because of the
4688    // way bitfields are treated special in each. But I am told that
4689    // 'size' for bitfield ivars is ignored by the runtime so it does
4690    // not matter.  If it matters, there is enough info to get the
4691    // bitfield right!
4692    Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4693    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4694  }
4695  // Return null for empty list.
4696  if (Ivars.empty())
4697    return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4698  std::vector<llvm::Constant*> Values(3);
4699  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4700  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4701  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4702  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4703                                             Ivars.size());
4704  Values[2] = llvm::ConstantArray::get(AT, Ivars);
4705  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4706  const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4707  llvm::GlobalVariable *GV =
4708    new llvm::GlobalVariable(Init->getType(), false,
4709                             llvm::GlobalValue::InternalLinkage,
4710                             Init,
4711                             Prefix + OID->getNameAsString(),
4712                             &CGM.getModule());
4713  GV->setAlignment(
4714    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4715  GV->setSection("__DATA, __objc_const");
4716
4717  UsedGlobals.push_back(GV);
4718  return llvm::ConstantExpr::getBitCast(GV,
4719                                        ObjCTypes.IvarListnfABIPtrTy);
4720}
4721
4722llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4723                                                  const ObjCProtocolDecl *PD) {
4724  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4725
4726  if (!Entry) {
4727    // We use the initializer as a marker of whether this is a forward
4728    // reference or not. At module finalization we add the empty
4729    // contents for protocols which were referenced but never defined.
4730    Entry =
4731    new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4732                             llvm::GlobalValue::ExternalLinkage,
4733                             0,
4734                             "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4735                             &CGM.getModule());
4736    Entry->setSection("__DATA,__datacoal_nt,coalesced");
4737    UsedGlobals.push_back(Entry);
4738  }
4739
4740  return Entry;
4741}
4742
4743/// GetOrEmitProtocol - Generate the protocol meta-data:
4744/// @code
4745/// struct _protocol_t {
4746///   id isa;  // NULL
4747///   const char * const protocol_name;
4748///   const struct _protocol_list_t * protocol_list; // super protocols
4749///   const struct method_list_t * const instance_methods;
4750///   const struct method_list_t * const class_methods;
4751///   const struct method_list_t *optionalInstanceMethods;
4752///   const struct method_list_t *optionalClassMethods;
4753///   const struct _prop_list_t * properties;
4754///   const uint32_t size;  // sizeof(struct _protocol_t)
4755///   const uint32_t flags;  // = 0
4756/// }
4757/// @endcode
4758///
4759
4760llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4761                                                  const ObjCProtocolDecl *PD) {
4762  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4763
4764  // Early exit if a defining object has already been generated.
4765  if (Entry && Entry->hasInitializer())
4766    return Entry;
4767
4768  const char *ProtocolName = PD->getNameAsCString();
4769
4770  // Construct method lists.
4771  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4772  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4773  for (ObjCProtocolDecl::instmeth_iterator
4774         i = PD->instmeth_begin(CGM.getContext()),
4775         e = PD->instmeth_end(CGM.getContext());
4776       i != e; ++i) {
4777    ObjCMethodDecl *MD = *i;
4778    llvm::Constant *C = GetMethodDescriptionConstant(MD);
4779    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4780      OptInstanceMethods.push_back(C);
4781    } else {
4782      InstanceMethods.push_back(C);
4783    }
4784  }
4785
4786  for (ObjCProtocolDecl::classmeth_iterator
4787         i = PD->classmeth_begin(CGM.getContext()),
4788         e = PD->classmeth_end(CGM.getContext());
4789       i != e; ++i) {
4790    ObjCMethodDecl *MD = *i;
4791    llvm::Constant *C = GetMethodDescriptionConstant(MD);
4792    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4793      OptClassMethods.push_back(C);
4794    } else {
4795      ClassMethods.push_back(C);
4796    }
4797  }
4798
4799  std::vector<llvm::Constant*> Values(10);
4800  // isa is NULL
4801  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4802  Values[1] = GetClassName(PD->getIdentifier());
4803  Values[2] = EmitProtocolList(
4804                          "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4805                          PD->protocol_begin(),
4806                          PD->protocol_end());
4807
4808  Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
4809                             + PD->getNameAsString(),
4810                             "__DATA, __objc_const",
4811                             InstanceMethods);
4812  Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
4813                             + PD->getNameAsString(),
4814                             "__DATA, __objc_const",
4815                             ClassMethods);
4816  Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
4817                             + PD->getNameAsString(),
4818                             "__DATA, __objc_const",
4819                             OptInstanceMethods);
4820  Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
4821                             + PD->getNameAsString(),
4822                             "__DATA, __objc_const",
4823                             OptClassMethods);
4824  Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4825                               0, PD, ObjCTypes);
4826  uint32_t Size =
4827    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4828  Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4829  Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4830  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4831                                                   Values);
4832
4833  if (Entry) {
4834    // Already created, fix the linkage and update the initializer.
4835    Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
4836    Entry->setInitializer(Init);
4837  } else {
4838    Entry =
4839    new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4840                             llvm::GlobalValue::WeakAnyLinkage,
4841                             Init,
4842                             std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4843                             &CGM.getModule());
4844    Entry->setAlignment(
4845      CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
4846    Entry->setSection("__DATA,__datacoal_nt,coalesced");
4847  }
4848  Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4849
4850  // Use this protocol meta-data to build protocol list table in section
4851  // __DATA, __objc_protolist
4852  llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
4853                                      ObjCTypes.ProtocolnfABIPtrTy, false,
4854                                      llvm::GlobalValue::WeakAnyLinkage,
4855                                      Entry,
4856                                      std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4857                                                  +ProtocolName,
4858                                      &CGM.getModule());
4859  PTGV->setAlignment(
4860    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
4861  PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
4862  PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4863  UsedGlobals.push_back(PTGV);
4864  return Entry;
4865}
4866
4867/// EmitProtocolList - Generate protocol list meta-data:
4868/// @code
4869/// struct _protocol_list_t {
4870///   long protocol_count;   // Note, this is 32/64 bit
4871///   struct _protocol_t[protocol_count];
4872/// }
4873/// @endcode
4874///
4875llvm::Constant *
4876CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4877                            ObjCProtocolDecl::protocol_iterator begin,
4878                            ObjCProtocolDecl::protocol_iterator end) {
4879  std::vector<llvm::Constant*> ProtocolRefs;
4880
4881  // Just return null for empty protocol lists
4882  if (begin == end)
4883    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4884
4885  // FIXME: We shouldn't need to do this lookup here, should we?
4886  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4887  if (GV)
4888    return llvm::ConstantExpr::getBitCast(GV,
4889                                          ObjCTypes.ProtocolListnfABIPtrTy);
4890
4891  for (; begin != end; ++begin)
4892    ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
4893
4894  // This list is null terminated.
4895  ProtocolRefs.push_back(llvm::Constant::getNullValue(
4896                                            ObjCTypes.ProtocolnfABIPtrTy));
4897
4898  std::vector<llvm::Constant*> Values(2);
4899  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4900  Values[1] =
4901    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
4902                                                  ProtocolRefs.size()),
4903                                                  ProtocolRefs);
4904
4905  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4906  GV = new llvm::GlobalVariable(Init->getType(), false,
4907                                llvm::GlobalValue::InternalLinkage,
4908                                Init,
4909                                Name,
4910                                &CGM.getModule());
4911  GV->setSection("__DATA, __objc_const");
4912  GV->setAlignment(
4913    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4914  UsedGlobals.push_back(GV);
4915  return llvm::ConstantExpr::getBitCast(GV,
4916                                        ObjCTypes.ProtocolListnfABIPtrTy);
4917}
4918
4919/// GetMethodDescriptionConstant - This routine build following meta-data:
4920/// struct _objc_method {
4921///   SEL _cmd;
4922///   char *method_type;
4923///   char *_imp;
4924/// }
4925
4926llvm::Constant *
4927CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4928  std::vector<llvm::Constant*> Desc(3);
4929  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4930                                           ObjCTypes.SelectorPtrTy);
4931  Desc[1] = GetMethodVarType(MD);
4932  // Protocol methods have no implementation. So, this entry is always NULL.
4933  Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4934  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4935}
4936
4937/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4938/// This code gen. amounts to generating code for:
4939/// @code
4940/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4941/// @encode
4942///
4943LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
4944                                             CodeGen::CodeGenFunction &CGF,
4945                                             QualType ObjectTy,
4946                                             llvm::Value *BaseValue,
4947                                             const ObjCIvarDecl *Ivar,
4948                                             unsigned CVRQualifiers) {
4949  const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4950  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4951                                  EmitIvarOffset(CGF, ID, Ivar));
4952}
4953
4954llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4955                                       CodeGen::CodeGenFunction &CGF,
4956                                       const ObjCInterfaceDecl *Interface,
4957                                       const ObjCIvarDecl *Ivar) {
4958  return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4959                                false, "ivar");
4960}
4961
4962CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4963                                           CodeGen::CodeGenFunction &CGF,
4964                                           QualType ResultType,
4965                                           Selector Sel,
4966                                           llvm::Value *Receiver,
4967                                           QualType Arg0Ty,
4968                                           bool IsSuper,
4969                                           const CallArgList &CallArgs) {
4970  // FIXME. Even though IsSuper is passes. This function doese not
4971  // handle calls to 'super' receivers.
4972  CodeGenTypes &Types = CGM.getTypes();
4973  llvm::Value *Arg0 = Receiver;
4974  if (!IsSuper)
4975    Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
4976
4977  // Find the message function name.
4978  // FIXME. This is too much work to get the ABI-specific result type
4979  // needed to find the message name.
4980  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4981                                        llvm::SmallVector<QualType, 16>());
4982  llvm::Constant *Fn = 0;
4983  std::string Name("\01l_");
4984  if (CGM.ReturnTypeUsesSret(FnInfo)) {
4985#if 0
4986    // unlike what is documented. gcc never generates this API!!
4987    if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4988      Fn = ObjCTypes.getMessageSendIdStretFixupFn();
4989      // FIXME. Is there a better way of getting these names.
4990      // They are available in RuntimeFunctions vector pair.
4991      Name += "objc_msgSendId_stret_fixup";
4992    }
4993    else
4994#endif
4995    if (IsSuper) {
4996        Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
4997        Name += "objc_msgSendSuper2_stret_fixup";
4998    }
4999    else
5000    {
5001      Fn = ObjCTypes.getMessageSendStretFixupFn();
5002      Name += "objc_msgSend_stret_fixup";
5003    }
5004  }
5005  else if (!IsSuper && ResultType->isFloatingType()) {
5006    if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5007      BuiltinType::Kind k = BT->getKind();
5008      if (k == BuiltinType::LongDouble) {
5009        Fn = ObjCTypes.getMessageSendFpretFixupFn();
5010        Name += "objc_msgSend_fpret_fixup";
5011      }
5012      else {
5013        Fn = ObjCTypes.getMessageSendFixupFn();
5014        Name += "objc_msgSend_fixup";
5015      }
5016    }
5017  }
5018  else {
5019#if 0
5020// unlike what is documented. gcc never generates this API!!
5021    if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
5022      Fn = ObjCTypes.getMessageSendIdFixupFn();
5023      Name += "objc_msgSendId_fixup";
5024    }
5025    else
5026#endif
5027    if (IsSuper) {
5028        Fn = ObjCTypes.getMessageSendSuper2FixupFn();
5029        Name += "objc_msgSendSuper2_fixup";
5030    }
5031    else
5032    {
5033      Fn = ObjCTypes.getMessageSendFixupFn();
5034      Name += "objc_msgSend_fixup";
5035    }
5036  }
5037  assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
5038  Name += '_';
5039  std::string SelName(Sel.getAsString());
5040  // Replace all ':' in selector name with '_'  ouch!
5041  for(unsigned i = 0; i < SelName.size(); i++)
5042    if (SelName[i] == ':')
5043      SelName[i] = '_';
5044  Name += SelName;
5045  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5046  if (!GV) {
5047    // Build message ref table entry.
5048    std::vector<llvm::Constant*> Values(2);
5049    Values[0] = Fn;
5050    Values[1] = GetMethodVarName(Sel);
5051    llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5052    GV =  new llvm::GlobalVariable(Init->getType(), false,
5053                                   llvm::GlobalValue::WeakAnyLinkage,
5054                                   Init,
5055                                   Name,
5056                                   &CGM.getModule());
5057    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5058    GV->setAlignment(16);
5059    GV->setSection("__DATA, __objc_msgrefs, coalesced");
5060  }
5061  llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
5062
5063  CallArgList ActualArgs;
5064  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5065  ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5066                                      ObjCTypes.MessageRefCPtrTy));
5067  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
5068  const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5069  llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5070  Callee = CGF.Builder.CreateLoad(Callee);
5071  const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
5072  Callee = CGF.Builder.CreateBitCast(Callee,
5073                                     llvm::PointerType::getUnqual(FTy));
5074  return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
5075}
5076
5077/// Generate code for a message send expression in the nonfragile abi.
5078CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5079                                               CodeGen::CodeGenFunction &CGF,
5080                                               QualType ResultType,
5081                                               Selector Sel,
5082                                               llvm::Value *Receiver,
5083                                               bool IsClassMessage,
5084                                               const CallArgList &CallArgs) {
5085  return EmitMessageSend(CGF, ResultType, Sel,
5086                         Receiver, CGF.getContext().getObjCIdType(),
5087                         false, CallArgs);
5088}
5089
5090llvm::GlobalVariable *
5091CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
5092  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5093
5094  if (!GV) {
5095    GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5096                                  llvm::GlobalValue::ExternalLinkage,
5097                                  0, Name, &CGM.getModule());
5098  }
5099
5100  return GV;
5101}
5102
5103llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
5104                                     const ObjCInterfaceDecl *ID) {
5105  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5106
5107  if (!Entry) {
5108    std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5109    llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5110    Entry =
5111      new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5112                               llvm::GlobalValue::InternalLinkage,
5113                               ClassGV,
5114                               "\01L_OBJC_CLASSLIST_REFERENCES_$_",
5115                               &CGM.getModule());
5116    Entry->setAlignment(
5117                     CGM.getTargetData().getPrefTypeAlignment(
5118                                                  ObjCTypes.ClassnfABIPtrTy));
5119    Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5120    UsedGlobals.push_back(Entry);
5121  }
5122
5123  return Builder.CreateLoad(Entry, false, "tmp");
5124}
5125
5126llvm::Value *
5127CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5128                                          const ObjCInterfaceDecl *ID) {
5129  llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5130
5131  if (!Entry) {
5132    std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5133    llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5134    Entry =
5135      new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5136                               llvm::GlobalValue::InternalLinkage,
5137                               ClassGV,
5138                               "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5139                               &CGM.getModule());
5140    Entry->setAlignment(
5141                     CGM.getTargetData().getPrefTypeAlignment(
5142                                                  ObjCTypes.ClassnfABIPtrTy));
5143    Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
5144    UsedGlobals.push_back(Entry);
5145  }
5146
5147  return Builder.CreateLoad(Entry, false, "tmp");
5148}
5149
5150/// EmitMetaClassRef - Return a Value * of the address of _class_t
5151/// meta-data
5152///
5153llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5154                                                  const ObjCInterfaceDecl *ID) {
5155  llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5156  if (Entry)
5157    return Builder.CreateLoad(Entry, false, "tmp");
5158
5159  std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
5160  llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
5161  Entry =
5162    new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5163                             llvm::GlobalValue::InternalLinkage,
5164                             MetaClassGV,
5165                             "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5166                             &CGM.getModule());
5167  Entry->setAlignment(
5168                      CGM.getTargetData().getPrefTypeAlignment(
5169                                                  ObjCTypes.ClassnfABIPtrTy));
5170
5171  Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
5172  UsedGlobals.push_back(Entry);
5173
5174  return Builder.CreateLoad(Entry, false, "tmp");
5175}
5176
5177/// GetClass - Return a reference to the class for the given interface
5178/// decl.
5179llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5180                                              const ObjCInterfaceDecl *ID) {
5181  return EmitClassRef(Builder, ID);
5182}
5183
5184/// Generates a message send where the super is the receiver.  This is
5185/// a message send to self with special delivery semantics indicating
5186/// which class's method should be called.
5187CodeGen::RValue
5188CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5189                                    QualType ResultType,
5190                                    Selector Sel,
5191                                    const ObjCInterfaceDecl *Class,
5192                                    bool isCategoryImpl,
5193                                    llvm::Value *Receiver,
5194                                    bool IsClassMessage,
5195                                    const CodeGen::CallArgList &CallArgs) {
5196  // ...
5197  // Create and init a super structure; this is a (receiver, class)
5198  // pair we will pass to objc_msgSendSuper.
5199  llvm::Value *ObjCSuper =
5200    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5201
5202  llvm::Value *ReceiverAsObject =
5203    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5204  CGF.Builder.CreateStore(ReceiverAsObject,
5205                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5206
5207  // If this is a class message the metaclass is passed as the target.
5208  llvm::Value *Target;
5209  if (IsClassMessage) {
5210    if (isCategoryImpl) {
5211      // Message sent to "super' in a class method defined in
5212      // a category implementation.
5213      Target = EmitClassRef(CGF.Builder, Class);
5214      Target = CGF.Builder.CreateStructGEP(Target, 0);
5215      Target = CGF.Builder.CreateLoad(Target);
5216    }
5217    else
5218      Target = EmitMetaClassRef(CGF.Builder, Class);
5219  }
5220  else
5221    Target = EmitSuperClassRef(CGF.Builder, Class);
5222
5223  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5224  // and ObjCTypes types.
5225  const llvm::Type *ClassTy =
5226    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5227  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5228  CGF.Builder.CreateStore(Target,
5229                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5230
5231  return EmitMessageSend(CGF, ResultType, Sel,
5232                         ObjCSuper, ObjCTypes.SuperPtrCTy,
5233                         true, CallArgs);
5234}
5235
5236llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5237                                                  Selector Sel) {
5238  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5239
5240  if (!Entry) {
5241    llvm::Constant *Casted =
5242    llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5243                                   ObjCTypes.SelectorPtrTy);
5244    Entry =
5245    new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5246                             llvm::GlobalValue::InternalLinkage,
5247                             Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5248                             &CGM.getModule());
5249    Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5250    UsedGlobals.push_back(Entry);
5251  }
5252
5253  return Builder.CreateLoad(Entry, false, "tmp");
5254}
5255/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5256/// objc_assign_ivar (id src, id *dst)
5257///
5258void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5259                                   llvm::Value *src, llvm::Value *dst)
5260{
5261  const llvm::Type * SrcTy = src->getType();
5262  if (!isa<llvm::PointerType>(SrcTy)) {
5263    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5264    assert(Size <= 8 && "does not support size > 8");
5265    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5266           : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5267    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5268  }
5269  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5270  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5271  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
5272                          src, dst, "assignivar");
5273  return;
5274}
5275
5276/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5277/// objc_assign_strongCast (id src, id *dst)
5278///
5279void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5280                                         CodeGen::CodeGenFunction &CGF,
5281                                         llvm::Value *src, llvm::Value *dst)
5282{
5283  const llvm::Type * SrcTy = src->getType();
5284  if (!isa<llvm::PointerType>(SrcTy)) {
5285    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5286    assert(Size <= 8 && "does not support size > 8");
5287    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5288                     : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5289    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5290  }
5291  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5292  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5293  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
5294                          src, dst, "weakassign");
5295  return;
5296}
5297
5298/// EmitObjCWeakRead - Code gen for loading value of a __weak
5299/// object: objc_read_weak (id *src)
5300///
5301llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5302                                          CodeGen::CodeGenFunction &CGF,
5303                                          llvm::Value *AddrWeakObj)
5304{
5305  const llvm::Type* DestTy =
5306      cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
5307  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5308  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
5309                                                  AddrWeakObj, "weakread");
5310  read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
5311  return read_weak;
5312}
5313
5314/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5315/// objc_assign_weak (id src, id *dst)
5316///
5317void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5318                                   llvm::Value *src, llvm::Value *dst)
5319{
5320  const llvm::Type * SrcTy = src->getType();
5321  if (!isa<llvm::PointerType>(SrcTy)) {
5322    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5323    assert(Size <= 8 && "does not support size > 8");
5324    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5325           : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5326    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5327  }
5328  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5329  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5330  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
5331                          src, dst, "weakassign");
5332  return;
5333}
5334
5335/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5336/// objc_assign_global (id src, id *dst)
5337///
5338void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5339                                     llvm::Value *src, llvm::Value *dst)
5340{
5341  const llvm::Type * SrcTy = src->getType();
5342  if (!isa<llvm::PointerType>(SrcTy)) {
5343    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5344    assert(Size <= 8 && "does not support size > 8");
5345    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5346           : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5347    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5348  }
5349  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5350  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5351  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
5352                          src, dst, "globalassign");
5353  return;
5354}
5355
5356void
5357CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5358                                                  const Stmt &S) {
5359  bool isTry = isa<ObjCAtTryStmt>(S);
5360  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5361  llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
5362  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
5363  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
5364  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
5365  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5366
5367  // For @synchronized, call objc_sync_enter(sync.expr). The
5368  // evaluation of the expression must occur before we enter the
5369  // @synchronized. We can safely avoid a temp here because jumps into
5370  // @synchronized are illegal & this will dominate uses.
5371  llvm::Value *SyncArg = 0;
5372  if (!isTry) {
5373    SyncArg =
5374      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5375    SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
5376    CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
5377  }
5378
5379  // Push an EH context entry, used for handling rethrows and jumps
5380  // through finally.
5381  CGF.PushCleanupBlock(FinallyBlock);
5382
5383  CGF.setInvokeDest(TryHandler);
5384
5385  CGF.EmitBlock(TryBlock);
5386  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5387                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5388  CGF.EmitBranchThroughCleanup(FinallyEnd);
5389
5390  // Emit the exception handler.
5391
5392  CGF.EmitBlock(TryHandler);
5393
5394  llvm::Value *llvm_eh_exception =
5395    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5396  llvm::Value *llvm_eh_selector_i64 =
5397    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5398  llvm::Value *llvm_eh_typeid_for_i64 =
5399    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5400  llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5401  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5402
5403  llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5404  SelectorArgs.push_back(Exc);
5405  SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
5406
5407  // Construct the lists of (type, catch body) to handle.
5408  llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
5409  bool HasCatchAll = false;
5410  if (isTry) {
5411    if (const ObjCAtCatchStmt* CatchStmt =
5412        cast<ObjCAtTryStmt>(S).getCatchStmts())  {
5413      for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
5414        const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
5415        Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
5416
5417        // catch(...) always matches.
5418        if (!CatchDecl) {
5419          // Use i8* null here to signal this is a catch all, not a cleanup.
5420          llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5421          SelectorArgs.push_back(Null);
5422          HasCatchAll = true;
5423          break;
5424        }
5425
5426        if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5427            CatchDecl->getType()->isObjCQualifiedIdType()) {
5428          llvm::Value *IDEHType =
5429            CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5430          if (!IDEHType)
5431            IDEHType =
5432              new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5433                                       llvm::GlobalValue::ExternalLinkage,
5434                                       0, "OBJC_EHTYPE_id", &CGM.getModule());
5435          SelectorArgs.push_back(IDEHType);
5436          HasCatchAll = true;
5437          break;
5438        }
5439
5440        // All other types should be Objective-C interface pointer types.
5441        const PointerType *PT = CatchDecl->getType()->getAsPointerType();
5442        assert(PT && "Invalid @catch type.");
5443        const ObjCInterfaceType *IT =
5444          PT->getPointeeType()->getAsObjCInterfaceType();
5445        assert(IT && "Invalid @catch type.");
5446        llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
5447        SelectorArgs.push_back(EHType);
5448      }
5449    }
5450  }
5451
5452  // We use a cleanup unless there was already a catch all.
5453  if (!HasCatchAll) {
5454    SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
5455    Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
5456  }
5457
5458  llvm::Value *Selector =
5459    CGF.Builder.CreateCall(llvm_eh_selector_i64,
5460                           SelectorArgs.begin(), SelectorArgs.end(),
5461                           "selector");
5462  for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
5463    const ParmVarDecl *CatchParam = Handlers[i].first;
5464    const Stmt *CatchBody = Handlers[i].second;
5465
5466    llvm::BasicBlock *Next = 0;
5467
5468    // The last handler always matches.
5469    if (i + 1 != e) {
5470      assert(CatchParam && "Only last handler can be a catch all.");
5471
5472      llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5473      Next = CGF.createBasicBlock("catch.next");
5474      llvm::Value *Id =
5475        CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5476                               CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5477                                                         ObjCTypes.Int8PtrTy));
5478      CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5479                               Match, Next);
5480
5481      CGF.EmitBlock(Match);
5482    }
5483
5484    if (CatchBody) {
5485      llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5486      llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5487
5488      // Cleanups must call objc_end_catch.
5489      //
5490      // FIXME: It seems incorrect for objc_begin_catch to be inside
5491      // this context, but this matches gcc.
5492      CGF.PushCleanupBlock(MatchEnd);
5493      CGF.setInvokeDest(MatchHandler);
5494
5495      llvm::Value *ExcObject =
5496        CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
5497
5498      // Bind the catch parameter if it exists.
5499      if (CatchParam) {
5500        ExcObject =
5501          CGF.Builder.CreateBitCast(ExcObject,
5502                                    CGF.ConvertType(CatchParam->getType()));
5503        // CatchParam is a ParmVarDecl because of the grammar
5504        // construction used to handle this, but for codegen purposes
5505        // we treat this as a local decl.
5506        CGF.EmitLocalBlockVarDecl(*CatchParam);
5507        CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
5508      }
5509
5510      CGF.ObjCEHValueStack.push_back(ExcObject);
5511      CGF.EmitStmt(CatchBody);
5512      CGF.ObjCEHValueStack.pop_back();
5513
5514      CGF.EmitBranchThroughCleanup(FinallyEnd);
5515
5516      CGF.EmitBlock(MatchHandler);
5517
5518      llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5519      // We are required to emit this call to satisfy LLVM, even
5520      // though we don't use the result.
5521      llvm::SmallVector<llvm::Value*, 8> Args;
5522      Args.push_back(Exc);
5523      Args.push_back(ObjCTypes.getEHPersonalityPtr());
5524      Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5525                                            0));
5526      CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5527      CGF.Builder.CreateStore(Exc, RethrowPtr);
5528      CGF.EmitBranchThroughCleanup(FinallyRethrow);
5529
5530      CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5531
5532      CGF.EmitBlock(MatchEnd);
5533
5534      // Unfortunately, we also have to generate another EH frame here
5535      // in case this throws.
5536      llvm::BasicBlock *MatchEndHandler =
5537        CGF.createBasicBlock("match.end.handler");
5538      llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5539      CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
5540                               Cont, MatchEndHandler,
5541                               Args.begin(), Args.begin());
5542
5543      CGF.EmitBlock(Cont);
5544      if (Info.SwitchBlock)
5545        CGF.EmitBlock(Info.SwitchBlock);
5546      if (Info.EndBlock)
5547        CGF.EmitBlock(Info.EndBlock);
5548
5549      CGF.EmitBlock(MatchEndHandler);
5550      Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5551      // We are required to emit this call to satisfy LLVM, even
5552      // though we don't use the result.
5553      Args.clear();
5554      Args.push_back(Exc);
5555      Args.push_back(ObjCTypes.getEHPersonalityPtr());
5556      Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5557                                            0));
5558      CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5559      CGF.Builder.CreateStore(Exc, RethrowPtr);
5560      CGF.EmitBranchThroughCleanup(FinallyRethrow);
5561
5562      if (Next)
5563        CGF.EmitBlock(Next);
5564    } else {
5565      assert(!Next && "catchup should be last handler.");
5566
5567      CGF.Builder.CreateStore(Exc, RethrowPtr);
5568      CGF.EmitBranchThroughCleanup(FinallyRethrow);
5569    }
5570  }
5571
5572  // Pop the cleanup entry, the @finally is outside this cleanup
5573  // scope.
5574  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5575  CGF.setInvokeDest(PrevLandingPad);
5576
5577  CGF.EmitBlock(FinallyBlock);
5578
5579  if (isTry) {
5580    if (const ObjCAtFinallyStmt* FinallyStmt =
5581        cast<ObjCAtTryStmt>(S).getFinallyStmt())
5582      CGF.EmitStmt(FinallyStmt->getFinallyBody());
5583  } else {
5584    // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5585    // @synchronized.
5586    CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
5587  }
5588
5589  if (Info.SwitchBlock)
5590    CGF.EmitBlock(Info.SwitchBlock);
5591  if (Info.EndBlock)
5592    CGF.EmitBlock(Info.EndBlock);
5593
5594  // Branch around the rethrow code.
5595  CGF.EmitBranch(FinallyEnd);
5596
5597  CGF.EmitBlock(FinallyRethrow);
5598  CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
5599                         CGF.Builder.CreateLoad(RethrowPtr));
5600  CGF.Builder.CreateUnreachable();
5601
5602  CGF.EmitBlock(FinallyEnd);
5603}
5604
5605/// EmitThrowStmt - Generate code for a throw statement.
5606void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5607                                           const ObjCAtThrowStmt &S) {
5608  llvm::Value *Exception;
5609  if (const Expr *ThrowExpr = S.getThrowExpr()) {
5610    Exception = CGF.EmitScalarExpr(ThrowExpr);
5611  } else {
5612    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5613           "Unexpected rethrow outside @catch block.");
5614    Exception = CGF.ObjCEHValueStack.back();
5615  }
5616
5617  llvm::Value *ExceptionAsObject =
5618    CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5619  llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5620  if (InvokeDest) {
5621    llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5622    CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
5623                             Cont, InvokeDest,
5624                             &ExceptionAsObject, &ExceptionAsObject + 1);
5625    CGF.EmitBlock(Cont);
5626  } else
5627    CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
5628  CGF.Builder.CreateUnreachable();
5629
5630  // Clear the insertion point to indicate we are in unreachable code.
5631  CGF.Builder.ClearInsertionPoint();
5632}
5633
5634llvm::Value *
5635CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5636                                           bool ForDefinition) {
5637  llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5638
5639  // If we don't need a definition, return the entry if found or check
5640  // if we use an external reference.
5641  if (!ForDefinition) {
5642    if (Entry)
5643      return Entry;
5644
5645    // If this type (or a super class) has the __objc_exception__
5646    // attribute, emit an external reference.
5647    if (hasObjCExceptionAttribute(ID))
5648      return Entry =
5649        new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5650                                 llvm::GlobalValue::ExternalLinkage,
5651                                 0,
5652                                 (std::string("OBJC_EHTYPE_$_") +
5653                                  ID->getIdentifier()->getName()),
5654                                 &CGM.getModule());
5655  }
5656
5657  // Otherwise we need to either make a new entry or fill in the
5658  // initializer.
5659  assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
5660  std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5661  std::string VTableName = "objc_ehtype_vtable";
5662  llvm::GlobalVariable *VTableGV =
5663    CGM.getModule().getGlobalVariable(VTableName);
5664  if (!VTableGV)
5665    VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5666                                        llvm::GlobalValue::ExternalLinkage,
5667                                        0, VTableName, &CGM.getModule());
5668
5669  llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5670
5671  std::vector<llvm::Constant*> Values(3);
5672  Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5673  Values[1] = GetClassName(ID->getIdentifier());
5674  Values[2] = GetClassGlobal(ClassName);
5675  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5676
5677  if (Entry) {
5678    Entry->setInitializer(Init);
5679  } else {
5680    Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5681                                     llvm::GlobalValue::WeakAnyLinkage,
5682                                     Init,
5683                                     (std::string("OBJC_EHTYPE_$_") +
5684                                      ID->getIdentifier()->getName()),
5685                                     &CGM.getModule());
5686  }
5687
5688  if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
5689    Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
5690  Entry->setAlignment(8);
5691
5692  if (ForDefinition) {
5693    Entry->setSection("__DATA,__objc_const");
5694    Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5695  } else {
5696    Entry->setSection("__DATA,__datacoal_nt,coalesced");
5697  }
5698
5699  return Entry;
5700}
5701
5702/* *** */
5703
5704CodeGen::CGObjCRuntime *
5705CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
5706  return new CGObjCMac(CGM);
5707}
5708
5709CodeGen::CGObjCRuntime *
5710CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
5711  return new CGObjCNonFragileABIMac(CGM);
5712}
5713