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