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