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