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
41using namespace clang;
42using namespace CodeGen;
43
44namespace {
45
46// FIXME: We should find a nicer way to make the labels for metadata, string
47// concatenation is lame.
48
49class ObjCCommonTypesHelper {
50protected:
51  llvm::LLVMContext &VMContext;
52
53private:
54  // The types of these functions don't really matter because we
55  // should always bitcast before calling them.
56
57  /// id objc_msgSend (id, SEL, ...)
58  ///
59  /// The default messenger, used for sends whose ABI is unchanged from
60  /// the all-integer/pointer case.
61  llvm::Constant *getMessageSendFn() const {
62    // Add the non-lazy-bind attribute, since objc_msgSend is likely to
63    // be called a lot.
64    llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
65    return
66      CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
67                                                        params, true),
68                                "objc_msgSend",
69                                llvm::AttributeSet::get(CGM.getLLVMContext(),
70                                              llvm::AttributeSet::FunctionIndex,
71                                                 llvm::Attribute::NonLazyBind));
72  }
73
74  /// void objc_msgSend_stret (id, SEL, ...)
75  ///
76  /// The messenger used when the return value is an aggregate returned
77  /// by indirect reference in the first argument, and therefore the
78  /// self and selector parameters are shifted over by one.
79  llvm::Constant *getMessageSendStretFn() const {
80    llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
81    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
82                                                             params, true),
83                                     "objc_msgSend_stret");
84
85  }
86
87  /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
88  ///
89  /// The messenger used when the return value is returned on the x87
90  /// floating-point stack; without a special entrypoint, the nil case
91  /// would be unbalanced.
92  llvm::Constant *getMessageSendFpretFn() const {
93    llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
94    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
95                                                             params, true),
96                                     "objc_msgSend_fpret");
97
98  }
99
100  /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
101  ///
102  /// The messenger used when the return value is returned in two values on the
103  /// x87 floating point stack; without a special entrypoint, the nil case
104  /// would be unbalanced. Only used on 64-bit X86.
105  llvm::Constant *getMessageSendFp2retFn() const {
106    llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
107    llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
108    llvm::Type *resultType =
109      llvm::StructType::get(longDoubleType, longDoubleType, NULL);
110
111    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
112                                                             params, true),
113                                     "objc_msgSend_fp2ret");
114  }
115
116  /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
117  ///
118  /// The messenger used for super calls, which have different dispatch
119  /// semantics.  The class passed is the superclass of the current
120  /// class.
121  llvm::Constant *getMessageSendSuperFn() const {
122    llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
123    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
124                                                             params, true),
125                                     "objc_msgSendSuper");
126  }
127
128  /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
129  ///
130  /// A slightly different messenger used for super calls.  The class
131  /// passed is the current class.
132  llvm::Constant *getMessageSendSuperFn2() const {
133    llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
134    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
135                                                             params, true),
136                                     "objc_msgSendSuper2");
137  }
138
139  /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
140  ///                              SEL op, ...)
141  ///
142  /// The messenger used for super calls which return an aggregate indirectly.
143  llvm::Constant *getMessageSendSuperStretFn() const {
144    llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
145    return CGM.CreateRuntimeFunction(
146      llvm::FunctionType::get(CGM.VoidTy, params, true),
147      "objc_msgSendSuper_stret");
148  }
149
150  /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
151  ///                               SEL op, ...)
152  ///
153  /// objc_msgSendSuper_stret with the super2 semantics.
154  llvm::Constant *getMessageSendSuperStretFn2() const {
155    llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
156    return CGM.CreateRuntimeFunction(
157      llvm::FunctionType::get(CGM.VoidTy, params, true),
158      "objc_msgSendSuper2_stret");
159  }
160
161  llvm::Constant *getMessageSendSuperFpretFn() const {
162    // There is no objc_msgSendSuper_fpret? How can that work?
163    return getMessageSendSuperFn();
164  }
165
166  llvm::Constant *getMessageSendSuperFpretFn2() const {
167    // There is no objc_msgSendSuper_fpret? How can that work?
168    return getMessageSendSuperFn2();
169  }
170
171protected:
172  CodeGen::CodeGenModule &CGM;
173
174public:
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
188private:
189  /// ProtocolPtrTy - LLVM type for external protocol handles
190  /// (typeof(Protocol))
191  llvm::Type *ExternalProtocolPtrTy;
192
193public:
194  llvm::Type *getExternalProtocolPtrTy() {
195    if (!ExternalProtocolPtrTy) {
196      // FIXME: It would be nice to unify this with the opaque type, so that the
197      // IR comes out a bit cleaner.
198      CodeGen::CodeGenTypes &Types = CGM.getTypes();
199      ASTContext &Ctx = CGM.getContext();
200      llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
201      ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
202    }
203
204    return ExternalProtocolPtrTy;
205  }
206
207  // SuperCTy - clang type for struct objc_super.
208  QualType SuperCTy;
209  // SuperPtrCTy - clang type for struct objc_super *.
210  QualType SuperPtrCTy;
211
212  /// SuperTy - LLVM type for struct objc_super.
213  llvm::StructType *SuperTy;
214  /// SuperPtrTy - LLVM type for struct objc_super *.
215  llvm::Type *SuperPtrTy;
216
217  /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
218  /// in GCC parlance).
219  llvm::StructType *PropertyTy;
220
221  /// PropertyListTy - LLVM type for struct objc_property_list
222  /// (_prop_list_t in GCC parlance).
223  llvm::StructType *PropertyListTy;
224  /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
225  llvm::Type *PropertyListPtrTy;
226
227  // MethodTy - LLVM type for struct objc_method.
228  llvm::StructType *MethodTy;
229
230  /// CacheTy - LLVM type for struct objc_cache.
231  llvm::Type *CacheTy;
232  /// CachePtrTy - LLVM type for struct objc_cache *.
233  llvm::Type *CachePtrTy;
234
235  llvm::Constant *getGetPropertyFn() {
236    CodeGen::CodeGenTypes &Types = CGM.getTypes();
237    ASTContext &Ctx = CGM.getContext();
238    // id objc_getProperty (id, SEL, ptrdiff_t, bool)
239    SmallVector<CanQualType,4> Params;
240    CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
241    CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
242    Params.push_back(IdType);
243    Params.push_back(SelType);
244    Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
245    Params.push_back(Ctx.BoolTy);
246    llvm::FunctionType *FTy =
247      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(IdType, false, Params,
248                                                          FunctionType::ExtInfo(),
249                                                          RequiredArgs::All));
250    return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
251  }
252
253  llvm::Constant *getSetPropertyFn() {
254    CodeGen::CodeGenTypes &Types = CGM.getTypes();
255    ASTContext &Ctx = CGM.getContext();
256    // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
257    SmallVector<CanQualType,6> Params;
258    CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
259    CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
260    Params.push_back(IdType);
261    Params.push_back(SelType);
262    Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
263    Params.push_back(IdType);
264    Params.push_back(Ctx.BoolTy);
265    Params.push_back(Ctx.BoolTy);
266    llvm::FunctionType *FTy =
267      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
268                                                          Params,
269                                                          FunctionType::ExtInfo(),
270                                                          RequiredArgs::All));
271    return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
272  }
273
274  llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
275    CodeGen::CodeGenTypes &Types = CGM.getTypes();
276    ASTContext &Ctx = CGM.getContext();
277    // void objc_setProperty_atomic(id self, SEL _cmd,
278    //                              id newValue, ptrdiff_t offset);
279    // void objc_setProperty_nonatomic(id self, SEL _cmd,
280    //                                 id newValue, ptrdiff_t offset);
281    // void objc_setProperty_atomic_copy(id self, SEL _cmd,
282    //                                   id newValue, ptrdiff_t offset);
283    // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
284    //                                      id newValue, ptrdiff_t offset);
285
286    SmallVector<CanQualType,4> Params;
287    CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
288    CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
289    Params.push_back(IdType);
290    Params.push_back(SelType);
291    Params.push_back(IdType);
292    Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
293    llvm::FunctionType *FTy =
294    Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
295                                                        Params,
296                                                        FunctionType::ExtInfo(),
297                                                        RequiredArgs::All));
298    const char *name;
299    if (atomic && copy)
300      name = "objc_setProperty_atomic_copy";
301    else if (atomic && !copy)
302      name = "objc_setProperty_atomic";
303    else if (!atomic && copy)
304      name = "objc_setProperty_nonatomic_copy";
305    else
306      name = "objc_setProperty_nonatomic";
307
308    return CGM.CreateRuntimeFunction(FTy, name);
309  }
310
311  llvm::Constant *getCopyStructFn() {
312    CodeGen::CodeGenTypes &Types = CGM.getTypes();
313    ASTContext &Ctx = CGM.getContext();
314    // void objc_copyStruct (void *, const void *, size_t, bool, bool)
315    SmallVector<CanQualType,5> Params;
316    Params.push_back(Ctx.VoidPtrTy);
317    Params.push_back(Ctx.VoidPtrTy);
318    Params.push_back(Ctx.LongTy);
319    Params.push_back(Ctx.BoolTy);
320    Params.push_back(Ctx.BoolTy);
321    llvm::FunctionType *FTy =
322      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
323                                                          Params,
324                                                          FunctionType::ExtInfo(),
325                                                          RequiredArgs::All));
326    return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
327  }
328
329  /// This routine declares and returns address of:
330  /// void objc_copyCppObjectAtomic(
331  ///         void *dest, const void *src,
332  ///         void (*copyHelper) (void *dest, const void *source));
333  llvm::Constant *getCppAtomicObjectFunction() {
334    CodeGen::CodeGenTypes &Types = CGM.getTypes();
335    ASTContext &Ctx = CGM.getContext();
336    /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
337    SmallVector<CanQualType,3> Params;
338    Params.push_back(Ctx.VoidPtrTy);
339    Params.push_back(Ctx.VoidPtrTy);
340    Params.push_back(Ctx.VoidPtrTy);
341    llvm::FunctionType *FTy =
342      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
343                                                          Params,
344                                                          FunctionType::ExtInfo(),
345                                                          RequiredArgs::All));
346    return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
347  }
348
349  llvm::Constant *getEnumerationMutationFn() {
350    CodeGen::CodeGenTypes &Types = CGM.getTypes();
351    ASTContext &Ctx = CGM.getContext();
352    // void objc_enumerationMutation (id)
353    SmallVector<CanQualType,1> Params;
354    Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
355    llvm::FunctionType *FTy =
356      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
357                                                          Params,
358                                                          FunctionType::ExtInfo(),
359                                                      RequiredArgs::All));
360    return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
361  }
362
363  /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
364  llvm::Constant *getGcReadWeakFn() {
365    // id objc_read_weak (id *)
366    llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
367    llvm::FunctionType *FTy =
368      llvm::FunctionType::get(ObjectPtrTy, args, false);
369    return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
370  }
371
372  /// GcAssignWeakFn -- LLVM objc_assign_weak function.
373  llvm::Constant *getGcAssignWeakFn() {
374    // id objc_assign_weak (id, id *)
375    llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
376    llvm::FunctionType *FTy =
377      llvm::FunctionType::get(ObjectPtrTy, args, false);
378    return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
379  }
380
381  /// GcAssignGlobalFn -- LLVM objc_assign_global function.
382  llvm::Constant *getGcAssignGlobalFn() {
383    // id objc_assign_global(id, id *)
384    llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
385    llvm::FunctionType *FTy =
386      llvm::FunctionType::get(ObjectPtrTy, args, false);
387    return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
388  }
389
390  /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
391  llvm::Constant *getGcAssignThreadLocalFn() {
392    // id objc_assign_threadlocal(id src, id * dest)
393    llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
394    llvm::FunctionType *FTy =
395      llvm::FunctionType::get(ObjectPtrTy, args, false);
396    return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
397  }
398
399  /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
400  llvm::Constant *getGcAssignIvarFn() {
401    // id objc_assign_ivar(id, id *, ptrdiff_t)
402    llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
403                           CGM.PtrDiffTy };
404    llvm::FunctionType *FTy =
405      llvm::FunctionType::get(ObjectPtrTy, args, false);
406    return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
407  }
408
409  /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
410  llvm::Constant *GcMemmoveCollectableFn() {
411    // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
412    llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
413    llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
414    return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
415  }
416
417  /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
418  llvm::Constant *getGcAssignStrongCastFn() {
419    // id objc_assign_strongCast(id, id *)
420    llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
421    llvm::FunctionType *FTy =
422      llvm::FunctionType::get(ObjectPtrTy, args, false);
423    return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
424  }
425
426  /// ExceptionThrowFn - LLVM objc_exception_throw function.
427  llvm::Constant *getExceptionThrowFn() {
428    // void objc_exception_throw(id)
429    llvm::Type *args[] = { ObjectPtrTy };
430    llvm::FunctionType *FTy =
431      llvm::FunctionType::get(CGM.VoidTy, args, false);
432    return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
433  }
434
435  /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
436  llvm::Constant *getExceptionRethrowFn() {
437    // void objc_exception_rethrow(void)
438    llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
439    return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
440  }
441
442  /// SyncEnterFn - LLVM object_sync_enter function.
443  llvm::Constant *getSyncEnterFn() {
444    // int objc_sync_enter (id)
445    llvm::Type *args[] = { ObjectPtrTy };
446    llvm::FunctionType *FTy =
447      llvm::FunctionType::get(CGM.IntTy, args, false);
448    return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
449  }
450
451  /// SyncExitFn - LLVM object_sync_exit function.
452  llvm::Constant *getSyncExitFn() {
453    // int objc_sync_exit (id)
454    llvm::Type *args[] = { ObjectPtrTy };
455    llvm::FunctionType *FTy =
456      llvm::FunctionType::get(CGM.IntTy, args, false);
457    return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
458  }
459
460  llvm::Constant *getSendFn(bool IsSuper) const {
461    return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
462  }
463
464  llvm::Constant *getSendFn2(bool IsSuper) const {
465    return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
466  }
467
468  llvm::Constant *getSendStretFn(bool IsSuper) const {
469    return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
470  }
471
472  llvm::Constant *getSendStretFn2(bool IsSuper) const {
473    return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
474  }
475
476  llvm::Constant *getSendFpretFn(bool IsSuper) const {
477    return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
478  }
479
480  llvm::Constant *getSendFpretFn2(bool IsSuper) const {
481    return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
482  }
483
484  llvm::Constant *getSendFp2retFn(bool IsSuper) const {
485    return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
486  }
487
488  llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
489    return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
490  }
491
492  ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
493  ~ObjCCommonTypesHelper(){}
494};
495
496/// ObjCTypesHelper - Helper class that encapsulates lazy
497/// construction of varies types used during ObjC generation.
498class ObjCTypesHelper : public ObjCCommonTypesHelper {
499public:
500  /// SymtabTy - LLVM type for struct objc_symtab.
501  llvm::StructType *SymtabTy;
502  /// SymtabPtrTy - LLVM type for struct objc_symtab *.
503  llvm::Type *SymtabPtrTy;
504  /// ModuleTy - LLVM type for struct objc_module.
505  llvm::StructType *ModuleTy;
506
507  /// ProtocolTy - LLVM type for struct objc_protocol.
508  llvm::StructType *ProtocolTy;
509  /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
510  llvm::Type *ProtocolPtrTy;
511  /// ProtocolExtensionTy - LLVM type for struct
512  /// objc_protocol_extension.
513  llvm::StructType *ProtocolExtensionTy;
514  /// ProtocolExtensionTy - LLVM type for struct
515  /// objc_protocol_extension *.
516  llvm::Type *ProtocolExtensionPtrTy;
517  /// MethodDescriptionTy - LLVM type for struct
518  /// objc_method_description.
519  llvm::StructType *MethodDescriptionTy;
520  /// MethodDescriptionListTy - LLVM type for struct
521  /// objc_method_description_list.
522  llvm::StructType *MethodDescriptionListTy;
523  /// MethodDescriptionListPtrTy - LLVM type for struct
524  /// objc_method_description_list *.
525  llvm::Type *MethodDescriptionListPtrTy;
526  /// ProtocolListTy - LLVM type for struct objc_property_list.
527  llvm::StructType *ProtocolListTy;
528  /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
529  llvm::Type *ProtocolListPtrTy;
530  /// CategoryTy - LLVM type for struct objc_category.
531  llvm::StructType *CategoryTy;
532  /// ClassTy - LLVM type for struct objc_class.
533  llvm::StructType *ClassTy;
534  /// ClassPtrTy - LLVM type for struct objc_class *.
535  llvm::Type *ClassPtrTy;
536  /// ClassExtensionTy - LLVM type for struct objc_class_ext.
537  llvm::StructType *ClassExtensionTy;
538  /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
539  llvm::Type *ClassExtensionPtrTy;
540  // IvarTy - LLVM type for struct objc_ivar.
541  llvm::StructType *IvarTy;
542  /// IvarListTy - LLVM type for struct objc_ivar_list.
543  llvm::Type *IvarListTy;
544  /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
545  llvm::Type *IvarListPtrTy;
546  /// MethodListTy - LLVM type for struct objc_method_list.
547  llvm::Type *MethodListTy;
548  /// MethodListPtrTy - LLVM type for struct objc_method_list *.
549  llvm::Type *MethodListPtrTy;
550
551  /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
552  llvm::Type *ExceptionDataTy;
553
554  /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
555  llvm::Constant *getExceptionTryEnterFn() {
556    llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
557    return CGM.CreateRuntimeFunction(
558      llvm::FunctionType::get(CGM.VoidTy, params, false),
559      "objc_exception_try_enter");
560  }
561
562  /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
563  llvm::Constant *getExceptionTryExitFn() {
564    llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
565    return CGM.CreateRuntimeFunction(
566      llvm::FunctionType::get(CGM.VoidTy, params, false),
567      "objc_exception_try_exit");
568  }
569
570  /// ExceptionExtractFn - LLVM objc_exception_extract function.
571  llvm::Constant *getExceptionExtractFn() {
572    llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
573    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
574                                                             params, false),
575                                     "objc_exception_extract");
576  }
577
578  /// ExceptionMatchFn - LLVM objc_exception_match function.
579  llvm::Constant *getExceptionMatchFn() {
580    llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
581    return CGM.CreateRuntimeFunction(
582      llvm::FunctionType::get(CGM.Int32Ty, params, false),
583      "objc_exception_match");
584
585  }
586
587  /// SetJmpFn - LLVM _setjmp function.
588  llvm::Constant *getSetJmpFn() {
589    // This is specifically the prototype for x86.
590    llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
591    return
592      CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
593                                                        params, false),
594                                "_setjmp",
595                                llvm::AttributeSet::get(CGM.getLLVMContext(),
596                                              llvm::AttributeSet::FunctionIndex,
597                                                 llvm::Attribute::NonLazyBind));
598  }
599
600public:
601  ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
602  ~ObjCTypesHelper() {}
603};
604
605/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
606/// modern abi
607class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
608public:
609
610  // MethodListnfABITy - LLVM for struct _method_list_t
611  llvm::StructType *MethodListnfABITy;
612
613  // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
614  llvm::Type *MethodListnfABIPtrTy;
615
616  // ProtocolnfABITy = LLVM for struct _protocol_t
617  llvm::StructType *ProtocolnfABITy;
618
619  // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
620  llvm::Type *ProtocolnfABIPtrTy;
621
622  // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
623  llvm::StructType *ProtocolListnfABITy;
624
625  // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
626  llvm::Type *ProtocolListnfABIPtrTy;
627
628  // ClassnfABITy - LLVM for struct _class_t
629  llvm::StructType *ClassnfABITy;
630
631  // ClassnfABIPtrTy - LLVM for struct _class_t*
632  llvm::Type *ClassnfABIPtrTy;
633
634  // IvarnfABITy - LLVM for struct _ivar_t
635  llvm::StructType *IvarnfABITy;
636
637  // IvarListnfABITy - LLVM for struct _ivar_list_t
638  llvm::StructType *IvarListnfABITy;
639
640  // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
641  llvm::Type *IvarListnfABIPtrTy;
642
643  // ClassRonfABITy - LLVM for struct _class_ro_t
644  llvm::StructType *ClassRonfABITy;
645
646  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
647  llvm::Type *ImpnfABITy;
648
649  // CategorynfABITy - LLVM for struct _category_t
650  llvm::StructType *CategorynfABITy;
651
652  // New types for nonfragile abi messaging.
653
654  // MessageRefTy - LLVM for:
655  // struct _message_ref_t {
656  //   IMP messenger;
657  //   SEL name;
658  // };
659  llvm::StructType *MessageRefTy;
660  // MessageRefCTy - clang type for struct _message_ref_t
661  QualType MessageRefCTy;
662
663  // MessageRefPtrTy - LLVM for struct _message_ref_t*
664  llvm::Type *MessageRefPtrTy;
665  // MessageRefCPtrTy - clang type for struct _message_ref_t*
666  QualType MessageRefCPtrTy;
667
668  // MessengerTy - Type of the messenger (shown as IMP above)
669  llvm::FunctionType *MessengerTy;
670
671  // SuperMessageRefTy - LLVM for:
672  // struct _super_message_ref_t {
673  //   SUPER_IMP messenger;
674  //   SEL name;
675  // };
676  llvm::StructType *SuperMessageRefTy;
677
678  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
679  llvm::Type *SuperMessageRefPtrTy;
680
681  llvm::Constant *getMessageSendFixupFn() {
682    // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
683    llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
684    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
685                                                             params, true),
686                                     "objc_msgSend_fixup");
687  }
688
689  llvm::Constant *getMessageSendFpretFixupFn() {
690    // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
691    llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
692    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
693                                                             params, true),
694                                     "objc_msgSend_fpret_fixup");
695  }
696
697  llvm::Constant *getMessageSendStretFixupFn() {
698    // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
699    llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
700    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
701                                                             params, true),
702                                     "objc_msgSend_stret_fixup");
703  }
704
705  llvm::Constant *getMessageSendSuper2FixupFn() {
706    // id objc_msgSendSuper2_fixup (struct objc_super *,
707    //                              struct _super_message_ref_t*, ...)
708    llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
709    return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
710                                                              params, true),
711                                      "objc_msgSendSuper2_fixup");
712  }
713
714  llvm::Constant *getMessageSendSuper2StretFixupFn() {
715    // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
716    //                                   struct _super_message_ref_t*, ...)
717    llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
718    return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
719                                                              params, true),
720                                      "objc_msgSendSuper2_stret_fixup");
721  }
722
723  llvm::Constant *getObjCEndCatchFn() {
724    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
725                                     "objc_end_catch");
726
727  }
728
729  llvm::Constant *getObjCBeginCatchFn() {
730    llvm::Type *params[] = { Int8PtrTy };
731    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
732                                                             params, false),
733                                     "objc_begin_catch");
734  }
735
736  llvm::StructType *EHTypeTy;
737  llvm::Type *EHTypePtrTy;
738
739  ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
740  ~ObjCNonFragileABITypesHelper(){}
741};
742
743class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
744public:
745  // FIXME - accessibility
746  class GC_IVAR {
747  public:
748    unsigned ivar_bytepos;
749    unsigned ivar_size;
750    GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
751      : ivar_bytepos(bytepos), ivar_size(size) {}
752
753    // Allow sorting based on byte pos.
754    bool operator<(const GC_IVAR &b) const {
755      return ivar_bytepos < b.ivar_bytepos;
756    }
757  };
758
759  class SKIP_SCAN {
760  public:
761    unsigned skip;
762    unsigned scan;
763    SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
764      : skip(_skip), scan(_scan) {}
765  };
766
767  /// opcode for captured block variables layout 'instructions'.
768  /// In the following descriptions, 'I' is the value of the immediate field.
769  /// (field following the opcode).
770  ///
771  enum BLOCK_LAYOUT_OPCODE {
772    /// An operator which affects how the following layout should be
773    /// interpreted.
774    ///   I == 0: Halt interpretation and treat everything else as
775    ///           a non-pointer.  Note that this instruction is equal
776    ///           to '\0'.
777    ///   I != 0: Currently unused.
778    BLOCK_LAYOUT_OPERATOR            = 0,
779
780    /// The next I+1 bytes do not contain a value of object pointer type.
781    /// Note that this can leave the stream unaligned, meaning that
782    /// subsequent word-size instructions do not begin at a multiple of
783    /// the pointer size.
784    BLOCK_LAYOUT_NON_OBJECT_BYTES    = 1,
785
786    /// The next I+1 words do not contain a value of object pointer type.
787    /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
788    /// when the required skip quantity is a multiple of the pointer size.
789    BLOCK_LAYOUT_NON_OBJECT_WORDS    = 2,
790
791    /// The next I+1 words are __strong pointers to Objective-C
792    /// objects or blocks.
793    BLOCK_LAYOUT_STRONG              = 3,
794
795    /// The next I+1 words are pointers to __block variables.
796    BLOCK_LAYOUT_BYREF               = 4,
797
798    /// The next I+1 words are __weak pointers to Objective-C
799    /// objects or blocks.
800    BLOCK_LAYOUT_WEAK                = 5,
801
802    /// The next I+1 words are __unsafe_unretained pointers to
803    /// Objective-C objects or blocks.
804    BLOCK_LAYOUT_UNRETAINED          = 6
805
806    /// The next I+1 words are block or object pointers with some
807    /// as-yet-unspecified ownership semantics.  If we add more
808    /// flavors of ownership semantics, values will be taken from
809    /// this range.
810    ///
811    /// This is included so that older tools can at least continue
812    /// processing the layout past such things.
813    //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
814
815    /// All other opcodes are reserved.  Halt interpretation and
816    /// treat everything else as opaque.
817  };
818
819  class RUN_SKIP {
820  public:
821    enum BLOCK_LAYOUT_OPCODE opcode;
822    CharUnits block_var_bytepos;
823    CharUnits block_var_size;
824    RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
825             CharUnits BytePos = CharUnits::Zero(),
826             CharUnits Size = CharUnits::Zero())
827    : opcode(Opcode), block_var_bytepos(BytePos),  block_var_size(Size) {}
828
829    // Allow sorting based on byte pos.
830    bool operator<(const RUN_SKIP &b) const {
831      return block_var_bytepos < b.block_var_bytepos;
832    }
833  };
834
835protected:
836  llvm::LLVMContext &VMContext;
837  // FIXME! May not be needing this after all.
838  unsigned ObjCABI;
839
840  // gc ivar layout bitmap calculation helper caches.
841  SmallVector<GC_IVAR, 16> SkipIvars;
842  SmallVector<GC_IVAR, 16> IvarsInfo;
843
844  // arc/mrr layout of captured block literal variables.
845  SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
846
847  /// LazySymbols - Symbols to generate a lazy reference for. See
848  /// DefinedSymbols and FinishModule().
849  llvm::SetVector<IdentifierInfo*> LazySymbols;
850
851  /// DefinedSymbols - External symbols which are defined by this
852  /// module. The symbols in this list and LazySymbols are used to add
853  /// special linker symbols which ensure that Objective-C modules are
854  /// linked properly.
855  llvm::SetVector<IdentifierInfo*> DefinedSymbols;
856
857  /// ClassNames - uniqued class names.
858  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
859
860  /// MethodVarNames - uniqued method variable names.
861  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
862
863  /// DefinedCategoryNames - list of category names in form Class_Category.
864  llvm::SetVector<std::string> DefinedCategoryNames;
865
866  /// MethodVarTypes - uniqued method type signatures. We have to use
867  /// a StringMap here because have no other unique reference.
868  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
869
870  /// MethodDefinitions - map of methods which have been defined in
871  /// this translation unit.
872  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
873
874  /// PropertyNames - uniqued method variable names.
875  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
876
877  /// ClassReferences - uniqued class references.
878  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
879
880  /// SelectorReferences - uniqued selector references.
881  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
882
883  /// Protocols - Protocols for which an objc_protocol structure has
884  /// been emitted. Forward declarations are handled by creating an
885  /// empty structure whose initializer is filled in when/if defined.
886  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
887
888  /// DefinedProtocols - Protocols which have actually been
889  /// defined. We should not need this, see FIXME in GenerateProtocol.
890  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
891
892  /// DefinedClasses - List of defined classes.
893  SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
894
895  /// ImplementedClasses - List of @implemented classes.
896  SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
897
898  /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
899  SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
900
901  /// DefinedCategories - List of defined categories.
902  SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
903
904  /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
905  SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
906
907  /// GetNameForMethod - Return a name for the given method.
908  /// \param[out] NameOut - The return value.
909  void GetNameForMethod(const ObjCMethodDecl *OMD,
910                        const ObjCContainerDecl *CD,
911                        SmallVectorImpl<char> &NameOut);
912
913  /// GetMethodVarName - Return a unique constant for the given
914  /// selector's name. The return value has type char *.
915  llvm::Constant *GetMethodVarName(Selector Sel);
916  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
917
918  /// GetMethodVarType - Return a unique constant for the given
919  /// method's type encoding string. The return value has type char *.
920
921  // FIXME: This is a horrible name.
922  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
923                                   bool Extended = false);
924  llvm::Constant *GetMethodVarType(const FieldDecl *D);
925
926  /// GetPropertyName - Return a unique constant for the given
927  /// name. The return value has type char *.
928  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
929
930  // FIXME: This can be dropped once string functions are unified.
931  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
932                                        const Decl *Container);
933
934  /// GetClassName - Return a unique constant for the given selector's
935  /// name. The return value has type char *.
936  llvm::Constant *GetClassName(IdentifierInfo *Ident);
937
938  llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
939
940  /// BuildIvarLayout - Builds ivar layout bitmap for the class
941  /// implementation for the __strong or __weak case.
942  ///
943  llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
944                                  bool ForStrongLayout);
945
946  llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
947
948  void BuildAggrIvarRecordLayout(const RecordType *RT,
949                                 unsigned int BytePos, bool ForStrongLayout,
950                                 bool &HasUnion);
951  void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
952                           const llvm::StructLayout *Layout,
953                           const RecordDecl *RD,
954                           ArrayRef<const FieldDecl*> RecFields,
955                           unsigned int BytePos, bool ForStrongLayout,
956                           bool &HasUnion);
957
958  Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
959
960  void UpdateRunSkipBlockVars(bool IsByref,
961                              Qualifiers::ObjCLifetime LifeTime,
962                              CharUnits FieldOffset,
963                              CharUnits FieldSize);
964
965  void BuildRCBlockVarRecordLayout(const RecordType *RT,
966                                   CharUnits BytePos, bool &HasUnion,
967                                   bool ByrefLayout=false);
968
969  void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
970                           const RecordDecl *RD,
971                           ArrayRef<const FieldDecl*> RecFields,
972                           CharUnits BytePos, bool &HasUnion,
973                           bool ByrefLayout);
974
975  uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
976
977  llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
978
979
980  /// GetIvarLayoutName - Returns a unique constant for the given
981  /// ivar layout bitmap.
982  llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
983                                    const ObjCCommonTypesHelper &ObjCTypes);
984
985  /// EmitPropertyList - Emit the given property list. The return
986  /// value has type PropertyListPtrTy.
987  llvm::Constant *EmitPropertyList(Twine Name,
988                                   const Decl *Container,
989                                   const ObjCContainerDecl *OCD,
990                                   const ObjCCommonTypesHelper &ObjCTypes);
991
992  /// EmitProtocolMethodTypes - Generate the array of extended method type
993  /// strings. The return value has type Int8PtrPtrTy.
994  llvm::Constant *EmitProtocolMethodTypes(Twine Name,
995                                          ArrayRef<llvm::Constant*> MethodTypes,
996                                       const ObjCCommonTypesHelper &ObjCTypes);
997
998  /// PushProtocolProperties - Push protocol's property on the input stack.
999  void PushProtocolProperties(
1000    llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
1001    SmallVectorImpl<llvm::Constant*> &Properties,
1002    const Decl *Container,
1003    const ObjCProtocolDecl *Proto,
1004    const ObjCCommonTypesHelper &ObjCTypes);
1005
1006  /// GetProtocolRef - Return a reference to the internal protocol
1007  /// description, creating an empty one if it has not been
1008  /// defined. The return value has type ProtocolPtrTy.
1009  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
1010
1011  /// CreateMetadataVar - Create a global variable with internal
1012  /// linkage for use by the Objective-C runtime.
1013  ///
1014  /// This is a convenience wrapper which not only creates the
1015  /// variable, but also sets the section and alignment and adds the
1016  /// global to the "llvm.used" list.
1017  ///
1018  /// \param Name - The variable name.
1019  /// \param Init - The variable initializer; this is also used to
1020  /// define the type of the variable.
1021  /// \param Section - The section the variable should go into, or empty.
1022  /// \param Align - The alignment for the variable, or 0.
1023  /// \param AddToUsed - Whether the variable should be added to
1024  /// "llvm.used".
1025  llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init,
1026                                          StringRef Section, unsigned Align,
1027                                          bool AddToUsed);
1028
1029  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1030                                  ReturnValueSlot Return,
1031                                  QualType ResultType,
1032                                  llvm::Value *Sel,
1033                                  llvm::Value *Arg0,
1034                                  QualType Arg0Ty,
1035                                  bool IsSuper,
1036                                  const CallArgList &CallArgs,
1037                                  const ObjCMethodDecl *OMD,
1038                                  const ObjCCommonTypesHelper &ObjCTypes);
1039
1040  /// EmitImageInfo - Emit the image info marker used to encode some module
1041  /// level information.
1042  void EmitImageInfo();
1043
1044public:
1045  CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
1046    CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
1047
1048  llvm::Constant *GenerateConstantString(const StringLiteral *SL) override;
1049
1050  llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
1051                                 const ObjCContainerDecl *CD=nullptr) override;
1052
1053  void GenerateProtocol(const ObjCProtocolDecl *PD) override;
1054
1055  /// GetOrEmitProtocol - Get the protocol object for the given
1056  /// declaration, emitting it if necessary. The return value has type
1057  /// ProtocolPtrTy.
1058  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
1059
1060  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1061  /// object for the given declaration, emitting it if needed. These
1062  /// forward references will be filled in with empty bodies if no
1063  /// definition is seen. The return value has type ProtocolPtrTy.
1064  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
1065  llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1066                                     const CGBlockInfo &blockInfo) override;
1067  llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1068                                     const CGBlockInfo &blockInfo) override;
1069
1070  llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1071                                   QualType T) override;
1072};
1073
1074class CGObjCMac : public CGObjCCommonMac {
1075private:
1076  ObjCTypesHelper ObjCTypes;
1077
1078  /// EmitModuleInfo - Another marker encoding module level
1079  /// information.
1080  void EmitModuleInfo();
1081
1082  /// EmitModuleSymols - Emit module symbols, the list of defined
1083  /// classes and categories. The result has type SymtabPtrTy.
1084  llvm::Constant *EmitModuleSymbols();
1085
1086  /// FinishModule - Write out global data structures at the end of
1087  /// processing a translation unit.
1088  void FinishModule();
1089
1090  /// EmitClassExtension - Generate the class extension structure used
1091  /// to store the weak ivar layout and properties. The return value
1092  /// has type ClassExtensionPtrTy.
1093  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
1094
1095  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1096  /// for the given class.
1097  llvm::Value *EmitClassRef(CodeGenFunction &CGF,
1098                            const ObjCInterfaceDecl *ID);
1099
1100  llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
1101                                  IdentifierInfo *II);
1102
1103  llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1104
1105  /// EmitSuperClassRef - Emits reference to class's main metadata class.
1106  llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
1107
1108  /// EmitIvarList - Emit the ivar list for the given
1109  /// implementation. If ForClass is true the list of class ivars
1110  /// (i.e. metaclass ivars) is emitted, otherwise the list of
1111  /// interface ivars will be emitted. The return value has type
1112  /// IvarListPtrTy.
1113  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
1114                               bool ForClass);
1115
1116  /// EmitMetaClass - Emit a forward reference to the class structure
1117  /// for the metaclass of the given interface. The return value has
1118  /// type ClassPtrTy.
1119  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1120
1121  /// EmitMetaClass - Emit a class structure for the metaclass of the
1122  /// given implementation. The return value has type ClassPtrTy.
1123  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1124                                llvm::Constant *Protocols,
1125                                ArrayRef<llvm::Constant*> Methods);
1126
1127  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1128
1129  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1130
1131  /// EmitMethodList - Emit the method list for the given
1132  /// implementation. The return value has type MethodListPtrTy.
1133  llvm::Constant *EmitMethodList(Twine Name,
1134                                 const char *Section,
1135                                 ArrayRef<llvm::Constant*> Methods);
1136
1137  /// EmitMethodDescList - Emit a method description list for a list of
1138  /// method declarations.
1139  ///  - TypeName: The name for the type containing the methods.
1140  ///  - IsProtocol: True iff these methods are for a protocol.
1141  ///  - ClassMethds: True iff these are class methods.
1142  ///  - Required: When true, only "required" methods are
1143  ///    listed. Similarly, when false only "optional" methods are
1144  ///    listed. For classes this should always be true.
1145  ///  - begin, end: The method list to output.
1146  ///
1147  /// The return value has type MethodDescriptionListPtrTy.
1148  llvm::Constant *EmitMethodDescList(Twine Name,
1149                                     const char *Section,
1150                                     ArrayRef<llvm::Constant*> Methods);
1151
1152  /// GetOrEmitProtocol - Get the protocol object for the given
1153  /// declaration, emitting it if necessary. The return value has type
1154  /// ProtocolPtrTy.
1155  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
1156
1157  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1158  /// object for the given declaration, emitting it if needed. These
1159  /// forward references will be filled in with empty bodies if no
1160  /// definition is seen. The return value has type ProtocolPtrTy.
1161  llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
1162
1163  /// EmitProtocolExtension - Generate the protocol extension
1164  /// structure used to store optional instance and class methods, and
1165  /// protocol properties. The return value has type
1166  /// ProtocolExtensionPtrTy.
1167  llvm::Constant *
1168  EmitProtocolExtension(const ObjCProtocolDecl *PD,
1169                        ArrayRef<llvm::Constant*> OptInstanceMethods,
1170                        ArrayRef<llvm::Constant*> OptClassMethods,
1171                        ArrayRef<llvm::Constant*> MethodTypesExt);
1172
1173  /// EmitProtocolList - Generate the list of referenced
1174  /// protocols. The return value has type ProtocolListPtrTy.
1175  llvm::Constant *EmitProtocolList(Twine Name,
1176                                   ObjCProtocolDecl::protocol_iterator begin,
1177                                   ObjCProtocolDecl::protocol_iterator end);
1178
1179  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1180  /// for the given selector.
1181  llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel,
1182                            bool lval=false);
1183
1184public:
1185  CGObjCMac(CodeGen::CodeGenModule &cgm);
1186
1187  llvm::Function *ModuleInitFunction() override;
1188
1189  CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1190                                      ReturnValueSlot Return,
1191                                      QualType ResultType,
1192                                      Selector Sel, llvm::Value *Receiver,
1193                                      const CallArgList &CallArgs,
1194                                      const ObjCInterfaceDecl *Class,
1195                                      const ObjCMethodDecl *Method) override;
1196
1197  CodeGen::RValue
1198  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1199                           ReturnValueSlot Return, QualType ResultType,
1200                           Selector Sel, const ObjCInterfaceDecl *Class,
1201                           bool isCategoryImpl, llvm::Value *Receiver,
1202                           bool IsClassMessage, const CallArgList &CallArgs,
1203                           const ObjCMethodDecl *Method) override;
1204
1205  llvm::Value *GetClass(CodeGenFunction &CGF,
1206                        const ObjCInterfaceDecl *ID) override;
1207
1208  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
1209                           bool lval = false) override;
1210
1211  /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1212  /// untyped one.
1213  llvm::Value *GetSelector(CodeGenFunction &CGF,
1214                           const ObjCMethodDecl *Method) override;
1215
1216  llvm::Constant *GetEHType(QualType T) override;
1217
1218  void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
1219
1220  void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
1221
1222  void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
1223
1224  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1225                                   const ObjCProtocolDecl *PD) override;
1226
1227  llvm::Constant *GetPropertyGetFunction() override;
1228  llvm::Constant *GetPropertySetFunction() override;
1229  llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1230                                                  bool copy) override;
1231  llvm::Constant *GetGetStructFunction() override;
1232  llvm::Constant *GetSetStructFunction() override;
1233  llvm::Constant *GetCppAtomicObjectGetFunction() override;
1234  llvm::Constant *GetCppAtomicObjectSetFunction() override;
1235  llvm::Constant *EnumerationMutationFunction() override;
1236
1237  void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1238                   const ObjCAtTryStmt &S) override;
1239  void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1240                            const ObjCAtSynchronizedStmt &S) override;
1241  void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
1242  void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1243                     bool ClearInsertionPoint=true) override;
1244  llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1245                                 llvm::Value *AddrWeakObj) override;
1246  void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1247                          llvm::Value *src, llvm::Value *dst) override;
1248  void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1249                            llvm::Value *src, llvm::Value *dest,
1250                            bool threadlocal = false) override;
1251  void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1252                          llvm::Value *src, llvm::Value *dest,
1253                          llvm::Value *ivarOffset) override;
1254  void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1255                                llvm::Value *src, llvm::Value *dest) override;
1256  void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1257                                llvm::Value *dest, llvm::Value *src,
1258                                llvm::Value *size) override;
1259
1260  LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1261                              llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1262                              unsigned CVRQualifiers) override;
1263  llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1264                              const ObjCInterfaceDecl *Interface,
1265                              const ObjCIvarDecl *Ivar) override;
1266
1267  /// GetClassGlobal - Return the global variable for the Objective-C
1268  /// class of the given name.
1269  llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
1270                                       bool Weak = false) override {
1271    llvm_unreachable("CGObjCMac::GetClassGlobal");
1272  }
1273};
1274
1275class CGObjCNonFragileABIMac : public CGObjCCommonMac {
1276private:
1277  ObjCNonFragileABITypesHelper ObjCTypes;
1278  llvm::GlobalVariable* ObjCEmptyCacheVar;
1279  llvm::GlobalVariable* ObjCEmptyVtableVar;
1280
1281  /// SuperClassReferences - uniqued super class references.
1282  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1283
1284  /// MetaClassReferences - uniqued meta class references.
1285  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
1286
1287  /// EHTypeReferences - uniqued class ehtype references.
1288  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
1289
1290  /// VTableDispatchMethods - List of methods for which we generate
1291  /// vtable-based message dispatch.
1292  llvm::DenseSet<Selector> VTableDispatchMethods;
1293
1294  /// DefinedMetaClasses - List of defined meta-classes.
1295  std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1296
1297  /// isVTableDispatchedSelector - Returns true if SEL is a
1298  /// vtable-based selector.
1299  bool isVTableDispatchedSelector(Selector Sel);
1300
1301  /// FinishNonFragileABIModule - Write out global data structures at the end of
1302  /// processing a translation unit.
1303  void FinishNonFragileABIModule();
1304
1305  /// AddModuleClassList - Add the given list of class pointers to the
1306  /// module with the provided symbol and section names.
1307  void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
1308                          const char *SymbolName,
1309                          const char *SectionName);
1310
1311  llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1312                                              unsigned InstanceStart,
1313                                              unsigned InstanceSize,
1314                                              const ObjCImplementationDecl *ID);
1315  llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1316                                            llvm::Constant *IsAGV,
1317                                            llvm::Constant *SuperClassGV,
1318                                            llvm::Constant *ClassRoGV,
1319                                            bool HiddenVisibility,
1320                                            bool Weak);
1321
1322  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1323
1324  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1325
1326  /// EmitMethodList - Emit the method list for the given
1327  /// implementation. The return value has type MethodListnfABITy.
1328  llvm::Constant *EmitMethodList(Twine Name,
1329                                 const char *Section,
1330                                 ArrayRef<llvm::Constant*> Methods);
1331  /// EmitIvarList - Emit the ivar list for the given
1332  /// implementation. If ForClass is true the list of class ivars
1333  /// (i.e. metaclass ivars) is emitted, otherwise the list of
1334  /// interface ivars will be emitted. The return value has type
1335  /// IvarListnfABIPtrTy.
1336  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
1337
1338  llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
1339                                    const ObjCIvarDecl *Ivar,
1340                                    unsigned long int offset);
1341
1342  /// GetOrEmitProtocol - Get the protocol object for the given
1343  /// declaration, emitting it if necessary. The return value has type
1344  /// ProtocolPtrTy.
1345  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
1346
1347  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1348  /// object for the given declaration, emitting it if needed. These
1349  /// forward references will be filled in with empty bodies if no
1350  /// definition is seen. The return value has type ProtocolPtrTy.
1351  llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
1352
1353  /// EmitProtocolList - Generate the list of referenced
1354  /// protocols. The return value has type ProtocolListPtrTy.
1355  llvm::Constant *EmitProtocolList(Twine Name,
1356                                   ObjCProtocolDecl::protocol_iterator begin,
1357                                   ObjCProtocolDecl::protocol_iterator end);
1358
1359  CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1360                                        ReturnValueSlot Return,
1361                                        QualType ResultType,
1362                                        Selector Sel,
1363                                        llvm::Value *Receiver,
1364                                        QualType Arg0Ty,
1365                                        bool IsSuper,
1366                                        const CallArgList &CallArgs,
1367                                        const ObjCMethodDecl *Method);
1368
1369  /// GetClassGlobal - Return the global variable for the Objective-C
1370  /// class of the given name.
1371  llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
1372                                       bool Weak = false) override;
1373
1374  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1375  /// for the given class reference.
1376  llvm::Value *EmitClassRef(CodeGenFunction &CGF,
1377                            const ObjCInterfaceDecl *ID);
1378
1379  llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
1380                                  IdentifierInfo *II, bool Weak);
1381
1382  llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1383
1384  /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1385  /// for the given super class reference.
1386  llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
1387                                 const ObjCInterfaceDecl *ID);
1388
1389  /// EmitMetaClassRef - Return a Value * of the address of _class_t
1390  /// meta-data
1391  llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
1392                                const ObjCInterfaceDecl *ID, bool Weak);
1393
1394  /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1395  /// the given ivar.
1396  ///
1397  llvm::GlobalVariable * ObjCIvarOffsetVariable(
1398    const ObjCInterfaceDecl *ID,
1399    const ObjCIvarDecl *Ivar);
1400
1401  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1402  /// for the given selector.
1403  llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel,
1404                            bool lval=false);
1405
1406  /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
1407  /// interface. The return value has type EHTypePtrTy.
1408  llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1409                                  bool ForDefinition);
1410
1411  const char *getMetaclassSymbolPrefix() const {
1412    return "OBJC_METACLASS_$_";
1413  }
1414
1415  const char *getClassSymbolPrefix() const {
1416    return "OBJC_CLASS_$_";
1417  }
1418
1419  void GetClassSizeInfo(const ObjCImplementationDecl *OID,
1420                        uint32_t &InstanceStart,
1421                        uint32_t &InstanceSize);
1422
1423  // Shamelessly stolen from Analysis/CFRefCount.cpp
1424  Selector GetNullarySelector(const char* name) const {
1425    IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1426    return CGM.getContext().Selectors.getSelector(0, &II);
1427  }
1428
1429  Selector GetUnarySelector(const char* name) const {
1430    IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1431    return CGM.getContext().Selectors.getSelector(1, &II);
1432  }
1433
1434  /// ImplementationIsNonLazy - Check whether the given category or
1435  /// class implementation is "non-lazy".
1436  bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
1437
1438  bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
1439                                   const ObjCIvarDecl *IV) {
1440    // Annotate the load as an invariant load iff inside an instance method
1441    // and ivar belongs to instance method's class and one of its super class.
1442    // This check is needed because the ivar offset is a lazily
1443    // initialised value that may depend on objc_msgSend to perform a fixup on
1444    // the first message dispatch.
1445    //
1446    // An additional opportunity to mark the load as invariant arises when the
1447    // base of the ivar access is a parameter to an Objective C method.
1448    // However, because the parameters are not available in the current
1449    // interface, we cannot perform this check.
1450    if (const ObjCMethodDecl *MD =
1451          dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
1452      if (MD->isInstanceMethod())
1453        if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1454          return IV->getContainingInterface()->isSuperClassOf(ID);
1455    return false;
1456  }
1457
1458public:
1459  CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
1460  // FIXME. All stubs for now!
1461  llvm::Function *ModuleInitFunction() override;
1462
1463  CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1464                                      ReturnValueSlot Return,
1465                                      QualType ResultType, Selector Sel,
1466                                      llvm::Value *Receiver,
1467                                      const CallArgList &CallArgs,
1468                                      const ObjCInterfaceDecl *Class,
1469                                      const ObjCMethodDecl *Method) override;
1470
1471  CodeGen::RValue
1472  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1473                           ReturnValueSlot Return, QualType ResultType,
1474                           Selector Sel, const ObjCInterfaceDecl *Class,
1475                           bool isCategoryImpl, llvm::Value *Receiver,
1476                           bool IsClassMessage, const CallArgList &CallArgs,
1477                           const ObjCMethodDecl *Method) override;
1478
1479  llvm::Value *GetClass(CodeGenFunction &CGF,
1480                        const ObjCInterfaceDecl *ID) override;
1481
1482  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
1483                           bool lvalue = false) override
1484    { return EmitSelector(CGF, Sel, lvalue); }
1485
1486  /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1487  /// untyped one.
1488  llvm::Value *GetSelector(CodeGenFunction &CGF,
1489                           const ObjCMethodDecl *Method) override
1490    { return EmitSelector(CGF, Method->getSelector()); }
1491
1492  void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
1493
1494  void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
1495
1496  void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
1497
1498  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1499                                   const ObjCProtocolDecl *PD) override;
1500
1501  llvm::Constant *GetEHType(QualType T) override;
1502
1503  llvm::Constant *GetPropertyGetFunction() override {
1504    return ObjCTypes.getGetPropertyFn();
1505  }
1506  llvm::Constant *GetPropertySetFunction() override {
1507    return ObjCTypes.getSetPropertyFn();
1508  }
1509
1510  llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
1511                                                  bool copy) override {
1512    return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1513  }
1514
1515  llvm::Constant *GetSetStructFunction() override {
1516    return ObjCTypes.getCopyStructFn();
1517  }
1518  llvm::Constant *GetGetStructFunction() override {
1519    return ObjCTypes.getCopyStructFn();
1520  }
1521  llvm::Constant *GetCppAtomicObjectSetFunction() override {
1522    return ObjCTypes.getCppAtomicObjectFunction();
1523  }
1524  llvm::Constant *GetCppAtomicObjectGetFunction() override {
1525    return ObjCTypes.getCppAtomicObjectFunction();
1526  }
1527
1528  llvm::Constant *EnumerationMutationFunction() override {
1529    return ObjCTypes.getEnumerationMutationFn();
1530  }
1531
1532  void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1533                   const ObjCAtTryStmt &S) override;
1534  void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1535                            const ObjCAtSynchronizedStmt &S) override;
1536  void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1537                     bool ClearInsertionPoint=true) override;
1538  llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1539                                 llvm::Value *AddrWeakObj) override;
1540  void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1541                          llvm::Value *src, llvm::Value *dst) override;
1542  void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1543                            llvm::Value *src, llvm::Value *dest,
1544                            bool threadlocal = false) override;
1545  void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1546                          llvm::Value *src, llvm::Value *dest,
1547                          llvm::Value *ivarOffset) override;
1548  void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1549                                llvm::Value *src, llvm::Value *dest) override;
1550  void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1551                                llvm::Value *dest, llvm::Value *src,
1552                                llvm::Value *size) override;
1553  LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1554                              llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1555                              unsigned CVRQualifiers) override;
1556  llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1557                              const ObjCInterfaceDecl *Interface,
1558                              const ObjCIvarDecl *Ivar) override;
1559};
1560
1561/// A helper class for performing the null-initialization of a return
1562/// value.
1563struct NullReturnState {
1564  llvm::BasicBlock *NullBB;
1565  NullReturnState() : NullBB(nullptr) {}
1566
1567  /// Perform a null-check of the given receiver.
1568  void init(CodeGenFunction &CGF, llvm::Value *receiver) {
1569    // Make blocks for the null-receiver and call edges.
1570    NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1571    llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
1572
1573    // Check for a null receiver and, if there is one, jump to the
1574    // null-receiver block.  There's no point in trying to avoid it:
1575    // we're always going to put *something* there, because otherwise
1576    // we shouldn't have done this null-check in the first place.
1577    llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1578    CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1579
1580    // Otherwise, start performing the call.
1581    CGF.EmitBlock(callBB);
1582  }
1583
1584  /// Complete the null-return operation.  It is valid to call this
1585  /// regardless of whether 'init' has been called.
1586  RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
1587                  const CallArgList &CallArgs,
1588                  const ObjCMethodDecl *Method) {
1589    // If we never had to do a null-check, just use the raw result.
1590    if (!NullBB) return result;
1591
1592    // The continuation block.  This will be left null if we don't have an
1593    // IP, which can happen if the method we're calling is marked noreturn.
1594    llvm::BasicBlock *contBB = nullptr;
1595
1596    // Finish the call path.
1597    llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1598    if (callBB) {
1599      contBB = CGF.createBasicBlock("msgSend.cont");
1600      CGF.Builder.CreateBr(contBB);
1601    }
1602
1603    // Okay, start emitting the null-receiver block.
1604    CGF.EmitBlock(NullBB);
1605
1606    // Release any consumed arguments we've got.
1607    if (Method) {
1608      CallArgList::const_iterator I = CallArgs.begin();
1609      for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1610           e = Method->param_end(); i != e; ++i, ++I) {
1611        const ParmVarDecl *ParamDecl = (*i);
1612        if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1613          RValue RV = I->RV;
1614          assert(RV.isScalar() &&
1615                 "NullReturnState::complete - arg not on object");
1616          CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
1617        }
1618      }
1619    }
1620
1621    // The phi code below assumes that we haven't needed any control flow yet.
1622    assert(CGF.Builder.GetInsertBlock() == NullBB);
1623
1624    // If we've got a void return, just jump to the continuation block.
1625    if (result.isScalar() && resultType->isVoidType()) {
1626      // No jumps required if the message-send was noreturn.
1627      if (contBB) CGF.EmitBlock(contBB);
1628      return result;
1629    }
1630
1631    // If we've got a scalar return, build a phi.
1632    if (result.isScalar()) {
1633      // Derive the null-initialization value.
1634      llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
1635
1636      // If no join is necessary, just flow out.
1637      if (!contBB) return RValue::get(null);
1638
1639      // Otherwise, build a phi.
1640      CGF.EmitBlock(contBB);
1641      llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1642      phi->addIncoming(result.getScalarVal(), callBB);
1643      phi->addIncoming(null, NullBB);
1644      return RValue::get(phi);
1645    }
1646
1647    // If we've got an aggregate return, null the buffer out.
1648    // FIXME: maybe we should be doing things differently for all the
1649    // cases where the ABI has us returning (1) non-agg values in
1650    // memory or (2) agg values in registers.
1651    if (result.isAggregate()) {
1652      assert(result.isAggregate() && "null init of non-aggregate result?");
1653      CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
1654      if (contBB) CGF.EmitBlock(contBB);
1655      return result;
1656    }
1657
1658    // Complex types.
1659    CGF.EmitBlock(contBB);
1660    CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1661
1662    // Find the scalar type and its zero value.
1663    llvm::Type *scalarTy = callResult.first->getType();
1664    llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1665
1666    // Build phis for both coordinates.
1667    llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1668    real->addIncoming(callResult.first, callBB);
1669    real->addIncoming(scalarZero, NullBB);
1670    llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1671    imag->addIncoming(callResult.second, callBB);
1672    imag->addIncoming(scalarZero, NullBB);
1673    return RValue::getComplex(real, imag);
1674  }
1675};
1676
1677} // end anonymous namespace
1678
1679/* *** Helper Functions *** */
1680
1681/// getConstantGEP() - Help routine to construct simple GEPs.
1682static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
1683                                      llvm::Constant *C,
1684                                      unsigned idx0,
1685                                      unsigned idx1) {
1686  llvm::Value *Idxs[] = {
1687    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1688    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
1689  };
1690  return llvm::ConstantExpr::getGetElementPtr(C, Idxs);
1691}
1692
1693/// hasObjCExceptionAttribute - Return true if this class or any super
1694/// class has the __objc_exception__ attribute.
1695static bool hasObjCExceptionAttribute(ASTContext &Context,
1696                                      const ObjCInterfaceDecl *OID) {
1697  if (OID->hasAttr<ObjCExceptionAttr>())
1698    return true;
1699  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1700    return hasObjCExceptionAttribute(Context, Super);
1701  return false;
1702}
1703
1704/* *** CGObjCMac Public Interface *** */
1705
1706CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1707                                                    ObjCTypes(cgm) {
1708  ObjCABI = 1;
1709  EmitImageInfo();
1710}
1711
1712/// GetClass - Return a reference to the class for the given interface
1713/// decl.
1714llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
1715                                 const ObjCInterfaceDecl *ID) {
1716  return EmitClassRef(CGF, ID);
1717}
1718
1719/// GetSelector - Return the pointer to the unique'd string for this selector.
1720llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel,
1721                                    bool lval) {
1722  return EmitSelector(CGF, Sel, lval);
1723}
1724llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
1725                                    *Method) {
1726  return EmitSelector(CGF, Method->getSelector());
1727}
1728
1729llvm::Constant *CGObjCMac::GetEHType(QualType T) {
1730  if (T->isObjCIdType() ||
1731      T->isObjCQualifiedIdType()) {
1732    return CGM.GetAddrOfRTTIDescriptor(
1733              CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
1734  }
1735  if (T->isObjCClassType() ||
1736      T->isObjCQualifiedClassType()) {
1737    return CGM.GetAddrOfRTTIDescriptor(
1738             CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
1739  }
1740  if (T->isObjCObjectPointerType())
1741    return CGM.GetAddrOfRTTIDescriptor(T,  /*ForEH=*/true);
1742
1743  llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
1744}
1745
1746/// Generate a constant CFString object.
1747/*
1748  struct __builtin_CFString {
1749  const int *isa; // point to __CFConstantStringClassReference
1750  int flags;
1751  const char *str;
1752  long length;
1753  };
1754*/
1755
1756/// or Generate a constant NSString object.
1757/*
1758   struct __builtin_NSString {
1759     const int *isa; // point to __NSConstantStringClassReference
1760     const char *str;
1761     unsigned int length;
1762   };
1763*/
1764
1765llvm::Constant *CGObjCCommonMac::GenerateConstantString(
1766  const StringLiteral *SL) {
1767  return (CGM.getLangOpts().NoConstantCFStrings == 0 ?
1768          CGM.GetAddrOfConstantCFString(SL) :
1769          CGM.GetAddrOfConstantString(SL));
1770}
1771
1772enum {
1773  kCFTaggedObjectID_Integer = (1 << 1) + 1
1774};
1775
1776/// Generates a message send where the super is the receiver.  This is
1777/// a message send to self with special delivery semantics indicating
1778/// which class's method should be called.
1779CodeGen::RValue
1780CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1781                                    ReturnValueSlot Return,
1782                                    QualType ResultType,
1783                                    Selector Sel,
1784                                    const ObjCInterfaceDecl *Class,
1785                                    bool isCategoryImpl,
1786                                    llvm::Value *Receiver,
1787                                    bool IsClassMessage,
1788                                    const CodeGen::CallArgList &CallArgs,
1789                                    const ObjCMethodDecl *Method) {
1790  // Create and init a super structure; this is a (receiver, class)
1791  // pair we will pass to objc_msgSendSuper.
1792  llvm::Value *ObjCSuper =
1793    CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
1794  llvm::Value *ReceiverAsObject =
1795    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1796  CGF.Builder.CreateStore(ReceiverAsObject,
1797                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
1798
1799  // If this is a class message the metaclass is passed as the target.
1800  llvm::Value *Target;
1801  if (IsClassMessage) {
1802    if (isCategoryImpl) {
1803      // Message sent to 'super' in a class method defined in a category
1804      // implementation requires an odd treatment.
1805      // If we are in a class method, we must retrieve the
1806      // _metaclass_ for the current class, pointed at by
1807      // the class's "isa" pointer.  The following assumes that
1808      // isa" is the first ivar in a class (which it must be).
1809      Target = EmitClassRef(CGF, Class->getSuperClass());
1810      Target = CGF.Builder.CreateStructGEP(Target, 0);
1811      Target = CGF.Builder.CreateLoad(Target);
1812    } else {
1813      llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1814      llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1815      llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1816      Target = Super;
1817    }
1818  }
1819  else if (isCategoryImpl)
1820    Target = EmitClassRef(CGF, Class->getSuperClass());
1821  else {
1822    llvm::Value *ClassPtr = EmitSuperClassRef(Class);
1823    ClassPtr = CGF.Builder.CreateStructGEP(ClassPtr, 1);
1824    Target = CGF.Builder.CreateLoad(ClassPtr);
1825  }
1826  // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1827  // ObjCTypes types.
1828  llvm::Type *ClassTy =
1829    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
1830  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
1831  CGF.Builder.CreateStore(Target,
1832                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1833  return EmitMessageSend(CGF, Return, ResultType,
1834                         EmitSelector(CGF, Sel),
1835                         ObjCSuper, ObjCTypes.SuperPtrCTy,
1836                         true, CallArgs, Method, ObjCTypes);
1837}
1838
1839/// Generate code for a message send expression.
1840CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1841                                               ReturnValueSlot Return,
1842                                               QualType ResultType,
1843                                               Selector Sel,
1844                                               llvm::Value *Receiver,
1845                                               const CallArgList &CallArgs,
1846                                               const ObjCInterfaceDecl *Class,
1847                                               const ObjCMethodDecl *Method) {
1848  return EmitMessageSend(CGF, Return, ResultType,
1849                         EmitSelector(CGF, Sel),
1850                         Receiver, CGF.getContext().getObjCIdType(),
1851                         false, CallArgs, Method, ObjCTypes);
1852}
1853
1854CodeGen::RValue
1855CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1856                                 ReturnValueSlot Return,
1857                                 QualType ResultType,
1858                                 llvm::Value *Sel,
1859                                 llvm::Value *Arg0,
1860                                 QualType Arg0Ty,
1861                                 bool IsSuper,
1862                                 const CallArgList &CallArgs,
1863                                 const ObjCMethodDecl *Method,
1864                                 const ObjCCommonTypesHelper &ObjCTypes) {
1865  CallArgList ActualArgs;
1866  if (!IsSuper)
1867    Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
1868  ActualArgs.add(RValue::get(Arg0), Arg0Ty);
1869  ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
1870  ActualArgs.addFrom(CallArgs);
1871
1872  // If we're calling a method, use the formal signature.
1873  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1874
1875  if (Method)
1876    assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
1877               CGM.getContext().getCanonicalType(ResultType) &&
1878           "Result type mismatch!");
1879
1880  NullReturnState nullReturn;
1881
1882  llvm::Constant *Fn = nullptr;
1883  if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
1884    if (!IsSuper) nullReturn.init(CGF, Arg0);
1885    Fn = (ObjCABI == 2) ?  ObjCTypes.getSendStretFn2(IsSuper)
1886      : ObjCTypes.getSendStretFn(IsSuper);
1887  } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1888    Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
1889      : ObjCTypes.getSendFpretFn(IsSuper);
1890  } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
1891    Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
1892      : ObjCTypes.getSendFp2retFn(IsSuper);
1893  } else {
1894    // arm64 uses objc_msgSend for stret methods and yet null receiver check
1895    // must be made for it.
1896    if (!IsSuper && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1897      nullReturn.init(CGF, Arg0);
1898    Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1899      : ObjCTypes.getSendFn(IsSuper);
1900  }
1901
1902  bool requiresnullCheck = false;
1903  if (CGM.getLangOpts().ObjCAutoRefCount && Method)
1904    for (const auto *ParamDecl : Method->params()) {
1905      if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1906        if (!nullReturn.NullBB)
1907          nullReturn.init(CGF, Arg0);
1908        requiresnullCheck = true;
1909        break;
1910      }
1911    }
1912
1913  Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
1914  RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs);
1915  return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
1916                             requiresnullCheck ? Method : nullptr);
1917}
1918
1919static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
1920  if (FQT.isObjCGCStrong())
1921    return Qualifiers::Strong;
1922
1923  if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() == Qualifiers::OCL_Weak)
1924    return Qualifiers::Weak;
1925
1926  // check for __unsafe_unretained
1927  if (FQT.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
1928    return Qualifiers::GCNone;
1929
1930  if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
1931    return Qualifiers::Strong;
1932
1933  if (const PointerType *PT = FQT->getAs<PointerType>())
1934    return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
1935
1936  return Qualifiers::GCNone;
1937}
1938
1939llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
1940                                                const CGBlockInfo &blockInfo) {
1941
1942  llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1943  if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
1944      !CGM.getLangOpts().ObjCAutoRefCount)
1945    return nullPtr;
1946
1947  bool hasUnion = false;
1948  SkipIvars.clear();
1949  IvarsInfo.clear();
1950  unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
1951  unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
1952
1953  // __isa is the first field in block descriptor and must assume by runtime's
1954  // convention that it is GC'able.
1955  IvarsInfo.push_back(GC_IVAR(0, 1));
1956
1957  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1958
1959  // Calculate the basic layout of the block structure.
1960  const llvm::StructLayout *layout =
1961    CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
1962
1963  // Ignore the optional 'this' capture: C++ objects are not assumed
1964  // to be GC'ed.
1965
1966  // Walk the captured variables.
1967  for (const auto &CI : blockDecl->captures()) {
1968    const VarDecl *variable = CI.getVariable();
1969    QualType type = variable->getType();
1970
1971    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1972
1973    // Ignore constant captures.
1974    if (capture.isConstant()) continue;
1975
1976    uint64_t fieldOffset = layout->getElementOffset(capture.getIndex());
1977
1978    // __block variables are passed by their descriptor address.
1979    if (CI.isByRef()) {
1980      IvarsInfo.push_back(GC_IVAR(fieldOffset, /*size in words*/ 1));
1981      continue;
1982    }
1983
1984    assert(!type->isArrayType() && "array variable should not be caught");
1985    if (const RecordType *record = type->getAs<RecordType>()) {
1986      BuildAggrIvarRecordLayout(record, fieldOffset, true, hasUnion);
1987      continue;
1988    }
1989
1990    Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
1991    unsigned fieldSize = CGM.getContext().getTypeSize(type);
1992
1993    if (GCAttr == Qualifiers::Strong)
1994      IvarsInfo.push_back(GC_IVAR(fieldOffset,
1995                                  fieldSize / WordSizeInBits));
1996    else if (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak)
1997      SkipIvars.push_back(GC_IVAR(fieldOffset,
1998                                  fieldSize / ByteSizeInBits));
1999  }
2000
2001  if (IvarsInfo.empty())
2002    return nullPtr;
2003
2004  // Sort on byte position; captures might not be allocated in order,
2005  // and unions can do funny things.
2006  llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
2007  llvm::array_pod_sort(SkipIvars.begin(), SkipIvars.end());
2008
2009  std::string BitMap;
2010  llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
2011  if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2012    printf("\n block variable layout for block: ");
2013    const unsigned char *s = (const unsigned char*)BitMap.c_str();
2014    for (unsigned i = 0, e = BitMap.size(); i < e; i++)
2015      if (!(s[i] & 0xf0))
2016        printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
2017      else
2018        printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
2019    printf("\n");
2020  }
2021
2022  return C;
2023}
2024
2025/// getBlockCaptureLifetime - This routine returns life time of the captured
2026/// block variable for the purpose of block layout meta-data generation. FQT is
2027/// the type of the variable captured in the block.
2028Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
2029                                                                  bool ByrefLayout) {
2030  if (CGM.getLangOpts().ObjCAutoRefCount)
2031    return FQT.getObjCLifetime();
2032
2033  // MRR.
2034  if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
2035    return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
2036
2037  return Qualifiers::OCL_None;
2038}
2039
2040void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
2041                                             Qualifiers::ObjCLifetime LifeTime,
2042                                             CharUnits FieldOffset,
2043                                             CharUnits FieldSize) {
2044  // __block variables are passed by their descriptor address.
2045  if (IsByref)
2046    RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
2047                                        FieldSize));
2048  else if (LifeTime == Qualifiers::OCL_Strong)
2049    RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
2050                                        FieldSize));
2051  else if (LifeTime == Qualifiers::OCL_Weak)
2052    RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
2053                                        FieldSize));
2054  else if (LifeTime == Qualifiers::OCL_ExplicitNone)
2055    RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
2056                                        FieldSize));
2057  else
2058    RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
2059                                        FieldOffset,
2060                                        FieldSize));
2061}
2062
2063void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
2064                                          const RecordDecl *RD,
2065                                          ArrayRef<const FieldDecl*> RecFields,
2066                                          CharUnits BytePos, bool &HasUnion,
2067                                          bool ByrefLayout) {
2068  bool IsUnion = (RD && RD->isUnion());
2069  CharUnits MaxUnionSize = CharUnits::Zero();
2070  const FieldDecl *MaxField = nullptr;
2071  const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
2072  CharUnits MaxFieldOffset = CharUnits::Zero();
2073  CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
2074
2075  if (RecFields.empty())
2076    return;
2077  unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
2078
2079  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2080    const FieldDecl *Field = RecFields[i];
2081    // Note that 'i' here is actually the field index inside RD of Field,
2082    // although this dependency is hidden.
2083    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2084    CharUnits FieldOffset =
2085      CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
2086
2087    // Skip over unnamed or bitfields
2088    if (!Field->getIdentifier() || Field->isBitField()) {
2089      LastFieldBitfieldOrUnnamed = Field;
2090      LastBitfieldOrUnnamedOffset = FieldOffset;
2091      continue;
2092    }
2093
2094    LastFieldBitfieldOrUnnamed = nullptr;
2095    QualType FQT = Field->getType();
2096    if (FQT->isRecordType() || FQT->isUnionType()) {
2097      if (FQT->isUnionType())
2098        HasUnion = true;
2099
2100      BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
2101                                  BytePos + FieldOffset, HasUnion);
2102      continue;
2103    }
2104
2105    if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2106      const ConstantArrayType *CArray =
2107        dyn_cast_or_null<ConstantArrayType>(Array);
2108      uint64_t ElCount = CArray->getSize().getZExtValue();
2109      assert(CArray && "only array with known element size is supported");
2110      FQT = CArray->getElementType();
2111      while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2112        const ConstantArrayType *CArray =
2113          dyn_cast_or_null<ConstantArrayType>(Array);
2114        ElCount *= CArray->getSize().getZExtValue();
2115        FQT = CArray->getElementType();
2116      }
2117      if (FQT->isRecordType() && ElCount) {
2118        int OldIndex = RunSkipBlockVars.size() - 1;
2119        const RecordType *RT = FQT->getAs<RecordType>();
2120        BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
2121                                    HasUnion);
2122
2123        // Replicate layout information for each array element. Note that
2124        // one element is already done.
2125        uint64_t ElIx = 1;
2126        for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
2127          CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
2128          for (int i = OldIndex+1; i <= FirstIndex; ++i)
2129            RunSkipBlockVars.push_back(
2130              RUN_SKIP(RunSkipBlockVars[i].opcode,
2131              RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
2132              RunSkipBlockVars[i].block_var_size));
2133        }
2134        continue;
2135      }
2136    }
2137    CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
2138    if (IsUnion) {
2139      CharUnits UnionIvarSize = FieldSize;
2140      if (UnionIvarSize > MaxUnionSize) {
2141        MaxUnionSize = UnionIvarSize;
2142        MaxField = Field;
2143        MaxFieldOffset = FieldOffset;
2144      }
2145    } else {
2146      UpdateRunSkipBlockVars(false,
2147                             getBlockCaptureLifetime(FQT, ByrefLayout),
2148                             BytePos + FieldOffset,
2149                             FieldSize);
2150    }
2151  }
2152
2153  if (LastFieldBitfieldOrUnnamed) {
2154    if (LastFieldBitfieldOrUnnamed->isBitField()) {
2155      // Last field was a bitfield. Must update the info.
2156      uint64_t BitFieldSize
2157        = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
2158      unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
2159                        ((BitFieldSize % ByteSizeInBits) != 0);
2160      CharUnits Size = CharUnits::fromQuantity(UnsSize);
2161      Size += LastBitfieldOrUnnamedOffset;
2162      UpdateRunSkipBlockVars(false,
2163                             getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2164                                                     ByrefLayout),
2165                             BytePos + LastBitfieldOrUnnamedOffset,
2166                             Size);
2167    } else {
2168      assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
2169      // Last field was unnamed. Must update skip info.
2170      CharUnits FieldSize
2171        = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
2172      UpdateRunSkipBlockVars(false,
2173                             getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
2174                                                     ByrefLayout),
2175                             BytePos + LastBitfieldOrUnnamedOffset,
2176                             FieldSize);
2177    }
2178  }
2179
2180  if (MaxField)
2181    UpdateRunSkipBlockVars(false,
2182                           getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
2183                           BytePos + MaxFieldOffset,
2184                           MaxUnionSize);
2185}
2186
2187void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
2188                                                  CharUnits BytePos,
2189                                                  bool &HasUnion,
2190                                                  bool ByrefLayout) {
2191  const RecordDecl *RD = RT->getDecl();
2192  SmallVector<const FieldDecl*, 16> Fields(RD->fields());
2193  llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2194  const llvm::StructLayout *RecLayout =
2195    CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
2196
2197  BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
2198}
2199
2200/// InlineLayoutInstruction - This routine produce an inline instruction for the
2201/// block variable layout if it can. If not, it returns 0. Rules are as follow:
2202/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
2203/// an inline layout of value 0x0000000000000xyz is interpreted as follows:
2204/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
2205/// y captured object of BLOCK_LAYOUT_BYREF. Followed by
2206/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
2207/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
2208/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
2209uint64_t CGObjCCommonMac::InlineLayoutInstruction(
2210                                    SmallVectorImpl<unsigned char> &Layout) {
2211  uint64_t Result = 0;
2212  if (Layout.size() <= 3) {
2213    unsigned size = Layout.size();
2214    unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
2215    unsigned char inst;
2216    enum BLOCK_LAYOUT_OPCODE opcode ;
2217    switch (size) {
2218      case 3:
2219        inst = Layout[0];
2220        opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2221        if (opcode == BLOCK_LAYOUT_STRONG)
2222          strong_word_count = (inst & 0xF)+1;
2223        else
2224          return 0;
2225        inst = Layout[1];
2226        opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2227        if (opcode == BLOCK_LAYOUT_BYREF)
2228          byref_word_count = (inst & 0xF)+1;
2229        else
2230          return 0;
2231        inst = Layout[2];
2232        opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2233        if (opcode == BLOCK_LAYOUT_WEAK)
2234          weak_word_count = (inst & 0xF)+1;
2235        else
2236          return 0;
2237        break;
2238
2239      case 2:
2240        inst = Layout[0];
2241        opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2242        if (opcode == BLOCK_LAYOUT_STRONG) {
2243          strong_word_count = (inst & 0xF)+1;
2244          inst = Layout[1];
2245          opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2246          if (opcode == BLOCK_LAYOUT_BYREF)
2247            byref_word_count = (inst & 0xF)+1;
2248          else if (opcode == BLOCK_LAYOUT_WEAK)
2249            weak_word_count = (inst & 0xF)+1;
2250          else
2251            return 0;
2252        }
2253        else if (opcode == BLOCK_LAYOUT_BYREF) {
2254          byref_word_count = (inst & 0xF)+1;
2255          inst = Layout[1];
2256          opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2257          if (opcode == BLOCK_LAYOUT_WEAK)
2258            weak_word_count = (inst & 0xF)+1;
2259          else
2260            return 0;
2261        }
2262        else
2263          return 0;
2264        break;
2265
2266      case 1:
2267        inst = Layout[0];
2268        opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2269        if (opcode == BLOCK_LAYOUT_STRONG)
2270          strong_word_count = (inst & 0xF)+1;
2271        else if (opcode == BLOCK_LAYOUT_BYREF)
2272          byref_word_count = (inst & 0xF)+1;
2273        else if (opcode == BLOCK_LAYOUT_WEAK)
2274          weak_word_count = (inst & 0xF)+1;
2275        else
2276          return 0;
2277        break;
2278
2279      default:
2280        return 0;
2281    }
2282
2283    // Cannot inline when any of the word counts is 15. Because this is one less
2284    // than the actual work count (so 15 means 16 actual word counts),
2285    // and we can only display 0 thru 15 word counts.
2286    if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
2287      return 0;
2288
2289    unsigned count =
2290      (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
2291
2292    if (size == count) {
2293      if (strong_word_count)
2294        Result = strong_word_count;
2295      Result <<= 4;
2296      if (byref_word_count)
2297        Result += byref_word_count;
2298      Result <<= 4;
2299      if (weak_word_count)
2300        Result += weak_word_count;
2301    }
2302  }
2303  return Result;
2304}
2305
2306llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
2307  llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2308  if (RunSkipBlockVars.empty())
2309    return nullPtr;
2310  unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2311  unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
2312  unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2313
2314  // Sort on byte position; captures might not be allocated in order,
2315  // and unions can do funny things.
2316  llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
2317  SmallVector<unsigned char, 16> Layout;
2318
2319  unsigned size = RunSkipBlockVars.size();
2320  for (unsigned i = 0; i < size; i++) {
2321    enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
2322    CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
2323    CharUnits end_byte_pos = start_byte_pos;
2324    unsigned j = i+1;
2325    while (j < size) {
2326      if (opcode == RunSkipBlockVars[j].opcode) {
2327        end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
2328        i++;
2329      }
2330      else
2331        break;
2332    }
2333    CharUnits size_in_bytes =
2334    end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
2335    if (j < size) {
2336      CharUnits gap =
2337      RunSkipBlockVars[j].block_var_bytepos -
2338      RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
2339      size_in_bytes += gap;
2340    }
2341    CharUnits residue_in_bytes = CharUnits::Zero();
2342    if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
2343      residue_in_bytes = size_in_bytes % WordSizeInBytes;
2344      size_in_bytes -= residue_in_bytes;
2345      opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
2346    }
2347
2348    unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
2349    while (size_in_words >= 16) {
2350      // Note that value in imm. is one less that the actual
2351      // value. So, 0xf means 16 words follow!
2352      unsigned char inst = (opcode << 4) | 0xf;
2353      Layout.push_back(inst);
2354      size_in_words -= 16;
2355    }
2356    if (size_in_words > 0) {
2357      // Note that value in imm. is one less that the actual
2358      // value. So, we subtract 1 away!
2359      unsigned char inst = (opcode << 4) | (size_in_words-1);
2360      Layout.push_back(inst);
2361    }
2362    if (residue_in_bytes > CharUnits::Zero()) {
2363      unsigned char inst =
2364      (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
2365      Layout.push_back(inst);
2366    }
2367  }
2368
2369  int e = Layout.size()-1;
2370  while (e >= 0) {
2371    unsigned char inst = Layout[e--];
2372    enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2373    if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
2374      Layout.pop_back();
2375    else
2376      break;
2377  }
2378
2379  uint64_t Result = InlineLayoutInstruction(Layout);
2380  if (Result != 0) {
2381    // Block variable layout instruction has been inlined.
2382    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2383      if (ComputeByrefLayout)
2384        printf("\n Inline instruction for BYREF variable layout: ");
2385      else
2386        printf("\n Inline instruction for block variable layout: ");
2387      printf("0x0%" PRIx64 "\n", Result);
2388    }
2389    if (WordSizeInBytes == 8) {
2390      const llvm::APInt Instruction(64, Result);
2391      return llvm::Constant::getIntegerValue(CGM.Int64Ty, Instruction);
2392    }
2393    else {
2394      const llvm::APInt Instruction(32, Result);
2395      return llvm::Constant::getIntegerValue(CGM.Int32Ty, Instruction);
2396    }
2397  }
2398
2399  unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
2400  Layout.push_back(inst);
2401  std::string BitMap;
2402  for (unsigned i = 0, e = Layout.size(); i != e; i++)
2403    BitMap += Layout[i];
2404
2405  if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2406    if (ComputeByrefLayout)
2407      printf("\n BYREF variable layout: ");
2408    else
2409      printf("\n block variable layout: ");
2410    for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
2411      unsigned char inst = BitMap[i];
2412      enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
2413      unsigned delta = 1;
2414      switch (opcode) {
2415        case BLOCK_LAYOUT_OPERATOR:
2416          printf("BL_OPERATOR:");
2417          delta = 0;
2418          break;
2419        case BLOCK_LAYOUT_NON_OBJECT_BYTES:
2420          printf("BL_NON_OBJECT_BYTES:");
2421          break;
2422        case BLOCK_LAYOUT_NON_OBJECT_WORDS:
2423          printf("BL_NON_OBJECT_WORD:");
2424          break;
2425        case BLOCK_LAYOUT_STRONG:
2426          printf("BL_STRONG:");
2427          break;
2428        case BLOCK_LAYOUT_BYREF:
2429          printf("BL_BYREF:");
2430          break;
2431        case BLOCK_LAYOUT_WEAK:
2432          printf("BL_WEAK:");
2433          break;
2434        case BLOCK_LAYOUT_UNRETAINED:
2435          printf("BL_UNRETAINED:");
2436          break;
2437      }
2438      // Actual value of word count is one more that what is in the imm.
2439      // field of the instruction
2440      printf("%d", (inst & 0xf) + delta);
2441      if (i < e-1)
2442        printf(", ");
2443      else
2444        printf("\n");
2445    }
2446  }
2447
2448  llvm::GlobalVariable * Entry =
2449  CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2450                    llvm::ConstantDataArray::getString(VMContext, BitMap,false),
2451                    "__TEXT,__objc_classname,cstring_literals", 1, true);
2452  return getConstantGEP(VMContext, Entry, 0, 0);
2453}
2454
2455llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
2456                                                    const CGBlockInfo &blockInfo) {
2457  assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2458
2459  RunSkipBlockVars.clear();
2460  bool hasUnion = false;
2461
2462  unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
2463  unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
2464  unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
2465
2466  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
2467
2468  // Calculate the basic layout of the block structure.
2469  const llvm::StructLayout *layout =
2470  CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
2471
2472  // Ignore the optional 'this' capture: C++ objects are not assumed
2473  // to be GC'ed.
2474  if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
2475    UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
2476                           blockInfo.BlockHeaderForcedGapOffset,
2477                           blockInfo.BlockHeaderForcedGapSize);
2478  // Walk the captured variables.
2479  for (const auto &CI : blockDecl->captures()) {
2480    const VarDecl *variable = CI.getVariable();
2481    QualType type = variable->getType();
2482
2483    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
2484
2485    // Ignore constant captures.
2486    if (capture.isConstant()) continue;
2487
2488    CharUnits fieldOffset =
2489       CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
2490
2491    assert(!type->isArrayType() && "array variable should not be caught");
2492    if (!CI.isByRef())
2493      if (const RecordType *record = type->getAs<RecordType>()) {
2494        BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
2495        continue;
2496      }
2497    CharUnits fieldSize;
2498    if (CI.isByRef())
2499      fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
2500    else
2501      fieldSize = CGM.getContext().getTypeSizeInChars(type);
2502    UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
2503                           fieldOffset, fieldSize);
2504  }
2505  return getBitmapBlockLayout(false);
2506}
2507
2508
2509llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
2510                                                  QualType T) {
2511  assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
2512  assert(!T->isArrayType() && "__block array variable should not be caught");
2513  CharUnits fieldOffset;
2514  RunSkipBlockVars.clear();
2515  bool hasUnion = false;
2516  if (const RecordType *record = T->getAs<RecordType>()) {
2517    BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
2518    llvm::Constant *Result = getBitmapBlockLayout(true);
2519    return Result;
2520  }
2521  llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
2522  return nullPtr;
2523}
2524
2525llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
2526                                            const ObjCProtocolDecl *PD) {
2527  // FIXME: I don't understand why gcc generates this, or where it is
2528  // resolved. Investigate. Its also wasteful to look this up over and over.
2529  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2530
2531  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
2532                                        ObjCTypes.getExternalProtocolPtrTy());
2533}
2534
2535void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
2536  // FIXME: We shouldn't need this, the protocol decl should contain enough
2537  // information to tell us whether this was a declaration or a definition.
2538  DefinedProtocols.insert(PD->getIdentifier());
2539
2540  // If we have generated a forward reference to this protocol, emit
2541  // it now. Otherwise do nothing, the protocol objects are lazily
2542  // emitted.
2543  if (Protocols.count(PD->getIdentifier()))
2544    GetOrEmitProtocol(PD);
2545}
2546
2547llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
2548  if (DefinedProtocols.count(PD->getIdentifier()))
2549    return GetOrEmitProtocol(PD);
2550
2551  return GetOrEmitProtocolRef(PD);
2552}
2553
2554static void assertPrivateName(const llvm::GlobalValue *GV) {
2555  StringRef NameRef = GV->getName();
2556  (void)NameRef;
2557  assert(NameRef[0] == '\01' && (NameRef[1] == 'L' || NameRef[1] == 'l'));
2558  assert(GV->getVisibility() == llvm::GlobalValue::DefaultVisibility);
2559  assert(GV->hasPrivateLinkage());
2560}
2561
2562/*
2563// Objective-C 1.0 extensions
2564struct _objc_protocol {
2565struct _objc_protocol_extension *isa;
2566char *protocol_name;
2567struct _objc_protocol_list *protocol_list;
2568struct _objc__method_prototype_list *instance_methods;
2569struct _objc__method_prototype_list *class_methods
2570};
2571
2572See EmitProtocolExtension().
2573*/
2574llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
2575  llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
2576
2577  // Early exit if a defining object has already been generated.
2578  if (Entry && Entry->hasInitializer())
2579    return Entry;
2580
2581  // Use the protocol definition, if there is one.
2582  if (const ObjCProtocolDecl *Def = PD->getDefinition())
2583    PD = Def;
2584
2585  // FIXME: I don't understand why gcc generates this, or where it is
2586  // resolved. Investigate. Its also wasteful to look this up over and over.
2587  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
2588
2589  // Construct method lists.
2590  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
2591  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
2592  std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
2593  for (const auto *MD : PD->instance_methods()) {
2594    llvm::Constant *C = GetMethodDescriptionConstant(MD);
2595    if (!C)
2596      return GetOrEmitProtocolRef(PD);
2597
2598    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2599      OptInstanceMethods.push_back(C);
2600      OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
2601    } else {
2602      InstanceMethods.push_back(C);
2603      MethodTypesExt.push_back(GetMethodVarType(MD, true));
2604    }
2605  }
2606
2607  for (const auto *MD : PD->class_methods()) {
2608    llvm::Constant *C = GetMethodDescriptionConstant(MD);
2609    if (!C)
2610      return GetOrEmitProtocolRef(PD);
2611
2612    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
2613      OptClassMethods.push_back(C);
2614      OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
2615    } else {
2616      ClassMethods.push_back(C);
2617      MethodTypesExt.push_back(GetMethodVarType(MD, true));
2618    }
2619  }
2620
2621  MethodTypesExt.insert(MethodTypesExt.end(),
2622                        OptMethodTypesExt.begin(), OptMethodTypesExt.end());
2623
2624  llvm::Constant *Values[] = {
2625    EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
2626                          MethodTypesExt),
2627    GetClassName(PD->getIdentifier()),
2628    EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getName(),
2629                     PD->protocol_begin(),
2630                     PD->protocol_end()),
2631    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
2632                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2633                       InstanceMethods),
2634    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
2635                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2636                       ClassMethods)
2637  };
2638  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2639                                                   Values);
2640
2641  if (Entry) {
2642    // Already created, update the initializer.
2643    assert(Entry->hasPrivateLinkage());
2644    Entry->setInitializer(Init);
2645  } else {
2646    Entry =
2647      new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
2648                               llvm::GlobalValue::PrivateLinkage,
2649                               Init,
2650                               "\01L_OBJC_PROTOCOL_" + PD->getName());
2651    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
2652    // FIXME: Is this necessary? Why only for protocol?
2653    Entry->setAlignment(4);
2654
2655    Protocols[PD->getIdentifier()] = Entry;
2656  }
2657  assertPrivateName(Entry);
2658  CGM.addCompilerUsedGlobal(Entry);
2659
2660  return Entry;
2661}
2662
2663llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
2664  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
2665
2666  if (!Entry) {
2667    // We use the initializer as a marker of whether this is a forward
2668    // reference or not. At module finalization we add the empty
2669    // contents for protocols which were referenced but never defined.
2670    Entry =
2671      new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
2672                               llvm::GlobalValue::PrivateLinkage,
2673                               nullptr,
2674                               "\01L_OBJC_PROTOCOL_" + PD->getName());
2675    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
2676    // FIXME: Is this necessary? Why only for protocol?
2677    Entry->setAlignment(4);
2678  }
2679  assertPrivateName(Entry);
2680
2681  return Entry;
2682}
2683
2684/*
2685  struct _objc_protocol_extension {
2686  uint32_t size;
2687  struct objc_method_description_list *optional_instance_methods;
2688  struct objc_method_description_list *optional_class_methods;
2689  struct objc_property_list *instance_properties;
2690  const char ** extendedMethodTypes;
2691  };
2692*/
2693llvm::Constant *
2694CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
2695                                 ArrayRef<llvm::Constant*> OptInstanceMethods,
2696                                 ArrayRef<llvm::Constant*> OptClassMethods,
2697                                 ArrayRef<llvm::Constant*> MethodTypesExt) {
2698  uint64_t Size =
2699    CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
2700  llvm::Constant *Values[] = {
2701    llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
2702    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
2703                       + PD->getName(),
2704                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2705                       OptInstanceMethods),
2706    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
2707                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2708                       OptClassMethods),
2709    EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr,
2710                     PD, ObjCTypes),
2711    EmitProtocolMethodTypes("\01L_OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
2712                            MethodTypesExt, ObjCTypes)
2713  };
2714
2715  // Return null if no extension bits are used.
2716  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
2717      Values[3]->isNullValue() && Values[4]->isNullValue())
2718    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2719
2720  llvm::Constant *Init =
2721    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
2722
2723  // No special section, but goes in llvm.used
2724  return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init,
2725                           StringRef(), 0, true);
2726}
2727
2728/*
2729  struct objc_protocol_list {
2730    struct objc_protocol_list *next;
2731    long count;
2732    Protocol *list[];
2733  };
2734*/
2735llvm::Constant *
2736CGObjCMac::EmitProtocolList(Twine Name,
2737                            ObjCProtocolDecl::protocol_iterator begin,
2738                            ObjCProtocolDecl::protocol_iterator end) {
2739  SmallVector<llvm::Constant *, 16> ProtocolRefs;
2740
2741  for (; begin != end; ++begin)
2742    ProtocolRefs.push_back(GetProtocolRef(*begin));
2743
2744  // Just return null for empty protocol lists
2745  if (ProtocolRefs.empty())
2746    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2747
2748  // This list is null terminated.
2749  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
2750
2751  llvm::Constant *Values[3];
2752  // This field is only used by the runtime.
2753  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2754  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
2755                                     ProtocolRefs.size() - 1);
2756  Values[2] =
2757    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
2758                                                  ProtocolRefs.size()),
2759                             ProtocolRefs);
2760
2761  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2762  llvm::GlobalVariable *GV =
2763    CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2764                      4, false);
2765  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
2766}
2767
2768void CGObjCCommonMac::
2769PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
2770                       SmallVectorImpl<llvm::Constant *> &Properties,
2771                       const Decl *Container,
2772                       const ObjCProtocolDecl *Proto,
2773                       const ObjCCommonTypesHelper &ObjCTypes) {
2774  for (const auto *P : Proto->protocols())
2775    PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
2776  for (const auto *PD : Proto->properties()) {
2777    if (!PropertySet.insert(PD->getIdentifier()))
2778      continue;
2779    llvm::Constant *Prop[] = {
2780      GetPropertyName(PD->getIdentifier()),
2781      GetPropertyTypeString(PD, Container)
2782    };
2783    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
2784  }
2785}
2786
2787/*
2788  struct _objc_property {
2789    const char * const name;
2790    const char * const attributes;
2791  };
2792
2793  struct _objc_property_list {
2794    uint32_t entsize; // sizeof (struct _objc_property)
2795    uint32_t prop_count;
2796    struct _objc_property[prop_count];
2797  };
2798*/
2799llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
2800                                       const Decl *Container,
2801                                       const ObjCContainerDecl *OCD,
2802                                       const ObjCCommonTypesHelper &ObjCTypes) {
2803  SmallVector<llvm::Constant *, 16> Properties;
2804  llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
2805  for (const auto *PD : OCD->properties()) {
2806    PropertySet.insert(PD->getIdentifier());
2807    llvm::Constant *Prop[] = {
2808      GetPropertyName(PD->getIdentifier()),
2809      GetPropertyTypeString(PD, Container)
2810    };
2811    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
2812                                                   Prop));
2813  }
2814  if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
2815    for (const auto *P : OID->all_referenced_protocols())
2816      PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
2817  }
2818  else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
2819    for (const auto *P : CD->protocols())
2820      PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
2821  }
2822
2823  // Return null for empty list.
2824  if (Properties.empty())
2825    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2826
2827  unsigned PropertySize =
2828    CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
2829  llvm::Constant *Values[3];
2830  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
2831  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
2832  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
2833                                             Properties.size());
2834  Values[2] = llvm::ConstantArray::get(AT, Properties);
2835  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2836
2837  llvm::GlobalVariable *GV =
2838    CreateMetadataVar(Name, Init,
2839                      (ObjCABI == 2) ? "__DATA, __objc_const" :
2840                      "__OBJC,__property,regular,no_dead_strip",
2841                      (ObjCABI == 2) ? 8 : 4,
2842                      true);
2843  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
2844}
2845
2846llvm::Constant *
2847CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
2848                                         ArrayRef<llvm::Constant*> MethodTypes,
2849                                         const ObjCCommonTypesHelper &ObjCTypes) {
2850  // Return null for empty list.
2851  if (MethodTypes.empty())
2852    return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
2853
2854  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2855                                             MethodTypes.size());
2856  llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
2857
2858  llvm::GlobalVariable *GV = CreateMetadataVar(
2859      Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(),
2860      (ObjCABI == 2) ? 8 : 4, true);
2861  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
2862}
2863
2864/*
2865  struct objc_method_description_list {
2866  int count;
2867  struct objc_method_description list[];
2868  };
2869*/
2870llvm::Constant *
2871CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
2872  llvm::Constant *Desc[] = {
2873    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2874                                   ObjCTypes.SelectorPtrTy),
2875    GetMethodVarType(MD)
2876  };
2877  if (!Desc[1])
2878    return nullptr;
2879
2880  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
2881                                   Desc);
2882}
2883
2884llvm::Constant *
2885CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
2886                              ArrayRef<llvm::Constant*> Methods) {
2887  // Return null for empty list.
2888  if (Methods.empty())
2889    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2890
2891  llvm::Constant *Values[2];
2892  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2893  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
2894                                             Methods.size());
2895  Values[1] = llvm::ConstantArray::get(AT, Methods);
2896  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
2897
2898  llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
2899  return llvm::ConstantExpr::getBitCast(GV,
2900                                        ObjCTypes.MethodDescriptionListPtrTy);
2901}
2902
2903/*
2904  struct _objc_category {
2905  char *category_name;
2906  char *class_name;
2907  struct _objc_method_list *instance_methods;
2908  struct _objc_method_list *class_methods;
2909  struct _objc_protocol_list *protocols;
2910  uint32_t size; // <rdar://4585769>
2911  struct _objc_property_list *instance_properties;
2912  };
2913*/
2914void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2915  unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
2916
2917  // FIXME: This is poor design, the OCD should have a pointer to the category
2918  // decl. Additionally, note that Category can be null for the @implementation
2919  // w/o an @interface case. Sema should just create one for us as it does for
2920  // @implementation so everyone else can live life under a clear blue sky.
2921  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
2922  const ObjCCategoryDecl *Category =
2923    Interface->FindCategoryDeclaration(OCD->getIdentifier());
2924
2925  SmallString<256> ExtName;
2926  llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
2927                                     << OCD->getName();
2928
2929  SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
2930  for (const auto *I : OCD->instance_methods())
2931    // Instance methods should always be defined.
2932    InstanceMethods.push_back(GetMethodConstant(I));
2933
2934  for (const auto *I : OCD->class_methods())
2935    // Class methods should always be defined.
2936    ClassMethods.push_back(GetMethodConstant(I));
2937
2938  llvm::Constant *Values[7];
2939  Values[0] = GetClassName(OCD->getIdentifier());
2940  Values[1] = GetClassName(Interface->getIdentifier());
2941  LazySymbols.insert(Interface->getIdentifier());
2942  Values[2] =
2943    EmitMethodList("\01L_OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
2944                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
2945                   InstanceMethods);
2946  Values[3] =
2947    EmitMethodList("\01L_OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
2948                   "__OBJC,__cat_cls_meth,regular,no_dead_strip",
2949                   ClassMethods);
2950  if (Category) {
2951    Values[4] =
2952      EmitProtocolList("\01L_OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
2953                       Category->protocol_begin(),
2954                       Category->protocol_end());
2955  } else {
2956    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2957  }
2958  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
2959
2960  // If there is no category @interface then there can be no properties.
2961  if (Category) {
2962    Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
2963                                 OCD, Category, ObjCTypes);
2964  } else {
2965    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
2966  }
2967
2968  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
2969                                                   Values);
2970
2971  llvm::GlobalVariable *GV =
2972    CreateMetadataVar("\01L_OBJC_CATEGORY_" + ExtName.str(), Init,
2973                      "__OBJC,__category,regular,no_dead_strip",
2974                      4, true);
2975  DefinedCategories.push_back(GV);
2976  DefinedCategoryNames.insert(ExtName.str());
2977  // method definition entries must be clear for next implementation.
2978  MethodDefinitions.clear();
2979}
2980
2981enum FragileClassFlags {
2982  FragileABI_Class_Factory                 = 0x00001,
2983  FragileABI_Class_Meta                    = 0x00002,
2984  FragileABI_Class_HasCXXStructors         = 0x02000,
2985  FragileABI_Class_Hidden                  = 0x20000
2986};
2987
2988enum NonFragileClassFlags {
2989  /// Is a meta-class.
2990  NonFragileABI_Class_Meta                 = 0x00001,
2991
2992  /// Is a root class.
2993  NonFragileABI_Class_Root                 = 0x00002,
2994
2995  /// Has a C++ constructor and destructor.
2996  NonFragileABI_Class_HasCXXStructors      = 0x00004,
2997
2998  /// Has hidden visibility.
2999  NonFragileABI_Class_Hidden               = 0x00010,
3000
3001  /// Has the exception attribute.
3002  NonFragileABI_Class_Exception            = 0x00020,
3003
3004  /// (Obsolete) ARC-specific: this class has a .release_ivars method
3005  NonFragileABI_Class_HasIvarReleaser      = 0x00040,
3006
3007  /// Class implementation was compiled under ARC.
3008  NonFragileABI_Class_CompiledByARC        = 0x00080,
3009
3010  /// Class has non-trivial destructors, but zero-initialization is okay.
3011  NonFragileABI_Class_HasCXXDestructorOnly = 0x00100
3012};
3013
3014/*
3015  struct _objc_class {
3016  Class isa;
3017  Class super_class;
3018  const char *name;
3019  long version;
3020  long info;
3021  long instance_size;
3022  struct _objc_ivar_list *ivars;
3023  struct _objc_method_list *methods;
3024  struct _objc_cache *cache;
3025  struct _objc_protocol_list *protocols;
3026  // Objective-C 1.0 extensions (<rdr://4585769>)
3027  const char *ivar_layout;
3028  struct _objc_class_ext *ext;
3029  };
3030
3031  See EmitClassExtension();
3032*/
3033void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
3034  DefinedSymbols.insert(ID->getIdentifier());
3035
3036  std::string ClassName = ID->getNameAsString();
3037  // FIXME: Gross
3038  ObjCInterfaceDecl *Interface =
3039    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
3040  llvm::Constant *Protocols =
3041    EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getName(),
3042                     Interface->all_referenced_protocol_begin(),
3043                     Interface->all_referenced_protocol_end());
3044  unsigned Flags = FragileABI_Class_Factory;
3045  if (ID->hasNonZeroConstructors() || ID->hasDestructors())
3046    Flags |= FragileABI_Class_HasCXXStructors;
3047  unsigned Size =
3048    CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
3049
3050  // FIXME: Set CXX-structors flag.
3051  if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
3052    Flags |= FragileABI_Class_Hidden;
3053
3054  SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
3055  for (const auto *I : ID->instance_methods())
3056    // Instance methods should always be defined.
3057    InstanceMethods.push_back(GetMethodConstant(I));
3058
3059  for (const auto *I : ID->class_methods())
3060    // Class methods should always be defined.
3061    ClassMethods.push_back(GetMethodConstant(I));
3062
3063  for (const auto *PID : ID->property_impls()) {
3064    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3065      ObjCPropertyDecl *PD = PID->getPropertyDecl();
3066
3067      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3068        if (llvm::Constant *C = GetMethodConstant(MD))
3069          InstanceMethods.push_back(C);
3070      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3071        if (llvm::Constant *C = GetMethodConstant(MD))
3072          InstanceMethods.push_back(C);
3073    }
3074  }
3075
3076  llvm::Constant *Values[12];
3077  Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
3078  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
3079    // Record a reference to the super class.
3080    LazySymbols.insert(Super->getIdentifier());
3081
3082    Values[ 1] =
3083      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
3084                                     ObjCTypes.ClassPtrTy);
3085  } else {
3086    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
3087  }
3088  Values[ 2] = GetClassName(ID->getIdentifier());
3089  // Version is always 0.
3090  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3091  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
3092  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
3093  Values[ 6] = EmitIvarList(ID, false);
3094  Values[ 7] =
3095    EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getName(),
3096                   "__OBJC,__inst_meth,regular,no_dead_strip",
3097                   InstanceMethods);
3098  // cache is always NULL.
3099  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
3100  Values[ 9] = Protocols;
3101  Values[10] = BuildIvarLayout(ID, true);
3102  Values[11] = EmitClassExtension(ID);
3103  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
3104                                                   Values);
3105  std::string Name("\01L_OBJC_CLASS_");
3106  Name += ClassName;
3107  const char *Section = "__OBJC,__class,regular,no_dead_strip";
3108  // Check for a forward reference.
3109  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3110  if (GV) {
3111    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3112           "Forward metaclass reference has incorrect type.");
3113    GV->setInitializer(Init);
3114    GV->setSection(Section);
3115    GV->setAlignment(4);
3116    CGM.addCompilerUsedGlobal(GV);
3117  } else
3118    GV = CreateMetadataVar(Name, Init, Section, 4, true);
3119  assertPrivateName(GV);
3120  DefinedClasses.push_back(GV);
3121  ImplementedClasses.push_back(Interface);
3122  // method definition entries must be clear for next implementation.
3123  MethodDefinitions.clear();
3124}
3125
3126llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
3127                                         llvm::Constant *Protocols,
3128                                         ArrayRef<llvm::Constant*> Methods) {
3129  unsigned Flags = FragileABI_Class_Meta;
3130  unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
3131
3132  if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
3133    Flags |= FragileABI_Class_Hidden;
3134
3135  llvm::Constant *Values[12];
3136  // The isa for the metaclass is the root of the hierarchy.
3137  const ObjCInterfaceDecl *Root = ID->getClassInterface();
3138  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3139    Root = Super;
3140  Values[ 0] =
3141    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
3142                                   ObjCTypes.ClassPtrTy);
3143  // The super class for the metaclass is emitted as the name of the
3144  // super class. The runtime fixes this up to point to the
3145  // *metaclass* for the super class.
3146  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
3147    Values[ 1] =
3148      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
3149                                     ObjCTypes.ClassPtrTy);
3150  } else {
3151    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
3152  }
3153  Values[ 2] = GetClassName(ID->getIdentifier());
3154  // Version is always 0.
3155  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
3156  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
3157  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
3158  Values[ 6] = EmitIvarList(ID, true);
3159  Values[ 7] =
3160    EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
3161                   "__OBJC,__cls_meth,regular,no_dead_strip",
3162                   Methods);
3163  // cache is always NULL.
3164  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
3165  Values[ 9] = Protocols;
3166  // ivar_layout for metaclass is always NULL.
3167  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3168  // The class extension is always unused for metaclasses.
3169  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
3170  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
3171                                                   Values);
3172
3173  std::string Name("\01L_OBJC_METACLASS_");
3174  Name += ID->getName();
3175
3176  // Check for a forward reference.
3177  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3178  if (GV) {
3179    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3180           "Forward metaclass reference has incorrect type.");
3181    GV->setInitializer(Init);
3182  } else {
3183    GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
3184                                  llvm::GlobalValue::PrivateLinkage,
3185                                  Init, Name);
3186  }
3187  assertPrivateName(GV);
3188  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
3189  GV->setAlignment(4);
3190  CGM.addCompilerUsedGlobal(GV);
3191
3192  return GV;
3193}
3194
3195llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
3196  std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
3197
3198  // FIXME: Should we look these up somewhere other than the module. Its a bit
3199  // silly since we only generate these while processing an implementation, so
3200  // exactly one pointer would work if know when we entered/exitted an
3201  // implementation block.
3202
3203  // Check for an existing forward reference.
3204  // Previously, metaclass with internal linkage may have been defined.
3205  // pass 'true' as 2nd argument so it is returned.
3206  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3207  if (!GV)
3208    GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
3209                                  llvm::GlobalValue::PrivateLinkage, nullptr,
3210                                  Name);
3211
3212  assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3213         "Forward metaclass reference has incorrect type.");
3214  assertPrivateName(GV);
3215  return GV;
3216}
3217
3218llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
3219  std::string Name = "\01L_OBJC_CLASS_" + ID->getNameAsString();
3220  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
3221
3222  if (!GV)
3223    GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
3224                                  llvm::GlobalValue::PrivateLinkage, nullptr,
3225                                  Name);
3226
3227  assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
3228         "Forward class metadata reference has incorrect type.");
3229  assertPrivateName(GV);
3230  return GV;
3231}
3232
3233/*
3234  struct objc_class_ext {
3235  uint32_t size;
3236  const char *weak_ivar_layout;
3237  struct _objc_property_list *properties;
3238  };
3239*/
3240llvm::Constant *
3241CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
3242  uint64_t Size =
3243    CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
3244
3245  llvm::Constant *Values[3];
3246  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3247  Values[1] = BuildIvarLayout(ID, false);
3248  Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
3249                               ID, ID->getClassInterface(), ObjCTypes);
3250
3251  // Return null if no extension bits are used.
3252  if (Values[1]->isNullValue() && Values[2]->isNullValue())
3253    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
3254
3255  llvm::Constant *Init =
3256    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
3257  return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getName(),
3258                           Init, "__OBJC,__class_ext,regular,no_dead_strip",
3259                           4, true);
3260}
3261
3262/*
3263  struct objc_ivar {
3264    char *ivar_name;
3265    char *ivar_type;
3266    int ivar_offset;
3267  };
3268
3269  struct objc_ivar_list {
3270    int ivar_count;
3271    struct objc_ivar list[count];
3272  };
3273*/
3274llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
3275                                        bool ForClass) {
3276  std::vector<llvm::Constant*> Ivars;
3277
3278  // When emitting the root class GCC emits ivar entries for the
3279  // actual class structure. It is not clear if we need to follow this
3280  // behavior; for now lets try and get away with not doing it. If so,
3281  // the cleanest solution would be to make up an ObjCInterfaceDecl
3282  // for the class.
3283  if (ForClass)
3284    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
3285
3286  const ObjCInterfaceDecl *OID = ID->getClassInterface();
3287
3288  for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
3289       IVD; IVD = IVD->getNextIvar()) {
3290    // Ignore unnamed bit-fields.
3291    if (!IVD->getDeclName())
3292      continue;
3293    llvm::Constant *Ivar[] = {
3294      GetMethodVarName(IVD->getIdentifier()),
3295      GetMethodVarType(IVD),
3296      llvm::ConstantInt::get(ObjCTypes.IntTy,
3297                             ComputeIvarBaseOffset(CGM, OID, IVD))
3298    };
3299    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
3300  }
3301
3302  // Return null for empty list.
3303  if (Ivars.empty())
3304    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
3305
3306  llvm::Constant *Values[2];
3307  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
3308  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
3309                                             Ivars.size());
3310  Values[1] = llvm::ConstantArray::get(AT, Ivars);
3311  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
3312
3313  llvm::GlobalVariable *GV;
3314  if (ForClass)
3315    GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getName(),
3316                           Init, "__OBJC,__class_vars,regular,no_dead_strip",
3317                           4, true);
3318  else
3319    GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getName(),
3320                           Init, "__OBJC,__instance_vars,regular,no_dead_strip",
3321                           4, true);
3322  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
3323}
3324
3325/*
3326  struct objc_method {
3327  SEL method_name;
3328  char *method_types;
3329  void *method;
3330  };
3331
3332  struct objc_method_list {
3333  struct objc_method_list *obsolete;
3334  int count;
3335  struct objc_method methods_list[count];
3336  };
3337*/
3338
3339/// GetMethodConstant - Return a struct objc_method constant for the
3340/// given method if it has been defined. The result is null if the
3341/// method has not been defined. The return value has type MethodPtrTy.
3342llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
3343  llvm::Function *Fn = GetMethodDefinition(MD);
3344  if (!Fn)
3345    return nullptr;
3346
3347  llvm::Constant *Method[] = {
3348    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3349                                   ObjCTypes.SelectorPtrTy),
3350    GetMethodVarType(MD),
3351    llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
3352  };
3353  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3354}
3355
3356llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
3357                                          const char *Section,
3358                                          ArrayRef<llvm::Constant*> Methods) {
3359  // Return null for empty list.
3360  if (Methods.empty())
3361    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
3362
3363  llvm::Constant *Values[3];
3364  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3365  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3366  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3367                                             Methods.size());
3368  Values[2] = llvm::ConstantArray::get(AT, Methods);
3369  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
3370
3371  llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
3372  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
3373}
3374
3375llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
3376                                                const ObjCContainerDecl *CD) {
3377  SmallString<256> Name;
3378  GetNameForMethod(OMD, CD, Name);
3379
3380  CodeGenTypes &Types = CGM.getTypes();
3381  llvm::FunctionType *MethodTy =
3382    Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3383  llvm::Function *Method =
3384    llvm::Function::Create(MethodTy,
3385                           llvm::GlobalValue::InternalLinkage,
3386                           Name.str(),
3387                           &CGM.getModule());
3388  MethodDefinitions.insert(std::make_pair(OMD, Method));
3389
3390  return Method;
3391}
3392
3393llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
3394                                                         llvm::Constant *Init,
3395                                                         StringRef Section,
3396                                                         unsigned Align,
3397                                                         bool AddToUsed) {
3398  llvm::Type *Ty = Init->getType();
3399  llvm::GlobalVariable *GV =
3400    new llvm::GlobalVariable(CGM.getModule(), Ty, false,
3401                             llvm::GlobalValue::PrivateLinkage, Init, Name);
3402  assertPrivateName(GV);
3403  if (!Section.empty())
3404    GV->setSection(Section);
3405  if (Align)
3406    GV->setAlignment(Align);
3407  if (AddToUsed)
3408    CGM.addCompilerUsedGlobal(GV);
3409  return GV;
3410}
3411
3412llvm::Function *CGObjCMac::ModuleInitFunction() {
3413  // Abuse this interface function as a place to finalize.
3414  FinishModule();
3415  return nullptr;
3416}
3417
3418llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
3419  return ObjCTypes.getGetPropertyFn();
3420}
3421
3422llvm::Constant *CGObjCMac::GetPropertySetFunction() {
3423  return ObjCTypes.getSetPropertyFn();
3424}
3425
3426llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
3427                                                           bool copy) {
3428  return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
3429}
3430
3431llvm::Constant *CGObjCMac::GetGetStructFunction() {
3432  return ObjCTypes.getCopyStructFn();
3433}
3434llvm::Constant *CGObjCMac::GetSetStructFunction() {
3435  return ObjCTypes.getCopyStructFn();
3436}
3437
3438llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
3439  return ObjCTypes.getCppAtomicObjectFunction();
3440}
3441llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
3442  return ObjCTypes.getCppAtomicObjectFunction();
3443}
3444
3445llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
3446  return ObjCTypes.getEnumerationMutationFn();
3447}
3448
3449void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
3450  return EmitTryOrSynchronizedStmt(CGF, S);
3451}
3452
3453void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
3454                                     const ObjCAtSynchronizedStmt &S) {
3455  return EmitTryOrSynchronizedStmt(CGF, S);
3456}
3457
3458namespace {
3459  struct PerformFragileFinally : EHScopeStack::Cleanup {
3460    const Stmt &S;
3461    llvm::Value *SyncArgSlot;
3462    llvm::Value *CallTryExitVar;
3463    llvm::Value *ExceptionData;
3464    ObjCTypesHelper &ObjCTypes;
3465    PerformFragileFinally(const Stmt *S,
3466                          llvm::Value *SyncArgSlot,
3467                          llvm::Value *CallTryExitVar,
3468                          llvm::Value *ExceptionData,
3469                          ObjCTypesHelper *ObjCTypes)
3470      : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
3471        ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
3472
3473    void Emit(CodeGenFunction &CGF, Flags flags) override {
3474      // Check whether we need to call objc_exception_try_exit.
3475      // In optimized code, this branch will always be folded.
3476      llvm::BasicBlock *FinallyCallExit =
3477        CGF.createBasicBlock("finally.call_exit");
3478      llvm::BasicBlock *FinallyNoCallExit =
3479        CGF.createBasicBlock("finally.no_call_exit");
3480      CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
3481                               FinallyCallExit, FinallyNoCallExit);
3482
3483      CGF.EmitBlock(FinallyCallExit);
3484      CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
3485                                  ExceptionData);
3486
3487      CGF.EmitBlock(FinallyNoCallExit);
3488
3489      if (isa<ObjCAtTryStmt>(S)) {
3490        if (const ObjCAtFinallyStmt* FinallyStmt =
3491              cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
3492          // Don't try to do the @finally if this is an EH cleanup.
3493          if (flags.isForEHCleanup()) return;
3494
3495          // Save the current cleanup destination in case there's
3496          // control flow inside the finally statement.
3497          llvm::Value *CurCleanupDest =
3498            CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
3499
3500          CGF.EmitStmt(FinallyStmt->getFinallyBody());
3501
3502          if (CGF.HaveInsertPoint()) {
3503            CGF.Builder.CreateStore(CurCleanupDest,
3504                                    CGF.getNormalCleanupDestSlot());
3505          } else {
3506            // Currently, the end of the cleanup must always exist.
3507            CGF.EnsureInsertPoint();
3508          }
3509        }
3510      } else {
3511        // Emit objc_sync_exit(expr); as finally's sole statement for
3512        // @synchronized.
3513        llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
3514        CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
3515      }
3516    }
3517  };
3518
3519  class FragileHazards {
3520    CodeGenFunction &CGF;
3521    SmallVector<llvm::Value*, 20> Locals;
3522    llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
3523
3524    llvm::InlineAsm *ReadHazard;
3525    llvm::InlineAsm *WriteHazard;
3526
3527    llvm::FunctionType *GetAsmFnType();
3528
3529    void collectLocals();
3530    void emitReadHazard(CGBuilderTy &Builder);
3531
3532  public:
3533    FragileHazards(CodeGenFunction &CGF);
3534
3535    void emitWriteHazard();
3536    void emitHazardsInNewBlocks();
3537  };
3538}
3539
3540/// Create the fragile-ABI read and write hazards based on the current
3541/// state of the function, which is presumed to be immediately prior
3542/// to a @try block.  These hazards are used to maintain correct
3543/// semantics in the face of optimization and the fragile ABI's
3544/// cavalier use of setjmp/longjmp.
3545FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
3546  collectLocals();
3547
3548  if (Locals.empty()) return;
3549
3550  // Collect all the blocks in the function.
3551  for (llvm::Function::iterator
3552         I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
3553    BlocksBeforeTry.insert(&*I);
3554
3555  llvm::FunctionType *AsmFnTy = GetAsmFnType();
3556
3557  // Create a read hazard for the allocas.  This inhibits dead-store
3558  // optimizations and forces the values to memory.  This hazard is
3559  // inserted before any 'throwing' calls in the protected scope to
3560  // reflect the possibility that the variables might be read from the
3561  // catch block if the call throws.
3562  {
3563    std::string Constraint;
3564    for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3565      if (I) Constraint += ',';
3566      Constraint += "*m";
3567    }
3568
3569    ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3570  }
3571
3572  // Create a write hazard for the allocas.  This inhibits folding
3573  // loads across the hazard.  This hazard is inserted at the
3574  // beginning of the catch path to reflect the possibility that the
3575  // variables might have been written within the protected scope.
3576  {
3577    std::string Constraint;
3578    for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
3579      if (I) Constraint += ',';
3580      Constraint += "=*m";
3581    }
3582
3583    WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
3584  }
3585}
3586
3587/// Emit a write hazard at the current location.
3588void FragileHazards::emitWriteHazard() {
3589  if (Locals.empty()) return;
3590
3591  CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
3592}
3593
3594void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
3595  assert(!Locals.empty());
3596  llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
3597  call->setDoesNotThrow();
3598  call->setCallingConv(CGF.getRuntimeCC());
3599}
3600
3601/// Emit read hazards in all the protected blocks, i.e. all the blocks
3602/// which have been inserted since the beginning of the try.
3603void FragileHazards::emitHazardsInNewBlocks() {
3604  if (Locals.empty()) return;
3605
3606  CGBuilderTy Builder(CGF.getLLVMContext());
3607
3608  // Iterate through all blocks, skipping those prior to the try.
3609  for (llvm::Function::iterator
3610         FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
3611    llvm::BasicBlock &BB = *FI;
3612    if (BlocksBeforeTry.count(&BB)) continue;
3613
3614    // Walk through all the calls in the block.
3615    for (llvm::BasicBlock::iterator
3616           BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
3617      llvm::Instruction &I = *BI;
3618
3619      // Ignore instructions that aren't non-intrinsic calls.
3620      // These are the only calls that can possibly call longjmp.
3621      if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
3622      if (isa<llvm::IntrinsicInst>(I))
3623        continue;
3624
3625      // Ignore call sites marked nounwind.  This may be questionable,
3626      // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
3627      llvm::CallSite CS(&I);
3628      if (CS.doesNotThrow()) continue;
3629
3630      // Insert a read hazard before the call.  This will ensure that
3631      // any writes to the locals are performed before making the
3632      // call.  If the call throws, then this is sufficient to
3633      // guarantee correctness as long as it doesn't also write to any
3634      // locals.
3635      Builder.SetInsertPoint(&BB, BI);
3636      emitReadHazard(Builder);
3637    }
3638  }
3639}
3640
3641static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
3642  if (V) S.insert(V);
3643}
3644
3645void FragileHazards::collectLocals() {
3646  // Compute a set of allocas to ignore.
3647  llvm::DenseSet<llvm::Value*> AllocasToIgnore;
3648  addIfPresent(AllocasToIgnore, CGF.ReturnValue);
3649  addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
3650
3651  // Collect all the allocas currently in the function.  This is
3652  // probably way too aggressive.
3653  llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
3654  for (llvm::BasicBlock::iterator
3655         I = Entry.begin(), E = Entry.end(); I != E; ++I)
3656    if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
3657      Locals.push_back(&*I);
3658}
3659
3660llvm::FunctionType *FragileHazards::GetAsmFnType() {
3661  SmallVector<llvm::Type *, 16> tys(Locals.size());
3662  for (unsigned i = 0, e = Locals.size(); i != e; ++i)
3663    tys[i] = Locals[i]->getType();
3664  return llvm::FunctionType::get(CGF.VoidTy, tys, false);
3665}
3666
3667/*
3668
3669  Objective-C setjmp-longjmp (sjlj) Exception Handling
3670  --
3671
3672  A catch buffer is a setjmp buffer plus:
3673    - a pointer to the exception that was caught
3674    - a pointer to the previous exception data buffer
3675    - two pointers of reserved storage
3676  Therefore catch buffers form a stack, with a pointer to the top
3677  of the stack kept in thread-local storage.
3678
3679  objc_exception_try_enter pushes a catch buffer onto the EH stack.
3680  objc_exception_try_exit pops the given catch buffer, which is
3681    required to be the top of the EH stack.
3682  objc_exception_throw pops the top of the EH stack, writes the
3683    thrown exception into the appropriate field, and longjmps
3684    to the setjmp buffer.  It crashes the process (with a printf
3685    and an abort()) if there are no catch buffers on the stack.
3686  objc_exception_extract just reads the exception pointer out of the
3687    catch buffer.
3688
3689  There's no reason an implementation couldn't use a light-weight
3690  setjmp here --- something like __builtin_setjmp, but API-compatible
3691  with the heavyweight setjmp.  This will be more important if we ever
3692  want to implement correct ObjC/C++ exception interactions for the
3693  fragile ABI.
3694
3695  Note that for this use of setjmp/longjmp to be correct, we may need
3696  to mark some local variables volatile: if a non-volatile local
3697  variable is modified between the setjmp and the longjmp, it has
3698  indeterminate value.  For the purposes of LLVM IR, it may be
3699  sufficient to make loads and stores within the @try (to variables
3700  declared outside the @try) volatile.  This is necessary for
3701  optimized correctness, but is not currently being done; this is
3702  being tracked as rdar://problem/8160285
3703
3704  The basic framework for a @try-catch-finally is as follows:
3705  {
3706  objc_exception_data d;
3707  id _rethrow = null;
3708  bool _call_try_exit = true;
3709
3710  objc_exception_try_enter(&d);
3711  if (!setjmp(d.jmp_buf)) {
3712  ... try body ...
3713  } else {
3714  // exception path
3715  id _caught = objc_exception_extract(&d);
3716
3717  // enter new try scope for handlers
3718  if (!setjmp(d.jmp_buf)) {
3719  ... match exception and execute catch blocks ...
3720
3721  // fell off end, rethrow.
3722  _rethrow = _caught;
3723  ... jump-through-finally to finally_rethrow ...
3724  } else {
3725  // exception in catch block
3726  _rethrow = objc_exception_extract(&d);
3727  _call_try_exit = false;
3728  ... jump-through-finally to finally_rethrow ...
3729  }
3730  }
3731  ... jump-through-finally to finally_end ...
3732
3733  finally:
3734  if (_call_try_exit)
3735  objc_exception_try_exit(&d);
3736
3737  ... finally block ....
3738  ... dispatch to finally destination ...
3739
3740  finally_rethrow:
3741  objc_exception_throw(_rethrow);
3742
3743  finally_end:
3744  }
3745
3746  This framework differs slightly from the one gcc uses, in that gcc
3747  uses _rethrow to determine if objc_exception_try_exit should be called
3748  and if the object should be rethrown. This breaks in the face of
3749  throwing nil and introduces unnecessary branches.
3750
3751  We specialize this framework for a few particular circumstances:
3752
3753  - If there are no catch blocks, then we avoid emitting the second
3754  exception handling context.
3755
3756  - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
3757  e)) we avoid emitting the code to rethrow an uncaught exception.
3758
3759  - FIXME: If there is no @finally block we can do a few more
3760  simplifications.
3761
3762  Rethrows and Jumps-Through-Finally
3763  --
3764
3765  '@throw;' is supported by pushing the currently-caught exception
3766  onto ObjCEHStack while the @catch blocks are emitted.
3767
3768  Branches through the @finally block are handled with an ordinary
3769  normal cleanup.  We do not register an EH cleanup; fragile-ABI ObjC
3770  exceptions are not compatible with C++ exceptions, and this is
3771  hardly the only place where this will go wrong.
3772
3773  @synchronized(expr) { stmt; } is emitted as if it were:
3774    id synch_value = expr;
3775    objc_sync_enter(synch_value);
3776    @try { stmt; } @finally { objc_sync_exit(synch_value); }
3777*/
3778
3779void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
3780                                          const Stmt &S) {
3781  bool isTry = isa<ObjCAtTryStmt>(S);
3782
3783  // A destination for the fall-through edges of the catch handlers to
3784  // jump to.
3785  CodeGenFunction::JumpDest FinallyEnd =
3786    CGF.getJumpDestInCurrentScope("finally.end");
3787
3788  // A destination for the rethrow edge of the catch handlers to jump
3789  // to.
3790  CodeGenFunction::JumpDest FinallyRethrow =
3791    CGF.getJumpDestInCurrentScope("finally.rethrow");
3792
3793  // For @synchronized, call objc_sync_enter(sync.expr). The
3794  // evaluation of the expression must occur before we enter the
3795  // @synchronized.  We can't avoid a temp here because we need the
3796  // value to be preserved.  If the backend ever does liveness
3797  // correctly after setjmp, this will be unnecessary.
3798  llvm::Value *SyncArgSlot = nullptr;
3799  if (!isTry) {
3800    llvm::Value *SyncArg =
3801      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
3802    SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
3803    CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
3804
3805    SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
3806    CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
3807  }
3808
3809  // Allocate memory for the setjmp buffer.  This needs to be kept
3810  // live throughout the try and catch blocks.
3811  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
3812                                                    "exceptiondata.ptr");
3813
3814  // Create the fragile hazards.  Note that this will not capture any
3815  // of the allocas required for exception processing, but will
3816  // capture the current basic block (which extends all the way to the
3817  // setjmp call) as "before the @try".
3818  FragileHazards Hazards(CGF);
3819
3820  // Create a flag indicating whether the cleanup needs to call
3821  // objc_exception_try_exit.  This is true except when
3822  //   - no catches match and we're branching through the cleanup
3823  //     just to rethrow the exception, or
3824  //   - a catch matched and we're falling out of the catch handler.
3825  // The setjmp-safety rule here is that we should always store to this
3826  // variable in a place that dominates the branch through the cleanup
3827  // without passing through any setjmps.
3828  llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
3829                                                     "_call_try_exit");
3830
3831  // A slot containing the exception to rethrow.  Only needed when we
3832  // have both a @catch and a @finally.
3833  llvm::Value *PropagatingExnVar = nullptr;
3834
3835  // Push a normal cleanup to leave the try scope.
3836  CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
3837                                                 SyncArgSlot,
3838                                                 CallTryExitVar,
3839                                                 ExceptionData,
3840                                                 &ObjCTypes);
3841
3842  // Enter a try block:
3843  //  - Call objc_exception_try_enter to push ExceptionData on top of
3844  //    the EH stack.
3845  CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
3846
3847  //  - Call setjmp on the exception data buffer.
3848  llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
3849  llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
3850  llvm::Value *SetJmpBuffer =
3851    CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
3852  llvm::CallInst *SetJmpResult =
3853    CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
3854  SetJmpResult->setCanReturnTwice();
3855
3856  // If setjmp returned 0, enter the protected block; otherwise,
3857  // branch to the handler.
3858  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
3859  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
3860  llvm::Value *DidCatch =
3861    CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
3862  CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
3863
3864  // Emit the protected block.
3865  CGF.EmitBlock(TryBlock);
3866  CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
3867  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
3868                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
3869
3870  CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
3871
3872  // Emit the exception handler block.
3873  CGF.EmitBlock(TryHandler);
3874
3875  // Don't optimize loads of the in-scope locals across this point.
3876  Hazards.emitWriteHazard();
3877
3878  // For a @synchronized (or a @try with no catches), just branch
3879  // through the cleanup to the rethrow block.
3880  if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
3881    // Tell the cleanup not to re-pop the exit.
3882    CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
3883    CGF.EmitBranchThroughCleanup(FinallyRethrow);
3884
3885  // Otherwise, we have to match against the caught exceptions.
3886  } else {
3887    // Retrieve the exception object.  We may emit multiple blocks but
3888    // nothing can cross this so the value is already in SSA form.
3889    llvm::CallInst *Caught =
3890      CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
3891                                  ExceptionData, "caught");
3892
3893    // Push the exception to rethrow onto the EH value stack for the
3894    // benefit of any @throws in the handlers.
3895    CGF.ObjCEHValueStack.push_back(Caught);
3896
3897    const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
3898
3899    bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
3900
3901    llvm::BasicBlock *CatchBlock = nullptr;
3902    llvm::BasicBlock *CatchHandler = nullptr;
3903    if (HasFinally) {
3904      // Save the currently-propagating exception before
3905      // objc_exception_try_enter clears the exception slot.
3906      PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
3907                                               "propagating_exception");
3908      CGF.Builder.CreateStore(Caught, PropagatingExnVar);
3909
3910      // Enter a new exception try block (in case a @catch block
3911      // throws an exception).
3912      CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
3913                                  ExceptionData);
3914
3915      llvm::CallInst *SetJmpResult =
3916        CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
3917                                    SetJmpBuffer, "setjmp.result");
3918      SetJmpResult->setCanReturnTwice();
3919
3920      llvm::Value *Threw =
3921        CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
3922
3923      CatchBlock = CGF.createBasicBlock("catch");
3924      CatchHandler = CGF.createBasicBlock("catch_for_catch");
3925      CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
3926
3927      CGF.EmitBlock(CatchBlock);
3928    }
3929
3930    CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
3931
3932    // Handle catch list. As a special case we check if everything is
3933    // matched and avoid generating code for falling off the end if
3934    // so.
3935    bool AllMatched = false;
3936    for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
3937      const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
3938
3939      const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
3940      const ObjCObjectPointerType *OPT = nullptr;
3941
3942      // catch(...) always matches.
3943      if (!CatchParam) {
3944        AllMatched = true;
3945      } else {
3946        OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
3947
3948        // catch(id e) always matches under this ABI, since only
3949        // ObjC exceptions end up here in the first place.
3950        // FIXME: For the time being we also match id<X>; this should
3951        // be rejected by Sema instead.
3952        if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
3953          AllMatched = true;
3954      }
3955
3956      // If this is a catch-all, we don't need to test anything.
3957      if (AllMatched) {
3958        CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
3959
3960        if (CatchParam) {
3961          CGF.EmitAutoVarDecl(*CatchParam);
3962          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
3963
3964          // These types work out because ConvertType(id) == i8*.
3965          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
3966        }
3967
3968        CGF.EmitStmt(CatchStmt->getCatchBody());
3969
3970        // The scope of the catch variable ends right here.
3971        CatchVarCleanups.ForceCleanup();
3972
3973        CGF.EmitBranchThroughCleanup(FinallyEnd);
3974        break;
3975      }
3976
3977      assert(OPT && "Unexpected non-object pointer type in @catch");
3978      const ObjCObjectType *ObjTy = OPT->getObjectType();
3979
3980      // FIXME: @catch (Class c) ?
3981      ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
3982      assert(IDecl && "Catch parameter must have Objective-C type!");
3983
3984      // Check if the @catch block matches the exception object.
3985      llvm::Value *Class = EmitClassRef(CGF, IDecl);
3986
3987      llvm::Value *matchArgs[] = { Class, Caught };
3988      llvm::CallInst *Match =
3989        CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
3990                                    matchArgs, "match");
3991
3992      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
3993      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
3994
3995      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
3996                               MatchedBlock, NextCatchBlock);
3997
3998      // Emit the @catch block.
3999      CGF.EmitBlock(MatchedBlock);
4000
4001      // Collect any cleanups for the catch variable.  The scope lasts until
4002      // the end of the catch body.
4003      CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
4004
4005      CGF.EmitAutoVarDecl(*CatchParam);
4006      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
4007
4008      // Initialize the catch variable.
4009      llvm::Value *Tmp =
4010        CGF.Builder.CreateBitCast(Caught,
4011                                  CGF.ConvertType(CatchParam->getType()));
4012      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
4013
4014      CGF.EmitStmt(CatchStmt->getCatchBody());
4015
4016      // We're done with the catch variable.
4017      CatchVarCleanups.ForceCleanup();
4018
4019      CGF.EmitBranchThroughCleanup(FinallyEnd);
4020
4021      CGF.EmitBlock(NextCatchBlock);
4022    }
4023
4024    CGF.ObjCEHValueStack.pop_back();
4025
4026    // If nothing wanted anything to do with the caught exception,
4027    // kill the extract call.
4028    if (Caught->use_empty())
4029      Caught->eraseFromParent();
4030
4031    if (!AllMatched)
4032      CGF.EmitBranchThroughCleanup(FinallyRethrow);
4033
4034    if (HasFinally) {
4035      // Emit the exception handler for the @catch blocks.
4036      CGF.EmitBlock(CatchHandler);
4037
4038      // In theory we might now need a write hazard, but actually it's
4039      // unnecessary because there's no local-accessing code between
4040      // the try's write hazard and here.
4041      //Hazards.emitWriteHazard();
4042
4043      // Extract the new exception and save it to the
4044      // propagating-exception slot.
4045      assert(PropagatingExnVar);
4046      llvm::CallInst *NewCaught =
4047        CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
4048                                    ExceptionData, "caught");
4049      CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
4050
4051      // Don't pop the catch handler; the throw already did.
4052      CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
4053      CGF.EmitBranchThroughCleanup(FinallyRethrow);
4054    }
4055  }
4056
4057  // Insert read hazards as required in the new blocks.
4058  Hazards.emitHazardsInNewBlocks();
4059
4060  // Pop the cleanup.
4061  CGF.Builder.restoreIP(TryFallthroughIP);
4062  if (CGF.HaveInsertPoint())
4063    CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
4064  CGF.PopCleanupBlock();
4065  CGF.EmitBlock(FinallyEnd.getBlock(), true);
4066
4067  // Emit the rethrow block.
4068  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
4069  CGF.EmitBlock(FinallyRethrow.getBlock(), true);
4070  if (CGF.HaveInsertPoint()) {
4071    // If we have a propagating-exception variable, check it.
4072    llvm::Value *PropagatingExn;
4073    if (PropagatingExnVar) {
4074      PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
4075
4076    // Otherwise, just look in the buffer for the exception to throw.
4077    } else {
4078      llvm::CallInst *Caught =
4079        CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
4080                                    ExceptionData);
4081      PropagatingExn = Caught;
4082    }
4083
4084    CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
4085                                PropagatingExn);
4086    CGF.Builder.CreateUnreachable();
4087  }
4088
4089  CGF.Builder.restoreIP(SavedIP);
4090}
4091
4092void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
4093                              const ObjCAtThrowStmt &S,
4094                              bool ClearInsertionPoint) {
4095  llvm::Value *ExceptionAsObject;
4096
4097  if (const Expr *ThrowExpr = S.getThrowExpr()) {
4098    llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4099    ExceptionAsObject =
4100      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
4101  } else {
4102    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4103           "Unexpected rethrow outside @catch block.");
4104    ExceptionAsObject = CGF.ObjCEHValueStack.back();
4105  }
4106
4107  CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
4108    ->setDoesNotReturn();
4109  CGF.Builder.CreateUnreachable();
4110
4111  // Clear the insertion point to indicate we are in unreachable code.
4112  if (ClearInsertionPoint)
4113    CGF.Builder.ClearInsertionPoint();
4114}
4115
4116/// EmitObjCWeakRead - Code gen for loading value of a __weak
4117/// object: objc_read_weak (id *src)
4118///
4119llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
4120                                          llvm::Value *AddrWeakObj) {
4121  llvm::Type* DestTy =
4122    cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
4123  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
4124                                          ObjCTypes.PtrObjectPtrTy);
4125  llvm::Value *read_weak =
4126    CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
4127                                AddrWeakObj, "weakread");
4128  read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
4129  return read_weak;
4130}
4131
4132/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4133/// objc_assign_weak (id src, id *dst)
4134///
4135void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4136                                   llvm::Value *src, llvm::Value *dst) {
4137  llvm::Type * SrcTy = src->getType();
4138  if (!isa<llvm::PointerType>(SrcTy)) {
4139    unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4140    assert(Size <= 8 && "does not support size > 8");
4141    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
4142      : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
4143    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4144  }
4145  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4146  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4147  llvm::Value *args[] = { src, dst };
4148  CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
4149                              args, "weakassign");
4150  return;
4151}
4152
4153/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4154/// objc_assign_global (id src, id *dst)
4155///
4156void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4157                                     llvm::Value *src, llvm::Value *dst,
4158                                     bool threadlocal) {
4159  llvm::Type * SrcTy = src->getType();
4160  if (!isa<llvm::PointerType>(SrcTy)) {
4161    unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4162    assert(Size <= 8 && "does not support size > 8");
4163    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
4164      : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
4165    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4166  }
4167  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4168  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4169  llvm::Value *args[] = { src, dst };
4170  if (!threadlocal)
4171    CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
4172                                args, "globalassign");
4173  else
4174    CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
4175                                args, "threadlocalassign");
4176  return;
4177}
4178
4179/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4180/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
4181///
4182void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4183                                   llvm::Value *src, llvm::Value *dst,
4184                                   llvm::Value *ivarOffset) {
4185  assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
4186  llvm::Type * SrcTy = src->getType();
4187  if (!isa<llvm::PointerType>(SrcTy)) {
4188    unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4189    assert(Size <= 8 && "does not support size > 8");
4190    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
4191      : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
4192    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4193  }
4194  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4195  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4196  llvm::Value *args[] = { src, dst, ivarOffset };
4197  CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
4198  return;
4199}
4200
4201/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4202/// objc_assign_strongCast (id src, id *dst)
4203///
4204void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
4205                                         llvm::Value *src, llvm::Value *dst) {
4206  llvm::Type * SrcTy = src->getType();
4207  if (!isa<llvm::PointerType>(SrcTy)) {
4208    unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4209    assert(Size <= 8 && "does not support size > 8");
4210    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
4211      : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
4212    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
4213  }
4214  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4215  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4216  llvm::Value *args[] = { src, dst };
4217  CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
4218                              args, "weakassign");
4219  return;
4220}
4221
4222void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
4223                                         llvm::Value *DestPtr,
4224                                         llvm::Value *SrcPtr,
4225                                         llvm::Value *size) {
4226  SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
4227  DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
4228  llvm::Value *args[] = { DestPtr, SrcPtr, size };
4229  CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
4230}
4231
4232/// EmitObjCValueForIvar - Code Gen for ivar reference.
4233///
4234LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
4235                                       QualType ObjectTy,
4236                                       llvm::Value *BaseValue,
4237                                       const ObjCIvarDecl *Ivar,
4238                                       unsigned CVRQualifiers) {
4239  const ObjCInterfaceDecl *ID =
4240    ObjectTy->getAs<ObjCObjectType>()->getInterface();
4241  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4242                                  EmitIvarOffset(CGF, ID, Ivar));
4243}
4244
4245llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
4246                                       const ObjCInterfaceDecl *Interface,
4247                                       const ObjCIvarDecl *Ivar) {
4248  uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
4249  return llvm::ConstantInt::get(
4250    CGM.getTypes().ConvertType(CGM.getContext().LongTy),
4251    Offset);
4252}
4253
4254/* *** Private Interface *** */
4255
4256/// EmitImageInfo - Emit the image info marker used to encode some module
4257/// level information.
4258///
4259/// See: <rdr://4810609&4810587&4810587>
4260/// struct IMAGE_INFO {
4261///   unsigned version;
4262///   unsigned flags;
4263/// };
4264enum ImageInfoFlags {
4265  eImageInfo_FixAndContinue      = (1 << 0), // This flag is no longer set by clang.
4266  eImageInfo_GarbageCollected    = (1 << 1),
4267  eImageInfo_GCOnly              = (1 << 2),
4268  eImageInfo_OptimizedByDyld     = (1 << 3), // This flag is set by the dyld shared cache.
4269
4270  // A flag indicating that the module has no instances of a @synthesize of a
4271  // superclass variable. <rdar://problem/6803242>
4272  eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
4273  eImageInfo_ImageIsSimulated    = (1 << 5)
4274};
4275
4276void CGObjCCommonMac::EmitImageInfo() {
4277  unsigned version = 0; // Version is unused?
4278  const char *Section = (ObjCABI == 1) ?
4279    "__OBJC, __image_info,regular" :
4280    "__DATA, __objc_imageinfo, regular, no_dead_strip";
4281
4282  // Generate module-level named metadata to convey this information to the
4283  // linker and code-gen.
4284  llvm::Module &Mod = CGM.getModule();
4285
4286  // Add the ObjC ABI version to the module flags.
4287  Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
4288  Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
4289                    version);
4290  Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
4291                    llvm::MDString::get(VMContext,Section));
4292
4293  if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
4294    // Non-GC overrides those files which specify GC.
4295    Mod.addModuleFlag(llvm::Module::Override,
4296                      "Objective-C Garbage Collection", (uint32_t)0);
4297  } else {
4298    // Add the ObjC garbage collection value.
4299    Mod.addModuleFlag(llvm::Module::Error,
4300                      "Objective-C Garbage Collection",
4301                      eImageInfo_GarbageCollected);
4302
4303    if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
4304      // Add the ObjC GC Only value.
4305      Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
4306                        eImageInfo_GCOnly);
4307
4308      // Require that GC be specified and set to eImageInfo_GarbageCollected.
4309      llvm::Value *Ops[2] = {
4310        llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
4311        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
4312                               eImageInfo_GarbageCollected)
4313      };
4314      Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
4315                        llvm::MDNode::get(VMContext, Ops));
4316    }
4317  }
4318
4319  // Indicate whether we're compiling this to run on a simulator.
4320  const llvm::Triple &Triple = CGM.getTarget().getTriple();
4321  if (Triple.isiOS() &&
4322      (Triple.getArch() == llvm::Triple::x86 ||
4323       Triple.getArch() == llvm::Triple::x86_64))
4324    Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
4325                      eImageInfo_ImageIsSimulated);
4326}
4327
4328// struct objc_module {
4329//   unsigned long version;
4330//   unsigned long size;
4331//   const char *name;
4332//   Symtab symtab;
4333// };
4334
4335// FIXME: Get from somewhere
4336static const int ModuleVersion = 7;
4337
4338void CGObjCMac::EmitModuleInfo() {
4339  uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
4340
4341  llvm::Constant *Values[] = {
4342    llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
4343    llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
4344    // This used to be the filename, now it is unused. <rdr://4327263>
4345    GetClassName(&CGM.getContext().Idents.get("")),
4346    EmitModuleSymbols()
4347  };
4348  CreateMetadataVar("\01L_OBJC_MODULES",
4349                    llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
4350                    "__OBJC,__module_info,regular,no_dead_strip",
4351                    4, true);
4352}
4353
4354llvm::Constant *CGObjCMac::EmitModuleSymbols() {
4355  unsigned NumClasses = DefinedClasses.size();
4356  unsigned NumCategories = DefinedCategories.size();
4357
4358  // Return null if no symbols were defined.
4359  if (!NumClasses && !NumCategories)
4360    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
4361
4362  llvm::Constant *Values[5];
4363  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
4364  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
4365  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
4366  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
4367
4368  // The runtime expects exactly the list of defined classes followed
4369  // by the list of defined categories, in a single array.
4370  SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
4371  for (unsigned i=0; i<NumClasses; i++) {
4372    const ObjCInterfaceDecl *ID = ImplementedClasses[i];
4373    assert(ID);
4374    if (ObjCImplementationDecl *IMP = ID->getImplementation())
4375      // We are implementing a weak imported interface. Give it external linkage
4376      if (ID->isWeakImported() && !IMP->isWeakImported())
4377        DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
4378
4379    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4380                                                ObjCTypes.Int8PtrTy);
4381  }
4382  for (unsigned i=0; i<NumCategories; i++)
4383    Symbols[NumClasses + i] =
4384      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4385                                     ObjCTypes.Int8PtrTy);
4386
4387  Values[4] =
4388    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4389                                                  Symbols.size()),
4390                             Symbols);
4391
4392  llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
4393
4394  llvm::GlobalVariable *GV =
4395    CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
4396                      "__OBJC,__symbols,regular,no_dead_strip",
4397                      4, true);
4398  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
4399}
4400
4401llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
4402                                           IdentifierInfo *II) {
4403  LazySymbols.insert(II);
4404
4405  llvm::GlobalVariable *&Entry = ClassReferences[II];
4406
4407  if (!Entry) {
4408    llvm::Constant *Casted =
4409    llvm::ConstantExpr::getBitCast(GetClassName(II),
4410                                   ObjCTypes.ClassPtrTy);
4411    Entry =
4412    CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
4413                      "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
4414                      4, true);
4415  }
4416
4417  return CGF.Builder.CreateLoad(Entry);
4418}
4419
4420llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
4421                                     const ObjCInterfaceDecl *ID) {
4422  return EmitClassRefFromId(CGF, ID->getIdentifier());
4423}
4424
4425llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
4426  IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
4427  return EmitClassRefFromId(CGF, II);
4428}
4429
4430llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel,
4431                                     bool lvalue) {
4432  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4433
4434  if (!Entry) {
4435    llvm::Constant *Casted =
4436      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4437                                     ObjCTypes.SelectorPtrTy);
4438    Entry =
4439      CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
4440                        "__OBJC,__message_refs,literal_pointers,no_dead_strip",
4441                        4, true);
4442    Entry->setExternallyInitialized(true);
4443  }
4444
4445  if (lvalue)
4446    return Entry;
4447  return CGF.Builder.CreateLoad(Entry);
4448}
4449
4450llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
4451  llvm::GlobalVariable *&Entry = ClassNames[Ident];
4452
4453  if (!Entry)
4454    Entry = CreateMetadataVar(
4455        "\01L_OBJC_CLASS_NAME_",
4456        llvm::ConstantDataArray::getString(VMContext, Ident->getName()),
4457        ((ObjCABI == 2) ? "__TEXT,__objc_classname,cstring_literals"
4458                        : "__TEXT,__cstring,cstring_literals"),
4459        1, true);
4460
4461  return getConstantGEP(VMContext, Entry, 0, 0);
4462}
4463
4464llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
4465  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
4466      I = MethodDefinitions.find(MD);
4467  if (I != MethodDefinitions.end())
4468    return I->second;
4469
4470  return nullptr;
4471}
4472
4473/// GetIvarLayoutName - Returns a unique constant for the given
4474/// ivar layout bitmap.
4475llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
4476                                       const ObjCCommonTypesHelper &ObjCTypes) {
4477  return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4478}
4479
4480void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
4481                                                unsigned int BytePos,
4482                                                bool ForStrongLayout,
4483                                                bool &HasUnion) {
4484  const RecordDecl *RD = RT->getDecl();
4485  // FIXME - Use iterator.
4486  SmallVector<const FieldDecl*, 16> Fields(RD->fields());
4487  llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
4488  const llvm::StructLayout *RecLayout =
4489    CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
4490
4491  BuildAggrIvarLayout(nullptr, RecLayout, RD, Fields, BytePos, ForStrongLayout,
4492                      HasUnion);
4493}
4494
4495void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
4496                             const llvm::StructLayout *Layout,
4497                             const RecordDecl *RD,
4498                             ArrayRef<const FieldDecl*> RecFields,
4499                             unsigned int BytePos, bool ForStrongLayout,
4500                             bool &HasUnion) {
4501  bool IsUnion = (RD && RD->isUnion());
4502  uint64_t MaxUnionIvarSize = 0;
4503  uint64_t MaxSkippedUnionIvarSize = 0;
4504  const FieldDecl *MaxField = nullptr;
4505  const FieldDecl *MaxSkippedField = nullptr;
4506  const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
4507  uint64_t MaxFieldOffset = 0;
4508  uint64_t MaxSkippedFieldOffset = 0;
4509  uint64_t LastBitfieldOrUnnamedOffset = 0;
4510  uint64_t FirstFieldDelta = 0;
4511
4512  if (RecFields.empty())
4513    return;
4514  unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
4515  unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
4516  if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
4517    const FieldDecl *FirstField = RecFields[0];
4518    FirstFieldDelta =
4519      ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
4520  }
4521
4522  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
4523    const FieldDecl *Field = RecFields[i];
4524    uint64_t FieldOffset;
4525    if (RD) {
4526      // Note that 'i' here is actually the field index inside RD of Field,
4527      // although this dependency is hidden.
4528      const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
4529      FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
4530    } else
4531      FieldOffset =
4532        ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
4533
4534    // Skip over unnamed or bitfields
4535    if (!Field->getIdentifier() || Field->isBitField()) {
4536      LastFieldBitfieldOrUnnamed = Field;
4537      LastBitfieldOrUnnamedOffset = FieldOffset;
4538      continue;
4539    }
4540
4541    LastFieldBitfieldOrUnnamed = nullptr;
4542    QualType FQT = Field->getType();
4543    if (FQT->isRecordType() || FQT->isUnionType()) {
4544      if (FQT->isUnionType())
4545        HasUnion = true;
4546
4547      BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
4548                                BytePos + FieldOffset,
4549                                ForStrongLayout, HasUnion);
4550      continue;
4551    }
4552
4553    if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
4554      const ConstantArrayType *CArray =
4555        dyn_cast_or_null<ConstantArrayType>(Array);
4556      uint64_t ElCount = CArray->getSize().getZExtValue();
4557      assert(CArray && "only array with known element size is supported");
4558      FQT = CArray->getElementType();
4559      while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
4560        const ConstantArrayType *CArray =
4561          dyn_cast_or_null<ConstantArrayType>(Array);
4562        ElCount *= CArray->getSize().getZExtValue();
4563        FQT = CArray->getElementType();
4564      }
4565      if (FQT->isRecordType() && ElCount) {
4566        int OldIndex = IvarsInfo.size() - 1;
4567        int OldSkIndex = SkipIvars.size() -1;
4568
4569        const RecordType *RT = FQT->getAs<RecordType>();
4570        BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
4571                                  ForStrongLayout, HasUnion);
4572
4573        // Replicate layout information for each array element. Note that
4574        // one element is already done.
4575        uint64_t ElIx = 1;
4576        for (int FirstIndex = IvarsInfo.size() - 1,
4577               FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
4578          uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
4579          for (int i = OldIndex+1; i <= FirstIndex; ++i)
4580            IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
4581                                        IvarsInfo[i].ivar_size));
4582          for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
4583            SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
4584                                        SkipIvars[i].ivar_size));
4585        }
4586        continue;
4587      }
4588    }
4589    // At this point, we are done with Record/Union and array there of.
4590    // For other arrays we are down to its element type.
4591    Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
4592
4593    unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
4594    if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
4595        || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
4596      if (IsUnion) {
4597        uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
4598        if (UnionIvarSize > MaxUnionIvarSize) {
4599          MaxUnionIvarSize = UnionIvarSize;
4600          MaxField = Field;
4601          MaxFieldOffset = FieldOffset;
4602        }
4603      } else {
4604        IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
4605                                    FieldSize / WordSizeInBits));
4606      }
4607    } else if ((ForStrongLayout &&
4608                (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
4609               || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
4610      if (IsUnion) {
4611        // FIXME: Why the asymmetry? We divide by word size in bits on other
4612        // side.
4613        uint64_t UnionIvarSize = FieldSize / ByteSizeInBits;
4614        if (UnionIvarSize > MaxSkippedUnionIvarSize) {
4615          MaxSkippedUnionIvarSize = UnionIvarSize;
4616          MaxSkippedField = Field;
4617          MaxSkippedFieldOffset = FieldOffset;
4618        }
4619      } else {
4620        // FIXME: Why the asymmetry, we divide by byte size in bits here?
4621        SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
4622                                    FieldSize / ByteSizeInBits));
4623      }
4624    }
4625  }
4626
4627  if (LastFieldBitfieldOrUnnamed) {
4628    if (LastFieldBitfieldOrUnnamed->isBitField()) {
4629      // Last field was a bitfield. Must update skip info.
4630      uint64_t BitFieldSize
4631          = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
4632      GC_IVAR skivar;
4633      skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
4634      skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
4635        + ((BitFieldSize % ByteSizeInBits) != 0);
4636      SkipIvars.push_back(skivar);
4637    } else {
4638      assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
4639      // Last field was unnamed. Must update skip info.
4640      unsigned FieldSize
4641          = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
4642      SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
4643                                  FieldSize / ByteSizeInBits));
4644    }
4645  }
4646
4647  if (MaxField)
4648    IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
4649                                MaxUnionIvarSize));
4650  if (MaxSkippedField)
4651    SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
4652                                MaxSkippedUnionIvarSize));
4653}
4654
4655/// BuildIvarLayoutBitmap - This routine is the horsework for doing all
4656/// the computations and returning the layout bitmap (for ivar or blocks) in
4657/// the given argument BitMap string container. Routine reads
4658/// two containers, IvarsInfo and SkipIvars which are assumed to be
4659/// filled already by the caller.
4660llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
4661  unsigned int WordsToScan, WordsToSkip;
4662  llvm::Type *PtrTy = CGM.Int8PtrTy;
4663
4664  // Build the string of skip/scan nibbles
4665  SmallVector<SKIP_SCAN, 32> SkipScanIvars;
4666  unsigned int WordSize =
4667  CGM.getTypes().getDataLayout().getTypeAllocSize(PtrTy);
4668  if (IvarsInfo[0].ivar_bytepos == 0) {
4669    WordsToSkip = 0;
4670    WordsToScan = IvarsInfo[0].ivar_size;
4671  } else {
4672    WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
4673    WordsToScan = IvarsInfo[0].ivar_size;
4674  }
4675  for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
4676    unsigned int TailPrevGCObjC =
4677    IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
4678    if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
4679      // consecutive 'scanned' object pointers.
4680      WordsToScan += IvarsInfo[i].ivar_size;
4681    } else {
4682      // Skip over 'gc'able object pointer which lay over each other.
4683      if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
4684        continue;
4685      // Must skip over 1 or more words. We save current skip/scan values
4686      //  and start a new pair.
4687      SKIP_SCAN SkScan;
4688      SkScan.skip = WordsToSkip;
4689      SkScan.scan = WordsToScan;
4690      SkipScanIvars.push_back(SkScan);
4691
4692      // Skip the hole.
4693      SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
4694      SkScan.scan = 0;
4695      SkipScanIvars.push_back(SkScan);
4696      WordsToSkip = 0;
4697      WordsToScan = IvarsInfo[i].ivar_size;
4698    }
4699  }
4700  if (WordsToScan > 0) {
4701    SKIP_SCAN SkScan;
4702    SkScan.skip = WordsToSkip;
4703    SkScan.scan = WordsToScan;
4704    SkipScanIvars.push_back(SkScan);
4705  }
4706
4707  if (!SkipIvars.empty()) {
4708    unsigned int LastIndex = SkipIvars.size()-1;
4709    int LastByteSkipped =
4710    SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
4711    LastIndex = IvarsInfo.size()-1;
4712    int LastByteScanned =
4713    IvarsInfo[LastIndex].ivar_bytepos +
4714    IvarsInfo[LastIndex].ivar_size * WordSize;
4715    // Compute number of bytes to skip at the tail end of the last ivar scanned.
4716    if (LastByteSkipped > LastByteScanned) {
4717      unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
4718      SKIP_SCAN SkScan;
4719      SkScan.skip = TotalWords - (LastByteScanned/WordSize);
4720      SkScan.scan = 0;
4721      SkipScanIvars.push_back(SkScan);
4722    }
4723  }
4724  // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
4725  // as 0xMN.
4726  int SkipScan = SkipScanIvars.size()-1;
4727  for (int i = 0; i <= SkipScan; i++) {
4728    if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
4729        && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
4730      // 0xM0 followed by 0x0N detected.
4731      SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
4732      for (int j = i+1; j < SkipScan; j++)
4733        SkipScanIvars[j] = SkipScanIvars[j+1];
4734      --SkipScan;
4735    }
4736  }
4737
4738  // Generate the string.
4739  for (int i = 0; i <= SkipScan; i++) {
4740    unsigned char byte;
4741    unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
4742    unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
4743    unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
4744    unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
4745
4746    // first skip big.
4747    for (unsigned int ix = 0; ix < skip_big; ix++)
4748      BitMap += (unsigned char)(0xf0);
4749
4750    // next (skip small, scan)
4751    if (skip_small) {
4752      byte = skip_small << 4;
4753      if (scan_big > 0) {
4754        byte |= 0xf;
4755        --scan_big;
4756      } else if (scan_small) {
4757        byte |= scan_small;
4758        scan_small = 0;
4759      }
4760      BitMap += byte;
4761    }
4762    // next scan big
4763    for (unsigned int ix = 0; ix < scan_big; ix++)
4764      BitMap += (unsigned char)(0x0f);
4765    // last scan small
4766    if (scan_small) {
4767      byte = scan_small;
4768      BitMap += byte;
4769    }
4770  }
4771  // null terminate string.
4772  unsigned char zero = 0;
4773  BitMap += zero;
4774
4775  llvm::GlobalVariable * Entry =
4776  CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
4777                    llvm::ConstantDataArray::getString(VMContext, BitMap,false),
4778                    ((ObjCABI == 2) ?
4779                     "__TEXT,__objc_classname,cstring_literals" :
4780                     "__TEXT,__cstring,cstring_literals"),
4781                    1, true);
4782  return getConstantGEP(VMContext, Entry, 0, 0);
4783}
4784
4785/// BuildIvarLayout - Builds ivar layout bitmap for the class
4786/// implementation for the __strong or __weak case.
4787/// The layout map displays which words in ivar list must be skipped
4788/// and which must be scanned by GC (see below). String is built of bytes.
4789/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
4790/// of words to skip and right nibble is count of words to scan. So, each
4791/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
4792/// represented by a 0x00 byte which also ends the string.
4793/// 1. when ForStrongLayout is true, following ivars are scanned:
4794/// - id, Class
4795/// - object *
4796/// - __strong anything
4797///
4798/// 2. When ForStrongLayout is false, following ivars are scanned:
4799/// - __weak anything
4800///
4801llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
4802  const ObjCImplementationDecl *OMD,
4803  bool ForStrongLayout) {
4804  bool hasUnion = false;
4805
4806  llvm::Type *PtrTy = CGM.Int8PtrTy;
4807  if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
4808      !CGM.getLangOpts().ObjCAutoRefCount)
4809    return llvm::Constant::getNullValue(PtrTy);
4810
4811  const ObjCInterfaceDecl *OI = OMD->getClassInterface();
4812  SmallVector<const FieldDecl*, 32> RecFields;
4813  if (CGM.getLangOpts().ObjCAutoRefCount) {
4814    for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
4815         IVD; IVD = IVD->getNextIvar())
4816      RecFields.push_back(cast<FieldDecl>(IVD));
4817  }
4818  else {
4819    SmallVector<const ObjCIvarDecl*, 32> Ivars;
4820    CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
4821
4822    // FIXME: This is not ideal; we shouldn't have to do this copy.
4823    RecFields.append(Ivars.begin(), Ivars.end());
4824  }
4825
4826  if (RecFields.empty())
4827    return llvm::Constant::getNullValue(PtrTy);
4828
4829  SkipIvars.clear();
4830  IvarsInfo.clear();
4831
4832  BuildAggrIvarLayout(OMD, nullptr, nullptr, RecFields, 0, ForStrongLayout,
4833                      hasUnion);
4834  if (IvarsInfo.empty())
4835    return llvm::Constant::getNullValue(PtrTy);
4836  // Sort on byte position in case we encounterred a union nested in
4837  // the ivar list.
4838  if (hasUnion && !IvarsInfo.empty())
4839    std::sort(IvarsInfo.begin(), IvarsInfo.end());
4840  if (hasUnion && !SkipIvars.empty())
4841    std::sort(SkipIvars.begin(), SkipIvars.end());
4842
4843  std::string BitMap;
4844  llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
4845
4846   if (CGM.getLangOpts().ObjCGCBitmapPrint) {
4847    printf("\n%s ivar layout for class '%s': ",
4848           ForStrongLayout ? "strong" : "weak",
4849           OMD->getClassInterface()->getName().data());
4850    const unsigned char *s = (const unsigned char*)BitMap.c_str();
4851    for (unsigned i = 0, e = BitMap.size(); i < e; i++)
4852      if (!(s[i] & 0xf0))
4853        printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
4854      else
4855        printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
4856    printf("\n");
4857  }
4858  return C;
4859}
4860
4861llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
4862  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
4863
4864  // FIXME: Avoid std::string in "Sel.getAsString()"
4865  if (!Entry)
4866    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
4867               llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
4868                              ((ObjCABI == 2) ?
4869                               "__TEXT,__objc_methname,cstring_literals" :
4870                               "__TEXT,__cstring,cstring_literals"),
4871                              1, true);
4872
4873  return getConstantGEP(VMContext, Entry, 0, 0);
4874}
4875
4876// FIXME: Merge into a single cstring creation function.
4877llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
4878  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
4879}
4880
4881llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
4882  std::string TypeStr;
4883  CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
4884
4885  llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
4886
4887  if (!Entry)
4888    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
4889                         llvm::ConstantDataArray::getString(VMContext, TypeStr),
4890                              ((ObjCABI == 2) ?
4891                               "__TEXT,__objc_methtype,cstring_literals" :
4892                               "__TEXT,__cstring,cstring_literals"),
4893                              1, true);
4894
4895  return getConstantGEP(VMContext, Entry, 0, 0);
4896}
4897
4898llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
4899                                                  bool Extended) {
4900  std::string TypeStr;
4901  if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
4902    return nullptr;
4903
4904  llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
4905
4906  if (!Entry)
4907    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
4908                         llvm::ConstantDataArray::getString(VMContext, TypeStr),
4909                              ((ObjCABI == 2) ?
4910                               "__TEXT,__objc_methtype,cstring_literals" :
4911                               "__TEXT,__cstring,cstring_literals"),
4912                              1, true);
4913
4914  return getConstantGEP(VMContext, Entry, 0, 0);
4915}
4916
4917// FIXME: Merge into a single cstring creation function.
4918llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
4919  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
4920
4921  if (!Entry)
4922    Entry = CreateMetadataVar(
4923        "\01L_OBJC_PROP_NAME_ATTR_",
4924        llvm::ConstantDataArray::getString(VMContext, Ident->getName()),
4925        "__TEXT,__cstring,cstring_literals", 1, true);
4926
4927  return getConstantGEP(VMContext, Entry, 0, 0);
4928}
4929
4930// FIXME: Merge into a single cstring creation function.
4931// FIXME: This Decl should be more precise.
4932llvm::Constant *
4933CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
4934                                       const Decl *Container) {
4935  std::string TypeStr;
4936  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
4937  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
4938}
4939
4940void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
4941                                       const ObjCContainerDecl *CD,
4942                                       SmallVectorImpl<char> &Name) {
4943  llvm::raw_svector_ostream OS(Name);
4944  assert (CD && "Missing container decl in GetNameForMethod");
4945  OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
4946     << '[' << CD->getName();
4947  if (const ObjCCategoryImplDecl *CID =
4948      dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
4949    OS << '(' << *CID << ')';
4950  OS << ' ' << D->getSelector().getAsString() << ']';
4951}
4952
4953void CGObjCMac::FinishModule() {
4954  EmitModuleInfo();
4955
4956  // Emit the dummy bodies for any protocols which were referenced but
4957  // never defined.
4958  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
4959         I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
4960    if (I->second->hasInitializer())
4961      continue;
4962
4963    llvm::Constant *Values[5];
4964    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
4965    Values[1] = GetClassName(I->first);
4966    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
4967    Values[3] = Values[4] =
4968      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
4969    assertPrivateName(I->second);
4970    I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
4971                                                        Values));
4972    CGM.addCompilerUsedGlobal(I->second);
4973  }
4974
4975  // Add assembler directives to add lazy undefined symbol references
4976  // for classes which are referenced but not defined. This is
4977  // important for correct linker interaction.
4978  //
4979  // FIXME: It would be nice if we had an LLVM construct for this.
4980  if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
4981    SmallString<256> Asm;
4982    Asm += CGM.getModule().getModuleInlineAsm();
4983    if (!Asm.empty() && Asm.back() != '\n')
4984      Asm += '\n';
4985
4986    llvm::raw_svector_ostream OS(Asm);
4987    for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
4988           e = DefinedSymbols.end(); I != e; ++I)
4989      OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
4990         << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
4991    for (