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