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