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