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