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