1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
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 contains code to emit blocks.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGBlocks.h"
14 #include "CGCXXABI.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/CodeGen/ConstantInitBuilder.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ScopedPrinter.h"
29 #include <algorithm>
30 #include <cstdio>
31 
32 using namespace clang;
33 using namespace CodeGen;
34 
35 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
36     : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
37       NoEscape(false), HasCXXObject(false), UsesStret(false),
38       HasCapturedVariableLayout(false), CapturesNonExternalType(false),
39       LocalAddress(Address::invalid()), StructureType(nullptr), Block(block) {
40 
41   // Skip asm prefix, if any.  'name' is usually taken directly from
42   // the mangled name of the enclosing function.
43   if (!name.empty() && name[0] == '\01')
44     name = name.substr(1);
45 }
46 
47 // Anchor the vtable to this translation unit.
48 BlockByrefHelpers::~BlockByrefHelpers() {}
49 
50 /// Build the given block as a global block.
51 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
52                                         const CGBlockInfo &blockInfo,
53                                         llvm::Constant *blockFn);
54 
55 /// Build the helper function to copy a block.
56 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
57                                        const CGBlockInfo &blockInfo) {
58   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
59 }
60 
61 /// Build the helper function to dispose of a block.
62 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
63                                           const CGBlockInfo &blockInfo) {
64   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
65 }
66 
67 namespace {
68 
69 /// Represents a captured entity that requires extra operations in order for
70 /// this entity to be copied or destroyed correctly.
71 struct BlockCaptureManagedEntity {
72   BlockCaptureEntityKind CopyKind, DisposeKind;
73   BlockFieldFlags CopyFlags, DisposeFlags;
74   const BlockDecl::Capture *CI;
75   const CGBlockInfo::Capture *Capture;
76 
77   BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
78                             BlockCaptureEntityKind DisposeType,
79                             BlockFieldFlags CopyFlags,
80                             BlockFieldFlags DisposeFlags,
81                             const BlockDecl::Capture &CI,
82                             const CGBlockInfo::Capture &Capture)
83       : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
84         DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
85 
86   bool operator<(const BlockCaptureManagedEntity &Other) const {
87     return Capture->getOffset() < Other.Capture->getOffset();
88   }
89 };
90 
91 enum class CaptureStrKind {
92   // String for the copy helper.
93   CopyHelper,
94   // String for the dispose helper.
95   DisposeHelper,
96   // Merge the strings for the copy helper and dispose helper.
97   Merged
98 };
99 
100 } // end anonymous namespace
101 
102 static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
103                                       CaptureStrKind StrKind,
104                                       CharUnits BlockAlignment,
105                                       CodeGenModule &CGM);
106 
107 static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
108                                           CodeGenModule &CGM) {
109   std::string Name = "__block_descriptor_";
110   Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
111 
112   if (BlockInfo.NeedsCopyDispose) {
113     if (CGM.getLangOpts().Exceptions)
114       Name += "e";
115     if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
116       Name += "a";
117     Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
118 
119     for (auto &Cap : BlockInfo.SortedCaptures) {
120       if (Cap.isConstantOrTrivial())
121         continue;
122 
123       Name += llvm::to_string(Cap.getOffset().getQuantity());
124 
125       if (Cap.CopyKind == Cap.DisposeKind) {
126         // If CopyKind and DisposeKind are the same, merge the capture
127         // information.
128         assert(Cap.CopyKind != BlockCaptureEntityKind::None &&
129                "shouldn't see BlockCaptureManagedEntity that is None");
130         Name += getBlockCaptureStr(Cap, CaptureStrKind::Merged,
131                                    BlockInfo.BlockAlign, CGM);
132       } else {
133         // If CopyKind and DisposeKind are not the same, which can happen when
134         // either Kind is None or the captured object is a __strong block,
135         // concatenate the copy and dispose strings.
136         Name += getBlockCaptureStr(Cap, CaptureStrKind::CopyHelper,
137                                    BlockInfo.BlockAlign, CGM);
138         Name += getBlockCaptureStr(Cap, CaptureStrKind::DisposeHelper,
139                                    BlockInfo.BlockAlign, CGM);
140       }
141     }
142     Name += "_";
143   }
144 
145   std::string TypeAtEncoding =
146       CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
147   /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
148   /// a separator between symbol name and symbol version.
149   std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
150   Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
151   Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
152   return Name;
153 }
154 
155 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
156 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
157 /// meta-data and contains stationary information about the block literal.
158 /// Its definition will have 4 (or optionally 6) words.
159 /// \code
160 /// struct Block_descriptor {
161 ///   unsigned long reserved;
162 ///   unsigned long size;  // size of Block_literal metadata in bytes.
163 ///   void *copy_func_helper_decl;  // optional copy helper.
164 ///   void *destroy_func_decl; // optional destructor helper.
165 ///   void *block_method_encoding_address; // @encode for block literal signature.
166 ///   void *block_layout_info; // encoding of captured block variables.
167 /// };
168 /// \endcode
169 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
170                                             const CGBlockInfo &blockInfo) {
171   ASTContext &C = CGM.getContext();
172 
173   llvm::IntegerType *ulong =
174     cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
175   llvm::PointerType *i8p = nullptr;
176   if (CGM.getLangOpts().OpenCL)
177     i8p =
178       llvm::Type::getInt8PtrTy(
179            CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
180   else
181     i8p = CGM.VoidPtrTy;
182 
183   std::string descName;
184 
185   // If an equivalent block descriptor global variable exists, return it.
186   if (C.getLangOpts().ObjC &&
187       CGM.getLangOpts().getGC() == LangOptions::NonGC) {
188     descName = getBlockDescriptorName(blockInfo, CGM);
189     if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
190       return llvm::ConstantExpr::getBitCast(desc,
191                                             CGM.getBlockDescriptorType());
192   }
193 
194   // If there isn't an equivalent block descriptor global variable, create a new
195   // one.
196   ConstantInitBuilder builder(CGM);
197   auto elements = builder.beginStruct();
198 
199   // reserved
200   elements.addInt(ulong, 0);
201 
202   // Size
203   // FIXME: What is the right way to say this doesn't fit?  We should give
204   // a user diagnostic in that case.  Better fix would be to change the
205   // API to size_t.
206   elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
207 
208   // Optional copy/dispose helpers.
209   bool hasInternalHelper = false;
210   if (blockInfo.NeedsCopyDispose) {
211     // copy_func_helper_decl
212     llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
213     elements.add(copyHelper);
214 
215     // destroy_func_decl
216     llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
217     elements.add(disposeHelper);
218 
219     if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
220         cast<llvm::Function>(disposeHelper->getOperand(0))
221             ->hasInternalLinkage())
222       hasInternalHelper = true;
223   }
224 
225   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
226   std::string typeAtEncoding =
227     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
228   elements.add(llvm::ConstantExpr::getBitCast(
229     CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
230 
231   // GC layout.
232   if (C.getLangOpts().ObjC) {
233     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
234       elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
235     else
236       elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
237   }
238   else
239     elements.addNullPointer(i8p);
240 
241   unsigned AddrSpace = 0;
242   if (C.getLangOpts().OpenCL)
243     AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
244 
245   llvm::GlobalValue::LinkageTypes linkage;
246   if (descName.empty()) {
247     linkage = llvm::GlobalValue::InternalLinkage;
248     descName = "__block_descriptor_tmp";
249   } else if (hasInternalHelper) {
250     // If either the copy helper or the dispose helper has internal linkage,
251     // the block descriptor must have internal linkage too.
252     linkage = llvm::GlobalValue::InternalLinkage;
253   } else {
254     linkage = llvm::GlobalValue::LinkOnceODRLinkage;
255   }
256 
257   llvm::GlobalVariable *global =
258       elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
259                                      /*constant*/ true, linkage, AddrSpace);
260 
261   if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
262     if (CGM.supportsCOMDAT())
263       global->setComdat(CGM.getModule().getOrInsertComdat(descName));
264     global->setVisibility(llvm::GlobalValue::HiddenVisibility);
265     global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
266   }
267 
268   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
269 }
270 
271 /*
272   Purely notional variadic template describing the layout of a block.
273 
274   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
275   struct Block_literal {
276     /// Initialized to one of:
277     ///   extern void *_NSConcreteStackBlock[];
278     ///   extern void *_NSConcreteGlobalBlock[];
279     ///
280     /// In theory, we could start one off malloc'ed by setting
281     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
282     /// this isa:
283     ///   extern void *_NSConcreteMallocBlock[];
284     struct objc_class *isa;
285 
286     /// These are the flags (with corresponding bit number) that the
287     /// compiler is actually supposed to know about.
288     ///  23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
289     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
290     ///   descriptor provides copy and dispose helper functions
291     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
292     ///   object with a nontrivial destructor or copy constructor
293     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
294     ///   as global memory
295     ///  29. BLOCK_USE_STRET - indicates that the block function
296     ///   uses stret, which objc_msgSend needs to know about
297     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
298     ///   @encoded signature string
299     /// And we're not supposed to manipulate these:
300     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
301     ///   to malloc'ed memory
302     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
303     ///   to GC-allocated memory
304     /// Additionally, the bottom 16 bits are a reference count which
305     /// should be zero on the stack.
306     int flags;
307 
308     /// Reserved;  should be zero-initialized.
309     int reserved;
310 
311     /// Function pointer generated from block literal.
312     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
313 
314     /// Block description metadata generated from block literal.
315     struct Block_descriptor *block_descriptor;
316 
317     /// Captured values follow.
318     _CapturesTypes captures...;
319   };
320  */
321 
322 namespace {
323   /// A chunk of data that we actually have to capture in the block.
324   struct BlockLayoutChunk {
325     CharUnits Alignment;
326     CharUnits Size;
327     const BlockDecl::Capture *Capture; // null for 'this'
328     llvm::Type *Type;
329     QualType FieldType;
330     BlockCaptureEntityKind CopyKind, DisposeKind;
331     BlockFieldFlags CopyFlags, DisposeFlags;
332 
333     BlockLayoutChunk(CharUnits align, CharUnits size,
334                      const BlockDecl::Capture *capture, llvm::Type *type,
335                      QualType fieldType, BlockCaptureEntityKind CopyKind,
336                      BlockFieldFlags CopyFlags,
337                      BlockCaptureEntityKind DisposeKind,
338                      BlockFieldFlags DisposeFlags)
339         : Alignment(align), Size(size), Capture(capture), Type(type),
340           FieldType(fieldType), CopyKind(CopyKind), DisposeKind(DisposeKind),
341           CopyFlags(CopyFlags), DisposeFlags(DisposeFlags) {}
342 
343     /// Tell the block info that this chunk has the given field index.
344     void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
345       if (!Capture) {
346         info.CXXThisIndex = index;
347         info.CXXThisOffset = offset;
348       } else {
349         info.SortedCaptures.push_back(CGBlockInfo::Capture::makeIndex(
350             index, offset, FieldType, CopyKind, CopyFlags, DisposeKind,
351             DisposeFlags, Capture));
352       }
353     }
354 
355     bool isTrivial() const {
356       return CopyKind == BlockCaptureEntityKind::None &&
357              DisposeKind == BlockCaptureEntityKind::None;
358     }
359   };
360 
361   /// Order by 1) all __strong together 2) next, all block together 3) next,
362   /// all byref together 4) next, all __weak together. Preserve descending
363   /// alignment in all situations.
364   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
365     if (left.Alignment != right.Alignment)
366       return left.Alignment > right.Alignment;
367 
368     auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
369       switch (chunk.CopyKind) {
370       case BlockCaptureEntityKind::ARCStrong:
371         return 0;
372       case BlockCaptureEntityKind::BlockObject:
373         switch (chunk.CopyFlags.getBitMask()) {
374         case BLOCK_FIELD_IS_OBJECT:
375           return 0;
376         case BLOCK_FIELD_IS_BLOCK:
377           return 1;
378         case BLOCK_FIELD_IS_BYREF:
379           return 2;
380         default:
381           break;
382         }
383         break;
384       case BlockCaptureEntityKind::ARCWeak:
385         return 3;
386       default:
387         break;
388       }
389       return 4;
390     };
391 
392     return getPrefOrder(left) < getPrefOrder(right);
393   }
394 } // end anonymous namespace
395 
396 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
397 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
398                                const LangOptions &LangOpts);
399 
400 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
401 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
402                                   const LangOptions &LangOpts);
403 
404 static void addBlockLayout(CharUnits align, CharUnits size,
405                            const BlockDecl::Capture *capture, llvm::Type *type,
406                            QualType fieldType,
407                            SmallVectorImpl<BlockLayoutChunk> &Layout,
408                            CGBlockInfo &Info, CodeGenModule &CGM) {
409   if (!capture) {
410     // 'this' capture.
411     Layout.push_back(BlockLayoutChunk(
412         align, size, capture, type, fieldType, BlockCaptureEntityKind::None,
413         BlockFieldFlags(), BlockCaptureEntityKind::None, BlockFieldFlags()));
414     return;
415   }
416 
417   const LangOptions &LangOpts = CGM.getLangOpts();
418   BlockCaptureEntityKind CopyKind, DisposeKind;
419   BlockFieldFlags CopyFlags, DisposeFlags;
420 
421   std::tie(CopyKind, CopyFlags) =
422       computeCopyInfoForBlockCapture(*capture, fieldType, LangOpts);
423   std::tie(DisposeKind, DisposeFlags) =
424       computeDestroyInfoForBlockCapture(*capture, fieldType, LangOpts);
425   Layout.push_back(BlockLayoutChunk(align, size, capture, type, fieldType,
426                                     CopyKind, CopyFlags, DisposeKind,
427                                     DisposeFlags));
428 
429   if (Info.NoEscape)
430     return;
431 
432   if (!Layout.back().isTrivial())
433     Info.NeedsCopyDispose = true;
434 }
435 
436 /// Determines if the given type is safe for constant capture in C++.
437 static bool isSafeForCXXConstantCapture(QualType type) {
438   const RecordType *recordType =
439     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
440 
441   // Only records can be unsafe.
442   if (!recordType) return true;
443 
444   const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
445 
446   // Maintain semantics for classes with non-trivial dtors or copy ctors.
447   if (!record->hasTrivialDestructor()) return false;
448   if (record->hasNonTrivialCopyConstructor()) return false;
449 
450   // Otherwise, we just have to make sure there aren't any mutable
451   // fields that might have changed since initialization.
452   return !record->hasMutableFields();
453 }
454 
455 /// It is illegal to modify a const object after initialization.
456 /// Therefore, if a const object has a constant initializer, we don't
457 /// actually need to keep storage for it in the block; we'll just
458 /// rematerialize it at the start of the block function.  This is
459 /// acceptable because we make no promises about address stability of
460 /// captured variables.
461 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
462                                             CodeGenFunction *CGF,
463                                             const VarDecl *var) {
464   // Return if this is a function parameter. We shouldn't try to
465   // rematerialize default arguments of function parameters.
466   if (isa<ParmVarDecl>(var))
467     return nullptr;
468 
469   QualType type = var->getType();
470 
471   // We can only do this if the variable is const.
472   if (!type.isConstQualified()) return nullptr;
473 
474   // Furthermore, in C++ we have to worry about mutable fields:
475   // C++ [dcl.type.cv]p4:
476   //   Except that any class member declared mutable can be
477   //   modified, any attempt to modify a const object during its
478   //   lifetime results in undefined behavior.
479   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
480     return nullptr;
481 
482   // If the variable doesn't have any initializer (shouldn't this be
483   // invalid?), it's not clear what we should do.  Maybe capture as
484   // zero?
485   const Expr *init = var->getInit();
486   if (!init) return nullptr;
487 
488   return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
489 }
490 
491 /// Get the low bit of a nonzero character count.  This is the
492 /// alignment of the nth byte if the 0th byte is universally aligned.
493 static CharUnits getLowBit(CharUnits v) {
494   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
495 }
496 
497 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
498                              SmallVectorImpl<llvm::Type*> &elementTypes) {
499 
500   assert(elementTypes.empty());
501   if (CGM.getLangOpts().OpenCL) {
502     // The header is basically 'struct { int; int; generic void *;
503     // custom_fields; }'. Assert that struct is packed.
504     auto GenericAS =
505         CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
506     auto GenPtrAlign =
507         CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
508     auto GenPtrSize =
509         CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
510     assert(CGM.getIntSize() <= GenPtrSize);
511     assert(CGM.getIntAlign() <= GenPtrAlign);
512     assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
513     elementTypes.push_back(CGM.IntTy); /* total size */
514     elementTypes.push_back(CGM.IntTy); /* align */
515     elementTypes.push_back(
516         CGM.getOpenCLRuntime()
517             .getGenericVoidPointerType()); /* invoke function */
518     unsigned Offset =
519         2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
520     unsigned BlockAlign = GenPtrAlign.getQuantity();
521     if (auto *Helper =
522             CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
523       for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
524         // TargetOpenCLBlockHelp needs to make sure the struct is packed.
525         // If necessary, add padding fields to the custom fields.
526         unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
527         if (BlockAlign < Align)
528           BlockAlign = Align;
529         assert(Offset % Align == 0);
530         Offset += CGM.getDataLayout().getTypeAllocSize(I);
531         elementTypes.push_back(I);
532       }
533     }
534     info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
535     info.BlockSize = CharUnits::fromQuantity(Offset);
536   } else {
537     // The header is basically 'struct { void *; int; int; void *; void *; }'.
538     // Assert that the struct is packed.
539     assert(CGM.getIntSize() <= CGM.getPointerSize());
540     assert(CGM.getIntAlign() <= CGM.getPointerAlign());
541     assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
542     info.BlockAlign = CGM.getPointerAlign();
543     info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
544     elementTypes.push_back(CGM.VoidPtrTy);
545     elementTypes.push_back(CGM.IntTy);
546     elementTypes.push_back(CGM.IntTy);
547     elementTypes.push_back(CGM.VoidPtrTy);
548     elementTypes.push_back(CGM.getBlockDescriptorType());
549   }
550 }
551 
552 static QualType getCaptureFieldType(const CodeGenFunction &CGF,
553                                     const BlockDecl::Capture &CI) {
554   const VarDecl *VD = CI.getVariable();
555 
556   // If the variable is captured by an enclosing block or lambda expression,
557   // use the type of the capture field.
558   if (CGF.BlockInfo && CI.isNested())
559     return CGF.BlockInfo->getCapture(VD).fieldType();
560   if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
561     return FD->getType();
562   // If the captured variable is a non-escaping __block variable, the field
563   // type is the reference type. If the variable is a __block variable that
564   // already has a reference type, the field type is the variable's type.
565   return VD->isNonEscapingByref() ?
566          CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
567 }
568 
569 /// Compute the layout of the given block.  Attempts to lay the block
570 /// out with minimal space requirements.
571 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
572                              CGBlockInfo &info) {
573   ASTContext &C = CGM.getContext();
574   const BlockDecl *block = info.getBlockDecl();
575 
576   SmallVector<llvm::Type*, 8> elementTypes;
577   initializeForBlockHeader(CGM, info, elementTypes);
578   bool hasNonConstantCustomFields = false;
579   if (auto *OpenCLHelper =
580           CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
581     hasNonConstantCustomFields =
582         !OpenCLHelper->areAllCustomFieldValuesConstant(info);
583   if (!block->hasCaptures() && !hasNonConstantCustomFields) {
584     info.StructureType =
585       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
586     info.CanBeGlobal = true;
587     return;
588   }
589   else if (C.getLangOpts().ObjC &&
590            CGM.getLangOpts().getGC() == LangOptions::NonGC)
591     info.HasCapturedVariableLayout = true;
592 
593   if (block->doesNotEscape())
594     info.NoEscape = true;
595 
596   // Collect the layout chunks.
597   SmallVector<BlockLayoutChunk, 16> layout;
598   layout.reserve(block->capturesCXXThis() +
599                  (block->capture_end() - block->capture_begin()));
600 
601   CharUnits maxFieldAlign;
602 
603   // First, 'this'.
604   if (block->capturesCXXThis()) {
605     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
606            "Can't capture 'this' outside a method");
607     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
608 
609     // Theoretically, this could be in a different address space, so
610     // don't assume standard pointer size/align.
611     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
612     auto TInfo = CGM.getContext().getTypeInfoInChars(thisType);
613     maxFieldAlign = std::max(maxFieldAlign, TInfo.Align);
614 
615     addBlockLayout(TInfo.Align, TInfo.Width, nullptr, llvmType, thisType,
616                    layout, info, CGM);
617   }
618 
619   // Next, all the block captures.
620   for (const auto &CI : block->captures()) {
621     const VarDecl *variable = CI.getVariable();
622 
623     if (CI.isEscapingByref()) {
624       // Just use void* instead of a pointer to the byref type.
625       CharUnits align = CGM.getPointerAlign();
626       maxFieldAlign = std::max(maxFieldAlign, align);
627 
628       // Since a __block variable cannot be captured by lambdas, its type and
629       // the capture field type should always match.
630       assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() &&
631              "capture type differs from the variable type");
632       addBlockLayout(align, CGM.getPointerSize(), &CI, CGM.VoidPtrTy,
633                      variable->getType(), layout, info, CGM);
634       continue;
635     }
636 
637     // Otherwise, build a layout chunk with the size and alignment of
638     // the declaration.
639     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
640       info.SortedCaptures.push_back(
641           CGBlockInfo::Capture::makeConstant(constant, &CI));
642       continue;
643     }
644 
645     QualType VT = getCaptureFieldType(*CGF, CI);
646 
647     if (CGM.getLangOpts().CPlusPlus)
648       if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl())
649         if (CI.hasCopyExpr() || !record->hasTrivialDestructor()) {
650           info.HasCXXObject = true;
651           if (!record->isExternallyVisible())
652             info.CapturesNonExternalType = true;
653         }
654 
655     CharUnits size = C.getTypeSizeInChars(VT);
656     CharUnits align = C.getDeclAlign(variable);
657 
658     maxFieldAlign = std::max(maxFieldAlign, align);
659 
660     llvm::Type *llvmType =
661       CGM.getTypes().ConvertTypeForMem(VT);
662 
663     addBlockLayout(align, size, &CI, llvmType, VT, layout, info, CGM);
664   }
665 
666   // If that was everything, we're done here.
667   if (layout.empty()) {
668     info.StructureType =
669       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
670     info.CanBeGlobal = true;
671     info.buildCaptureMap();
672     return;
673   }
674 
675   // Sort the layout by alignment.  We have to use a stable sort here
676   // to get reproducible results.  There should probably be an
677   // llvm::array_pod_stable_sort.
678   llvm::stable_sort(layout);
679 
680   // Needed for blocks layout info.
681   info.BlockHeaderForcedGapOffset = info.BlockSize;
682   info.BlockHeaderForcedGapSize = CharUnits::Zero();
683 
684   CharUnits &blockSize = info.BlockSize;
685   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
686 
687   // Assuming that the first byte in the header is maximally aligned,
688   // get the alignment of the first byte following the header.
689   CharUnits endAlign = getLowBit(blockSize);
690 
691   // If the end of the header isn't satisfactorily aligned for the
692   // maximum thing, look for things that are okay with the header-end
693   // alignment, and keep appending them until we get something that's
694   // aligned right.  This algorithm is only guaranteed optimal if
695   // that condition is satisfied at some point; otherwise we can get
696   // things like:
697   //   header                 // next byte has alignment 4
698   //   something_with_size_5; // next byte has alignment 1
699   //   something_with_alignment_8;
700   // which has 7 bytes of padding, as opposed to the naive solution
701   // which might have less (?).
702   if (endAlign < maxFieldAlign) {
703     SmallVectorImpl<BlockLayoutChunk>::iterator
704       li = layout.begin() + 1, le = layout.end();
705 
706     // Look for something that the header end is already
707     // satisfactorily aligned for.
708     for (; li != le && endAlign < li->Alignment; ++li)
709       ;
710 
711     // If we found something that's naturally aligned for the end of
712     // the header, keep adding things...
713     if (li != le) {
714       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
715       for (; li != le; ++li) {
716         assert(endAlign >= li->Alignment);
717 
718         li->setIndex(info, elementTypes.size(), blockSize);
719         elementTypes.push_back(li->Type);
720         blockSize += li->Size;
721         endAlign = getLowBit(blockSize);
722 
723         // ...until we get to the alignment of the maximum field.
724         if (endAlign >= maxFieldAlign) {
725           ++li;
726           break;
727         }
728       }
729       // Don't re-append everything we just appended.
730       layout.erase(first, li);
731     }
732   }
733 
734   assert(endAlign == getLowBit(blockSize));
735 
736   // At this point, we just have to add padding if the end align still
737   // isn't aligned right.
738   if (endAlign < maxFieldAlign) {
739     CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
740     CharUnits padding = newBlockSize - blockSize;
741 
742     // If we haven't yet added any fields, remember that there was an
743     // initial gap; this need to go into the block layout bit map.
744     if (blockSize == info.BlockHeaderForcedGapOffset) {
745       info.BlockHeaderForcedGapSize = padding;
746     }
747 
748     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
749                                                 padding.getQuantity()));
750     blockSize = newBlockSize;
751     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
752   }
753 
754   assert(endAlign >= maxFieldAlign);
755   assert(endAlign == getLowBit(blockSize));
756   // Slam everything else on now.  This works because they have
757   // strictly decreasing alignment and we expect that size is always a
758   // multiple of alignment.
759   for (SmallVectorImpl<BlockLayoutChunk>::iterator
760          li = layout.begin(), le = layout.end(); li != le; ++li) {
761     if (endAlign < li->Alignment) {
762       // size may not be multiple of alignment. This can only happen with
763       // an over-aligned variable. We will be adding a padding field to
764       // make the size be multiple of alignment.
765       CharUnits padding = li->Alignment - endAlign;
766       elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
767                                                   padding.getQuantity()));
768       blockSize += padding;
769       endAlign = getLowBit(blockSize);
770     }
771     assert(endAlign >= li->Alignment);
772     li->setIndex(info, elementTypes.size(), blockSize);
773     elementTypes.push_back(li->Type);
774     blockSize += li->Size;
775     endAlign = getLowBit(blockSize);
776   }
777 
778   info.buildCaptureMap();
779   info.StructureType =
780     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
781 }
782 
783 /// Emit a block literal expression in the current function.
784 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
785   // If the block has no captures, we won't have a pre-computed
786   // layout for it.
787   if (!blockExpr->getBlockDecl()->hasCaptures())
788     // The block literal is emitted as a global variable, and the block invoke
789     // function has to be extracted from its initializer.
790     if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
791       return Block;
792 
793   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
794   computeBlockInfo(CGM, this, blockInfo);
795   blockInfo.BlockExpression = blockExpr;
796   if (!blockInfo.CanBeGlobal)
797     blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
798                                               blockInfo.BlockAlign, "block");
799   return EmitBlockLiteral(blockInfo);
800 }
801 
802 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
803   bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
804   auto GenVoidPtrTy =
805       IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
806   LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
807   auto GenVoidPtrSize = CharUnits::fromQuantity(
808       CGM.getTarget().getPointerWidth(
809           CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
810       8);
811   // Using the computed layout, generate the actual block function.
812   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
813   CodeGenFunction BlockCGF{CGM, true};
814   BlockCGF.SanOpts = SanOpts;
815   auto *InvokeFn = BlockCGF.GenerateBlockFunction(
816       CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
817   auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
818 
819   // If there is nothing to capture, we can emit this as a global block.
820   if (blockInfo.CanBeGlobal)
821     return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
822 
823   // Otherwise, we have to emit this as a local block.
824 
825   Address blockAddr = blockInfo.LocalAddress;
826   assert(blockAddr.isValid() && "block has no address!");
827 
828   llvm::Constant *isa;
829   llvm::Constant *descriptor;
830   BlockFlags flags;
831   if (!IsOpenCL) {
832     // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
833     // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
834     // block just returns the original block and releasing it is a no-op.
835     llvm::Constant *blockISA = blockInfo.NoEscape
836                                    ? CGM.getNSConcreteGlobalBlock()
837                                    : CGM.getNSConcreteStackBlock();
838     isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
839 
840     // Build the block descriptor.
841     descriptor = buildBlockDescriptor(CGM, blockInfo);
842 
843     // Compute the initial on-stack block flags.
844     flags = BLOCK_HAS_SIGNATURE;
845     if (blockInfo.HasCapturedVariableLayout)
846       flags |= BLOCK_HAS_EXTENDED_LAYOUT;
847     if (blockInfo.NeedsCopyDispose)
848       flags |= BLOCK_HAS_COPY_DISPOSE;
849     if (blockInfo.HasCXXObject)
850       flags |= BLOCK_HAS_CXX_OBJ;
851     if (blockInfo.UsesStret)
852       flags |= BLOCK_USE_STRET;
853     if (blockInfo.NoEscape)
854       flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
855   }
856 
857   auto projectField = [&](unsigned index, const Twine &name) -> Address {
858     return Builder.CreateStructGEP(blockAddr, index, name);
859   };
860   auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
861     Builder.CreateStore(value, projectField(index, name));
862   };
863 
864   // Initialize the block header.
865   {
866     // We assume all the header fields are densely packed.
867     unsigned index = 0;
868     CharUnits offset;
869     auto addHeaderField = [&](llvm::Value *value, CharUnits size,
870                               const Twine &name) {
871       storeField(value, index, name);
872       offset += size;
873       index++;
874     };
875 
876     if (!IsOpenCL) {
877       addHeaderField(isa, getPointerSize(), "block.isa");
878       addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
879                      getIntSize(), "block.flags");
880       addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
881                      "block.reserved");
882     } else {
883       addHeaderField(
884           llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
885           getIntSize(), "block.size");
886       addHeaderField(
887           llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
888           getIntSize(), "block.align");
889     }
890     addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
891     if (!IsOpenCL)
892       addHeaderField(descriptor, getPointerSize(), "block.descriptor");
893     else if (auto *Helper =
894                  CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
895       for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
896         addHeaderField(
897             I.first,
898             CharUnits::fromQuantity(
899                 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
900             I.second);
901       }
902     }
903   }
904 
905   // Finally, capture all the values into the block.
906   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
907 
908   // First, 'this'.
909   if (blockDecl->capturesCXXThis()) {
910     Address addr =
911         projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
912     Builder.CreateStore(LoadCXXThis(), addr);
913   }
914 
915   // Next, captured variables.
916   for (const auto &CI : blockDecl->captures()) {
917     const VarDecl *variable = CI.getVariable();
918     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
919 
920     // Ignore constant captures.
921     if (capture.isConstant()) continue;
922 
923     QualType type = capture.fieldType();
924 
925     // This will be a [[type]]*, except that a byref entry will just be
926     // an i8**.
927     Address blockField = projectField(capture.getIndex(), "block.captured");
928 
929     // Compute the address of the thing we're going to move into the
930     // block literal.
931     Address src = Address::invalid();
932 
933     if (blockDecl->isConversionFromLambda()) {
934       // The lambda capture in a lambda's conversion-to-block-pointer is
935       // special; we'll simply emit it directly.
936       src = Address::invalid();
937     } else if (CI.isEscapingByref()) {
938       if (BlockInfo && CI.isNested()) {
939         // We need to use the capture from the enclosing block.
940         const CGBlockInfo::Capture &enclosingCapture =
941             BlockInfo->getCapture(variable);
942 
943         // This is a [[type]]*, except that a byref entry will just be an i8**.
944         src = Builder.CreateStructGEP(LoadBlockStruct(),
945                                       enclosingCapture.getIndex(),
946                                       "block.capture.addr");
947       } else {
948         auto I = LocalDeclMap.find(variable);
949         assert(I != LocalDeclMap.end());
950         src = I->second;
951       }
952     } else {
953       DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
954                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
955                           type.getNonReferenceType(), VK_LValue,
956                           SourceLocation());
957       src = EmitDeclRefLValue(&declRef).getAddress(*this);
958     };
959 
960     // For byrefs, we just write the pointer to the byref struct into
961     // the block field.  There's no need to chase the forwarding
962     // pointer at this point, since we're building something that will
963     // live a shorter life than the stack byref anyway.
964     if (CI.isEscapingByref()) {
965       // Get a void* that points to the byref struct.
966       llvm::Value *byrefPointer;
967       if (CI.isNested())
968         byrefPointer = Builder.CreateLoad(src, "byref.capture");
969       else
970         byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
971 
972       // Write that void* into the capture field.
973       Builder.CreateStore(byrefPointer, blockField);
974 
975     // If we have a copy constructor, evaluate that into the block field.
976     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
977       if (blockDecl->isConversionFromLambda()) {
978         // If we have a lambda conversion, emit the expression
979         // directly into the block instead.
980         AggValueSlot Slot =
981             AggValueSlot::forAddr(blockField, Qualifiers(),
982                                   AggValueSlot::IsDestructed,
983                                   AggValueSlot::DoesNotNeedGCBarriers,
984                                   AggValueSlot::IsNotAliased,
985                                   AggValueSlot::DoesNotOverlap);
986         EmitAggExpr(copyExpr, Slot);
987       } else {
988         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
989       }
990 
991     // If it's a reference variable, copy the reference into the block field.
992     } else if (type->isReferenceType()) {
993       Builder.CreateStore(src.getPointer(), blockField);
994 
995     // If type is const-qualified, copy the value into the block field.
996     } else if (type.isConstQualified() &&
997                type.getObjCLifetime() == Qualifiers::OCL_Strong &&
998                CGM.getCodeGenOpts().OptimizationLevel != 0) {
999       llvm::Value *value = Builder.CreateLoad(src, "captured");
1000       Builder.CreateStore(value, blockField);
1001 
1002     // If this is an ARC __strong block-pointer variable, don't do a
1003     // block copy.
1004     //
1005     // TODO: this can be generalized into the normal initialization logic:
1006     // we should never need to do a block-copy when initializing a local
1007     // variable, because the local variable's lifetime should be strictly
1008     // contained within the stack block's.
1009     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1010                type->isBlockPointerType()) {
1011       // Load the block and do a simple retain.
1012       llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1013       value = EmitARCRetainNonBlock(value);
1014 
1015       // Do a primitive store to the block field.
1016       Builder.CreateStore(value, blockField);
1017 
1018     // Otherwise, fake up a POD copy into the block field.
1019     } else {
1020       // Fake up a new variable so that EmitScalarInit doesn't think
1021       // we're referring to the variable in its own initializer.
1022       ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1023                                             ImplicitParamDecl::Other);
1024 
1025       // We use one of these or the other depending on whether the
1026       // reference is nested.
1027       DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1028                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1029                           type, VK_LValue, SourceLocation());
1030 
1031       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1032                            &declRef, VK_PRValue, FPOptionsOverride());
1033       // FIXME: Pass a specific location for the expr init so that the store is
1034       // attributed to a reasonable location - otherwise it may be attributed to
1035       // locations of subexpressions in the initialization.
1036       EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1037                      MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1038                      /*captured by init*/ false);
1039     }
1040 
1041     // Push a cleanup for the capture if necessary.
1042     if (!blockInfo.NoEscape && !blockInfo.NeedsCopyDispose)
1043       continue;
1044 
1045     // Ignore __block captures; there's nothing special in the on-stack block
1046     // that we need to do for them.
1047     if (CI.isByRef())
1048       continue;
1049 
1050     // Ignore objects that aren't destructed.
1051     QualType::DestructionKind dtorKind = type.isDestructedType();
1052     if (dtorKind == QualType::DK_none)
1053       continue;
1054 
1055     CodeGenFunction::Destroyer *destroyer;
1056 
1057     // Block captures count as local values and have imprecise semantics.
1058     // They also can't be arrays, so need to worry about that.
1059     //
1060     // For const-qualified captures, emit clang.arc.use to ensure the captured
1061     // object doesn't get released while we are still depending on its validity
1062     // within the block.
1063     if (type.isConstQualified() &&
1064         type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1065         CGM.getCodeGenOpts().OptimizationLevel != 0) {
1066       assert(CGM.getLangOpts().ObjCAutoRefCount &&
1067              "expected ObjC ARC to be enabled");
1068       destroyer = emitARCIntrinsicUse;
1069     } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
1070       destroyer = destroyARCStrongImprecise;
1071     } else {
1072       destroyer = getDestroyer(dtorKind);
1073     }
1074 
1075     CleanupKind cleanupKind = NormalCleanup;
1076     bool useArrayEHCleanup = needsEHCleanup(dtorKind);
1077     if (useArrayEHCleanup)
1078       cleanupKind = NormalAndEHCleanup;
1079 
1080     // Extend the lifetime of the capture to the end of the scope enclosing the
1081     // block expression except when the block decl is in the list of RetExpr's
1082     // cleanup objects, in which case its lifetime ends after the full
1083     // expression.
1084     auto IsBlockDeclInRetExpr = [&]() {
1085       auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
1086       if (EWC)
1087         for (auto &C : EWC->getObjects())
1088           if (auto *BD = C.dyn_cast<BlockDecl *>())
1089             if (BD == blockDecl)
1090               return true;
1091       return false;
1092     };
1093 
1094     if (IsBlockDeclInRetExpr())
1095       pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
1096     else
1097       pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
1098                                   useArrayEHCleanup);
1099   }
1100 
1101   // Cast to the converted block-pointer type, which happens (somewhat
1102   // unfortunately) to be a pointer to function type.
1103   llvm::Value *result = Builder.CreatePointerCast(
1104       blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1105 
1106   if (IsOpenCL) {
1107     CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1108                                            result);
1109   }
1110 
1111   return result;
1112 }
1113 
1114 
1115 llvm::Type *CodeGenModule::getBlockDescriptorType() {
1116   if (BlockDescriptorType)
1117     return BlockDescriptorType;
1118 
1119   llvm::Type *UnsignedLongTy =
1120     getTypes().ConvertType(getContext().UnsignedLongTy);
1121 
1122   // struct __block_descriptor {
1123   //   unsigned long reserved;
1124   //   unsigned long block_size;
1125   //
1126   //   // later, the following will be added
1127   //
1128   //   struct {
1129   //     void (*copyHelper)();
1130   //     void (*copyHelper)();
1131   //   } helpers;                // !!! optional
1132   //
1133   //   const char *signature;   // the block signature
1134   //   const char *layout;      // reserved
1135   // };
1136   BlockDescriptorType = llvm::StructType::create(
1137       "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1138 
1139   // Now form a pointer to that.
1140   unsigned AddrSpace = 0;
1141   if (getLangOpts().OpenCL)
1142     AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1143   BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1144   return BlockDescriptorType;
1145 }
1146 
1147 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1148   if (GenericBlockLiteralType)
1149     return GenericBlockLiteralType;
1150 
1151   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1152 
1153   if (getLangOpts().OpenCL) {
1154     // struct __opencl_block_literal_generic {
1155     //   int __size;
1156     //   int __align;
1157     //   __generic void *__invoke;
1158     //   /* custom fields */
1159     // };
1160     SmallVector<llvm::Type *, 8> StructFields(
1161         {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1162     if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1163       for (auto I : Helper->getCustomFieldTypes())
1164         StructFields.push_back(I);
1165     }
1166     GenericBlockLiteralType = llvm::StructType::create(
1167         StructFields, "struct.__opencl_block_literal_generic");
1168   } else {
1169     // struct __block_literal_generic {
1170     //   void *__isa;
1171     //   int __flags;
1172     //   int __reserved;
1173     //   void (*__invoke)(void *);
1174     //   struct __block_descriptor *__descriptor;
1175     // };
1176     GenericBlockLiteralType =
1177         llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1178                                  IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1179   }
1180 
1181   return GenericBlockLiteralType;
1182 }
1183 
1184 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1185                                           ReturnValueSlot ReturnValue) {
1186   const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
1187   llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1188   llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1189   llvm::Value *Func = nullptr;
1190   QualType FnType = BPT->getPointeeType();
1191   ASTContext &Ctx = getContext();
1192   CallArgList Args;
1193 
1194   if (getLangOpts().OpenCL) {
1195     // For OpenCL, BlockPtr is already casted to generic block literal.
1196 
1197     // First argument of a block call is a generic block literal casted to
1198     // generic void pointer, i.e. i8 addrspace(4)*
1199     llvm::Type *GenericVoidPtrTy =
1200         CGM.getOpenCLRuntime().getGenericVoidPointerType();
1201     llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1202         BlockPtr, GenericVoidPtrTy);
1203     QualType VoidPtrQualTy = Ctx.getPointerType(
1204         Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1205     Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1206     // And the rest of the arguments.
1207     EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1208 
1209     // We *can* call the block directly unless it is a function argument.
1210     if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1211       Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1212     else {
1213       llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1214       Func = Builder.CreateAlignedLoad(GenericVoidPtrTy, FuncPtr,
1215                                        getPointerAlign());
1216     }
1217   } else {
1218     // Bitcast the block literal to a generic block literal.
1219     BlockPtr = Builder.CreatePointerCast(
1220         BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1221     // Get pointer to the block invoke function
1222     llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1223 
1224     // First argument is a block literal casted to a void pointer
1225     BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1226     Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1227     // And the rest of the arguments.
1228     EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1229 
1230     // Load the function.
1231     Func = Builder.CreateAlignedLoad(VoidPtrTy, FuncPtr, getPointerAlign());
1232   }
1233 
1234   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1235   const CGFunctionInfo &FnInfo =
1236     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1237 
1238   // Cast the function pointer to the right type.
1239   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1240 
1241   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1242   Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1243 
1244   // Prepare the callee.
1245   CGCallee Callee(CGCalleeInfo(), Func);
1246 
1247   // And call the block.
1248   return EmitCall(FnInfo, Callee, ReturnValue, Args);
1249 }
1250 
1251 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1252   assert(BlockInfo && "evaluating block ref without block information?");
1253   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1254 
1255   // Handle constant captures.
1256   if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1257 
1258   Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1259                                          "block.capture.addr");
1260 
1261   if (variable->isEscapingByref()) {
1262     // addr should be a void** right now.  Load, then cast the result
1263     // to byref*.
1264 
1265     auto &byrefInfo = getBlockByrefInfo(variable);
1266     addr = Address(Builder.CreateLoad(addr), Int8Ty, byrefInfo.ByrefAlignment);
1267 
1268     addr = Builder.CreateElementBitCast(addr, byrefInfo.Type, "byref.addr");
1269 
1270     addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1271                                  variable->getName());
1272   }
1273 
1274   assert((!variable->isNonEscapingByref() ||
1275           capture.fieldType()->isReferenceType()) &&
1276          "the capture field of a non-escaping variable should have a "
1277          "reference type");
1278   if (capture.fieldType()->isReferenceType())
1279     addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1280 
1281   return addr;
1282 }
1283 
1284 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1285                                          llvm::Constant *Addr) {
1286   bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1287   (void)Ok;
1288   assert(Ok && "Trying to replace an already-existing global block!");
1289 }
1290 
1291 llvm::Constant *
1292 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1293                                     StringRef Name) {
1294   if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1295     return Block;
1296 
1297   CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1298   blockInfo.BlockExpression = BE;
1299 
1300   // Compute information about the layout, etc., of this block.
1301   computeBlockInfo(*this, nullptr, blockInfo);
1302 
1303   // Using that metadata, generate the actual block function.
1304   {
1305     CodeGenFunction::DeclMapTy LocalDeclMap;
1306     CodeGenFunction(*this).GenerateBlockFunction(
1307         GlobalDecl(), blockInfo, LocalDeclMap,
1308         /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1309   }
1310 
1311   return getAddrOfGlobalBlockIfEmitted(BE);
1312 }
1313 
1314 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1315                                         const CGBlockInfo &blockInfo,
1316                                         llvm::Constant *blockFn) {
1317   assert(blockInfo.CanBeGlobal);
1318   // Callers should detect this case on their own: calling this function
1319   // generally requires computing layout information, which is a waste of time
1320   // if we've already emitted this block.
1321   assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1322          "Refusing to re-emit a global block.");
1323 
1324   // Generate the constants for the block literal initializer.
1325   ConstantInitBuilder builder(CGM);
1326   auto fields = builder.beginStruct();
1327 
1328   bool IsOpenCL = CGM.getLangOpts().OpenCL;
1329   bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1330   if (!IsOpenCL) {
1331     // isa
1332     if (IsWindows)
1333       fields.addNullPointer(CGM.Int8PtrPtrTy);
1334     else
1335       fields.add(CGM.getNSConcreteGlobalBlock());
1336 
1337     // __flags
1338     BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1339     if (blockInfo.UsesStret)
1340       flags |= BLOCK_USE_STRET;
1341 
1342     fields.addInt(CGM.IntTy, flags.getBitMask());
1343 
1344     // Reserved
1345     fields.addInt(CGM.IntTy, 0);
1346   } else {
1347     fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1348     fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1349   }
1350 
1351   // Function
1352   fields.add(blockFn);
1353 
1354   if (!IsOpenCL) {
1355     // Descriptor
1356     fields.add(buildBlockDescriptor(CGM, blockInfo));
1357   } else if (auto *Helper =
1358                  CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1359     for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1360       fields.add(I);
1361     }
1362   }
1363 
1364   unsigned AddrSpace = 0;
1365   if (CGM.getContext().getLangOpts().OpenCL)
1366     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1367 
1368   llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
1369       "__block_literal_global", blockInfo.BlockAlign,
1370       /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1371 
1372   literal->addAttribute("objc_arc_inert");
1373 
1374   // Windows does not allow globals to be initialised to point to globals in
1375   // different DLLs.  Any such variables must run code to initialise them.
1376   if (IsWindows) {
1377     auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1378           {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1379         &CGM.getModule());
1380     llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1381           Init));
1382     b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1383                          b.CreateStructGEP(literal->getValueType(), literal, 0),
1384                          CGM.getPointerAlign().getAsAlign());
1385     b.CreateRetVoid();
1386     // We can't use the normal LLVM global initialisation array, because we
1387     // need to specify that this runs early in library initialisation.
1388     auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1389         /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1390         Init, ".block_isa_init_ptr");
1391     InitVar->setSection(".CRT$XCLa");
1392     CGM.addUsedGlobal(InitVar);
1393   }
1394 
1395   // Return a constant of the appropriately-casted type.
1396   llvm::Type *RequiredType =
1397     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1398   llvm::Constant *Result =
1399       llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1400   CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1401   if (CGM.getContext().getLangOpts().OpenCL)
1402     CGM.getOpenCLRuntime().recordBlockInfo(
1403         blockInfo.BlockExpression,
1404         cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
1405   return Result;
1406 }
1407 
1408 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1409                                                unsigned argNum,
1410                                                llvm::Value *arg) {
1411   assert(BlockInfo && "not emitting prologue of block invocation function?!");
1412 
1413   // Allocate a stack slot like for any local variable to guarantee optimal
1414   // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1415   Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1416   Builder.CreateStore(arg, alloc);
1417   if (CGDebugInfo *DI = getDebugInfo()) {
1418     if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1419       DI->setLocation(D->getLocation());
1420       DI->EmitDeclareOfBlockLiteralArgVariable(
1421           *BlockInfo, D->getName(), argNum,
1422           cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1423     }
1424   }
1425 
1426   SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1427   ApplyDebugLocation Scope(*this, StartLoc);
1428 
1429   // Instead of messing around with LocalDeclMap, just set the value
1430   // directly as BlockPointer.
1431   BlockPointer = Builder.CreatePointerCast(
1432       arg,
1433       BlockInfo->StructureType->getPointerTo(
1434           getContext().getLangOpts().OpenCL
1435               ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1436               : 0),
1437       "block");
1438 }
1439 
1440 Address CodeGenFunction::LoadBlockStruct() {
1441   assert(BlockInfo && "not in a block invocation function!");
1442   assert(BlockPointer && "no block pointer set!");
1443   return Address(BlockPointer, BlockInfo->StructureType, BlockInfo->BlockAlign);
1444 }
1445 
1446 llvm::Function *CodeGenFunction::GenerateBlockFunction(
1447     GlobalDecl GD, const CGBlockInfo &blockInfo, const DeclMapTy &ldm,
1448     bool IsLambdaConversionToBlock, bool BuildGlobalBlock) {
1449   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1450 
1451   CurGD = GD;
1452 
1453   CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1454 
1455   BlockInfo = &blockInfo;
1456 
1457   // Arrange for local static and local extern declarations to appear
1458   // to be local to this function as well, in case they're directly
1459   // referenced in a block.
1460   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1461     const auto *var = dyn_cast<VarDecl>(i->first);
1462     if (var && !var->hasLocalStorage())
1463       setAddrOfLocalVar(var, i->second);
1464   }
1465 
1466   // Begin building the function declaration.
1467 
1468   // Build the argument list.
1469   FunctionArgList args;
1470 
1471   // The first argument is the block pointer.  Just take it as a void*
1472   // and cast it later.
1473   QualType selfTy = getContext().VoidPtrTy;
1474 
1475   // For OpenCL passed block pointer can be private AS local variable or
1476   // global AS program scope variable (for the case with and without captures).
1477   // Generic AS is used therefore to be able to accommodate both private and
1478   // generic AS in one implementation.
1479   if (getLangOpts().OpenCL)
1480     selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1481         getContext().VoidTy, LangAS::opencl_generic));
1482 
1483   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1484 
1485   ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1486                              SourceLocation(), II, selfTy,
1487                              ImplicitParamDecl::ObjCSelf);
1488   args.push_back(&SelfDecl);
1489 
1490   // Now add the rest of the parameters.
1491   args.append(blockDecl->param_begin(), blockDecl->param_end());
1492 
1493   // Create the function declaration.
1494   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1495   const CGFunctionInfo &fnInfo =
1496     CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1497   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1498     blockInfo.UsesStret = true;
1499 
1500   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1501 
1502   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1503   llvm::Function *fn = llvm::Function::Create(
1504       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1505   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1506 
1507   if (BuildGlobalBlock) {
1508     auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1509                             ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1510                             : VoidPtrTy;
1511     buildGlobalBlock(CGM, blockInfo,
1512                      llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1513   }
1514 
1515   // Begin generating the function.
1516   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1517                 blockDecl->getLocation(),
1518                 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1519 
1520   // Okay.  Undo some of what StartFunction did.
1521 
1522   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1523   // won't delete the dbg.declare intrinsics for captured variables.
1524   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1525   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1526     // Allocate a stack slot for it, so we can point the debugger to it
1527     Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1528                                       getPointerAlign(),
1529                                       "block.addr");
1530     // Set the DebugLocation to empty, so the store is recognized as a
1531     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1532     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1533     Builder.CreateStore(BlockPointer, Alloca);
1534     BlockPointerDbgLoc = Alloca.getPointer();
1535   }
1536 
1537   // If we have a C++ 'this' reference, go ahead and force it into
1538   // existence now.
1539   if (blockDecl->capturesCXXThis()) {
1540     Address addr = Builder.CreateStructGEP(
1541         LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
1542     CXXThisValue = Builder.CreateLoad(addr, "this");
1543   }
1544 
1545   // Also force all the constant captures.
1546   for (const auto &CI : blockDecl->captures()) {
1547     const VarDecl *variable = CI.getVariable();
1548     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1549     if (!capture.isConstant()) continue;
1550 
1551     CharUnits align = getContext().getDeclAlign(variable);
1552     Address alloca =
1553       CreateMemTemp(variable->getType(), align, "block.captured-const");
1554 
1555     Builder.CreateStore(capture.getConstant(), alloca);
1556 
1557     setAddrOfLocalVar(variable, alloca);
1558   }
1559 
1560   // Save a spot to insert the debug information for all the DeclRefExprs.
1561   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1562   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1563   --entry_ptr;
1564 
1565   if (IsLambdaConversionToBlock)
1566     EmitLambdaBlockInvokeBody();
1567   else {
1568     PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1569     incrementProfileCounter(blockDecl->getBody());
1570     EmitStmt(blockDecl->getBody());
1571   }
1572 
1573   // Remember where we were...
1574   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1575 
1576   // Go back to the entry.
1577   ++entry_ptr;
1578   Builder.SetInsertPoint(entry, entry_ptr);
1579 
1580   // Emit debug information for all the DeclRefExprs.
1581   // FIXME: also for 'this'
1582   if (CGDebugInfo *DI = getDebugInfo()) {
1583     for (const auto &CI : blockDecl->captures()) {
1584       const VarDecl *variable = CI.getVariable();
1585       DI->EmitLocation(Builder, variable->getLocation());
1586 
1587       if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1588         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1589         if (capture.isConstant()) {
1590           auto addr = LocalDeclMap.find(variable)->second;
1591           (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1592                                               Builder);
1593           continue;
1594         }
1595 
1596         DI->EmitDeclareOfBlockDeclRefVariable(
1597             variable, BlockPointerDbgLoc, Builder, blockInfo,
1598             entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1599       }
1600     }
1601     // Recover location if it was changed in the above loop.
1602     DI->EmitLocation(Builder,
1603                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1604   }
1605 
1606   // And resume where we left off.
1607   if (resume == nullptr)
1608     Builder.ClearInsertionPoint();
1609   else
1610     Builder.SetInsertPoint(resume);
1611 
1612   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1613 
1614   return fn;
1615 }
1616 
1617 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1618 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1619                                const LangOptions &LangOpts) {
1620   if (CI.getCopyExpr()) {
1621     assert(!CI.isByRef());
1622     // don't bother computing flags
1623     return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1624   }
1625   BlockFieldFlags Flags;
1626   if (CI.isEscapingByref()) {
1627     Flags = BLOCK_FIELD_IS_BYREF;
1628     if (T.isObjCGCWeak())
1629       Flags |= BLOCK_FIELD_IS_WEAK;
1630     return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1631   }
1632 
1633   Flags = BLOCK_FIELD_IS_OBJECT;
1634   bool isBlockPointer = T->isBlockPointerType();
1635   if (isBlockPointer)
1636     Flags = BLOCK_FIELD_IS_BLOCK;
1637 
1638   switch (T.isNonTrivialToPrimitiveCopy()) {
1639   case QualType::PCK_Struct:
1640     return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1641                           BlockFieldFlags());
1642   case QualType::PCK_ARCWeak:
1643     // We need to register __weak direct captures with the runtime.
1644     return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1645   case QualType::PCK_ARCStrong:
1646     // We need to retain the copied value for __strong direct captures.
1647     // If it's a block pointer, we have to copy the block and assign that to
1648     // the destination pointer, so we might as well use _Block_object_assign.
1649     // Otherwise we can avoid that.
1650     return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1651                                           : BlockCaptureEntityKind::BlockObject,
1652                           Flags);
1653   case QualType::PCK_Trivial:
1654   case QualType::PCK_VolatileTrivial: {
1655     if (!T->isObjCRetainableType())
1656       // For all other types, the memcpy is fine.
1657       return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1658 
1659     // Honor the inert __unsafe_unretained qualifier, which doesn't actually
1660     // make it into the type system.
1661     if (T->isObjCInertUnsafeUnretainedType())
1662       return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1663 
1664     // Special rules for ARC captures:
1665     Qualifiers QS = T.getQualifiers();
1666 
1667     // Non-ARC captures of retainable pointers are strong and
1668     // therefore require a call to _Block_object_assign.
1669     if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1670       return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1671 
1672     // Otherwise the memcpy is fine.
1673     return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1674   }
1675   }
1676   llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1677 }
1678 
1679 namespace {
1680 /// Release a __block variable.
1681 struct CallBlockRelease final : EHScopeStack::Cleanup {
1682   Address Addr;
1683   BlockFieldFlags FieldFlags;
1684   bool LoadBlockVarAddr, CanThrow;
1685 
1686   CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1687                    bool CT)
1688       : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1689         CanThrow(CT) {}
1690 
1691   void Emit(CodeGenFunction &CGF, Flags flags) override {
1692     llvm::Value *BlockVarAddr;
1693     if (LoadBlockVarAddr) {
1694       BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1695       BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1696     } else {
1697       BlockVarAddr = Addr.getPointer();
1698     }
1699 
1700     CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1701   }
1702 };
1703 } // end anonymous namespace
1704 
1705 /// Check if \p T is a C++ class that has a destructor that can throw.
1706 bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1707   if (const auto *RD = T->getAsCXXRecordDecl())
1708     if (const CXXDestructorDecl *DD = RD->getDestructor())
1709       return DD->getType()->castAs<FunctionProtoType>()->canThrow();
1710   return false;
1711 }
1712 
1713 // Return a string that has the information about a capture.
1714 static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
1715                                       CaptureStrKind StrKind,
1716                                       CharUnits BlockAlignment,
1717                                       CodeGenModule &CGM) {
1718   std::string Str;
1719   ASTContext &Ctx = CGM.getContext();
1720   const BlockDecl::Capture &CI = *Cap.Cap;
1721   QualType CaptureTy = CI.getVariable()->getType();
1722 
1723   BlockCaptureEntityKind Kind;
1724   BlockFieldFlags Flags;
1725 
1726   // CaptureStrKind::Merged should be passed only when the operations and the
1727   // flags are the same for copy and dispose.
1728   assert((StrKind != CaptureStrKind::Merged ||
1729           (Cap.CopyKind == Cap.DisposeKind &&
1730            Cap.CopyFlags == Cap.DisposeFlags)) &&
1731          "different operations and flags");
1732 
1733   if (StrKind == CaptureStrKind::DisposeHelper) {
1734     Kind = Cap.DisposeKind;
1735     Flags = Cap.DisposeFlags;
1736   } else {
1737     Kind = Cap.CopyKind;
1738     Flags = Cap.CopyFlags;
1739   }
1740 
1741   switch (Kind) {
1742   case BlockCaptureEntityKind::CXXRecord: {
1743     Str += "c";
1744     SmallString<256> TyStr;
1745     llvm::raw_svector_ostream Out(TyStr);
1746     CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
1747     Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1748     break;
1749   }
1750   case BlockCaptureEntityKind::ARCWeak:
1751     Str += "w";
1752     break;
1753   case BlockCaptureEntityKind::ARCStrong:
1754     Str += "s";
1755     break;
1756   case BlockCaptureEntityKind::BlockObject: {
1757     const VarDecl *Var = CI.getVariable();
1758     unsigned F = Flags.getBitMask();
1759     if (F & BLOCK_FIELD_IS_BYREF) {
1760       Str += "r";
1761       if (F & BLOCK_FIELD_IS_WEAK)
1762         Str += "w";
1763       else {
1764         // If CaptureStrKind::Merged is passed, check both the copy expression
1765         // and the destructor.
1766         if (StrKind != CaptureStrKind::DisposeHelper) {
1767           if (Ctx.getBlockVarCopyInit(Var).canThrow())
1768             Str += "c";
1769         }
1770         if (StrKind != CaptureStrKind::CopyHelper) {
1771           if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1772             Str += "d";
1773         }
1774       }
1775     } else {
1776       assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1777       if (F == BLOCK_FIELD_IS_BLOCK)
1778         Str += "b";
1779       else
1780         Str += "o";
1781     }
1782     break;
1783   }
1784   case BlockCaptureEntityKind::NonTrivialCStruct: {
1785     bool IsVolatile = CaptureTy.isVolatileQualified();
1786     CharUnits Alignment = BlockAlignment.alignmentAtOffset(Cap.getOffset());
1787 
1788     Str += "n";
1789     std::string FuncStr;
1790     if (StrKind == CaptureStrKind::DisposeHelper)
1791       FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1792           CaptureTy, Alignment, IsVolatile, Ctx);
1793     else
1794       // If CaptureStrKind::Merged is passed, use the copy constructor string.
1795       // It has all the information that the destructor string has.
1796       FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1797           CaptureTy, Alignment, IsVolatile, Ctx);
1798     // The underscore is necessary here because non-trivial copy constructor
1799     // and destructor strings can start with a number.
1800     Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1801     break;
1802   }
1803   case BlockCaptureEntityKind::None:
1804     break;
1805   }
1806 
1807   return Str;
1808 }
1809 
1810 static std::string getCopyDestroyHelperFuncName(
1811     const SmallVectorImpl<CGBlockInfo::Capture> &Captures,
1812     CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1813   assert((StrKind == CaptureStrKind::CopyHelper ||
1814           StrKind == CaptureStrKind::DisposeHelper) &&
1815          "unexpected CaptureStrKind");
1816   std::string Name = StrKind == CaptureStrKind::CopyHelper
1817                          ? "__copy_helper_block_"
1818                          : "__destroy_helper_block_";
1819   if (CGM.getLangOpts().Exceptions)
1820     Name += "e";
1821   if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1822     Name += "a";
1823   Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1824 
1825   for (auto &Cap : Captures) {
1826     if (Cap.isConstantOrTrivial())
1827       continue;
1828     Name += llvm::to_string(Cap.getOffset().getQuantity());
1829     Name += getBlockCaptureStr(Cap, StrKind, BlockAlignment, CGM);
1830   }
1831 
1832   return Name;
1833 }
1834 
1835 static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1836                                Address Field, QualType CaptureType,
1837                                BlockFieldFlags Flags, bool ForCopyHelper,
1838                                VarDecl *Var, CodeGenFunction &CGF) {
1839   bool EHOnly = ForCopyHelper;
1840 
1841   switch (CaptureKind) {
1842   case BlockCaptureEntityKind::CXXRecord:
1843   case BlockCaptureEntityKind::ARCWeak:
1844   case BlockCaptureEntityKind::NonTrivialCStruct:
1845   case BlockCaptureEntityKind::ARCStrong: {
1846     if (CaptureType.isDestructedType() &&
1847         (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1848       CodeGenFunction::Destroyer *Destroyer =
1849           CaptureKind == BlockCaptureEntityKind::ARCStrong
1850               ? CodeGenFunction::destroyARCStrongImprecise
1851               : CGF.getDestroyer(CaptureType.isDestructedType());
1852       CleanupKind Kind =
1853           EHOnly ? EHCleanup
1854                  : CGF.getCleanupKind(CaptureType.isDestructedType());
1855       CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1856     }
1857     break;
1858   }
1859   case BlockCaptureEntityKind::BlockObject: {
1860     if (!EHOnly || CGF.getLangOpts().Exceptions) {
1861       CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1862       // Calls to _Block_object_dispose along the EH path in the copy helper
1863       // function don't throw as newly-copied __block variables always have a
1864       // reference count of 2.
1865       bool CanThrow =
1866           !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1867       CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1868                             CanThrow);
1869     }
1870     break;
1871   }
1872   case BlockCaptureEntityKind::None:
1873     break;
1874   }
1875 }
1876 
1877 static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1878                                                llvm::Function *Fn,
1879                                                const CGFunctionInfo &FI,
1880                                                CodeGenModule &CGM) {
1881   if (CapturesNonExternalType) {
1882     CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1883   } else {
1884     Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1885     Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1886     CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
1887     CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1888   }
1889 }
1890 /// Generate the copy-helper function for a block closure object:
1891 ///   static void block_copy_helper(block_t *dst, block_t *src);
1892 /// The runtime will have previously initialized 'dst' by doing a
1893 /// bit-copy of 'src'.
1894 ///
1895 /// Note that this copies an entire block closure object to the heap;
1896 /// it should not be confused with a 'byref copy helper', which moves
1897 /// the contents of an individual __block variable to the heap.
1898 llvm::Constant *
1899 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1900   std::string FuncName = getCopyDestroyHelperFuncName(
1901       blockInfo.SortedCaptures, blockInfo.BlockAlign,
1902       CaptureStrKind::CopyHelper, CGM);
1903 
1904   if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
1905     return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
1906 
1907   ASTContext &C = getContext();
1908 
1909   QualType ReturnTy = C.VoidTy;
1910 
1911   FunctionArgList args;
1912   ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1913   args.push_back(&DstDecl);
1914   ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1915   args.push_back(&SrcDecl);
1916 
1917   const CGFunctionInfo &FI =
1918       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
1919 
1920   // FIXME: it would be nice if these were mergeable with things with
1921   // identical semantics.
1922   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1923 
1924   llvm::Function *Fn =
1925     llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1926                            FuncName, &CGM.getModule());
1927   if (CGM.supportsCOMDAT())
1928     Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
1929 
1930   SmallVector<QualType, 2> ArgTys;
1931   ArgTys.push_back(C.VoidPtrTy);
1932   ArgTys.push_back(C.VoidPtrTy);
1933 
1934   setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1935                                      CGM);
1936   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
1937   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1938 
1939   Address src = GetAddrOfLocalVar(&SrcDecl);
1940   src = Address(Builder.CreateLoad(src), Int8Ty, blockInfo.BlockAlign);
1941   src = Builder.CreateElementBitCast(src, blockInfo.StructureType,
1942                                      "block.source");
1943 
1944   Address dst = GetAddrOfLocalVar(&DstDecl);
1945   dst = Address(Builder.CreateLoad(dst), Int8Ty, blockInfo.BlockAlign);
1946   dst =
1947       Builder.CreateElementBitCast(dst, blockInfo.StructureType, "block.dest");
1948 
1949   for (auto &capture : blockInfo.SortedCaptures) {
1950     if (capture.isConstantOrTrivial())
1951       continue;
1952 
1953     const BlockDecl::Capture &CI = *capture.Cap;
1954     QualType captureType = CI.getVariable()->getType();
1955     BlockFieldFlags flags = capture.CopyFlags;
1956 
1957     unsigned index = capture.getIndex();
1958     Address srcField = Builder.CreateStructGEP(src, index);
1959     Address dstField = Builder.CreateStructGEP(dst, index);
1960 
1961     switch (capture.CopyKind) {
1962     case BlockCaptureEntityKind::CXXRecord:
1963       // If there's an explicit copy expression, we do that.
1964       assert(CI.getCopyExpr() && "copy expression for variable is missing");
1965       EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1966       break;
1967     case BlockCaptureEntityKind::ARCWeak:
1968       EmitARCCopyWeak(dstField, srcField);
1969       break;
1970     case BlockCaptureEntityKind::NonTrivialCStruct: {
1971       // If this is a C struct that requires non-trivial copy construction,
1972       // emit a call to its copy constructor.
1973       QualType varType = CI.getVariable()->getType();
1974       callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
1975                                  MakeAddrLValue(srcField, varType));
1976       break;
1977     }
1978     case BlockCaptureEntityKind::ARCStrong: {
1979       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1980       // At -O0, store null into the destination field (so that the
1981       // storeStrong doesn't over-release) and then call storeStrong.
1982       // This is a workaround to not having an initStrong call.
1983       if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1984         auto *ty = cast<llvm::PointerType>(srcValue->getType());
1985         llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1986         Builder.CreateStore(null, dstField);
1987         EmitARCStoreStrongCall(dstField, srcValue, true);
1988 
1989       // With optimization enabled, take advantage of the fact that
1990       // the blocks runtime guarantees a memcpy of the block data, and
1991       // just emit a retain of the src field.
1992       } else {
1993         EmitARCRetainNonBlock(srcValue);
1994 
1995         // Unless EH cleanup is required, we don't need this anymore, so kill
1996         // it. It's not quite worth the annoyance to avoid creating it in the
1997         // first place.
1998         if (!needsEHCleanup(captureType.isDestructedType()))
1999           cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
2000       }
2001       break;
2002     }
2003     case BlockCaptureEntityKind::BlockObject: {
2004       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2005       srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2006       llvm::Value *dstAddr =
2007           Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2008       llvm::Value *args[] = {
2009         dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2010       };
2011 
2012       if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2013         EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2014       else
2015         EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2016       break;
2017     }
2018     case BlockCaptureEntityKind::None:
2019       continue;
2020     }
2021 
2022     // Ensure that we destroy the copied object if an exception is thrown later
2023     // in the helper function.
2024     pushCaptureCleanup(capture.CopyKind, dstField, captureType, flags,
2025                        /*ForCopyHelper*/ true, CI.getVariable(), *this);
2026   }
2027 
2028   FinishFunction();
2029 
2030   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2031 }
2032 
2033 static BlockFieldFlags
2034 getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2035                                        QualType T) {
2036   BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2037   if (T->isBlockPointerType())
2038     Flags = BLOCK_FIELD_IS_BLOCK;
2039   return Flags;
2040 }
2041 
2042 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2043 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2044                                   const LangOptions &LangOpts) {
2045   if (CI.isEscapingByref()) {
2046     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2047     if (T.isObjCGCWeak())
2048       Flags |= BLOCK_FIELD_IS_WEAK;
2049     return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2050   }
2051 
2052   switch (T.isDestructedType()) {
2053   case QualType::DK_cxx_destructor:
2054     return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2055   case QualType::DK_objc_strong_lifetime:
2056     // Use objc_storeStrong for __strong direct captures; the
2057     // dynamic tools really like it when we do this.
2058     return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2059                           getBlockFieldFlagsForObjCObjectPointer(CI, T));
2060   case QualType::DK_objc_weak_lifetime:
2061     // Support __weak direct captures.
2062     return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2063                           getBlockFieldFlagsForObjCObjectPointer(CI, T));
2064   case QualType::DK_nontrivial_c_struct:
2065     return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2066                           BlockFieldFlags());
2067   case QualType::DK_none: {
2068     // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2069     // But honor the inert __unsafe_unretained qualifier, which doesn't actually
2070     // make it into the type system.
2071     if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2072         !LangOpts.ObjCAutoRefCount && !T->isObjCInertUnsafeUnretainedType())
2073       return std::make_pair(BlockCaptureEntityKind::BlockObject,
2074                             getBlockFieldFlagsForObjCObjectPointer(CI, T));
2075     // Otherwise, we have nothing to do.
2076     return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2077   }
2078   }
2079   llvm_unreachable("after exhaustive DestructionKind switch");
2080 }
2081 
2082 /// Generate the destroy-helper function for a block closure object:
2083 ///   static void block_destroy_helper(block_t *theBlock);
2084 ///
2085 /// Note that this destroys a heap-allocated block closure object;
2086 /// it should not be confused with a 'byref destroy helper', which
2087 /// destroys the heap-allocated contents of an individual __block
2088 /// variable.
2089 llvm::Constant *
2090 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2091   std::string FuncName = getCopyDestroyHelperFuncName(
2092       blockInfo.SortedCaptures, blockInfo.BlockAlign,
2093       CaptureStrKind::DisposeHelper, CGM);
2094 
2095   if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2096     return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2097 
2098   ASTContext &C = getContext();
2099 
2100   QualType ReturnTy = C.VoidTy;
2101 
2102   FunctionArgList args;
2103   ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2104   args.push_back(&SrcDecl);
2105 
2106   const CGFunctionInfo &FI =
2107       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2108 
2109   // FIXME: We'd like to put these into a mergable by content, with
2110   // internal linkage.
2111   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2112 
2113   llvm::Function *Fn =
2114     llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2115                            FuncName, &CGM.getModule());
2116   if (CGM.supportsCOMDAT())
2117     Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2118 
2119   SmallVector<QualType, 1> ArgTys;
2120   ArgTys.push_back(C.VoidPtrTy);
2121 
2122   setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2123                                      CGM);
2124   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
2125   markAsIgnoreThreadCheckingAtRuntime(Fn);
2126 
2127   auto AL = ApplyDebugLocation::CreateArtificial(*this);
2128 
2129   Address src = GetAddrOfLocalVar(&SrcDecl);
2130   src = Address(Builder.CreateLoad(src), Int8Ty, blockInfo.BlockAlign);
2131   src = Builder.CreateElementBitCast(src, blockInfo.StructureType, "block");
2132 
2133   CodeGenFunction::RunCleanupsScope cleanups(*this);
2134 
2135   for (auto &capture : blockInfo.SortedCaptures) {
2136     if (capture.isConstantOrTrivial())
2137       continue;
2138 
2139     const BlockDecl::Capture &CI = *capture.Cap;
2140     BlockFieldFlags flags = capture.DisposeFlags;
2141 
2142     Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
2143 
2144     pushCaptureCleanup(capture.DisposeKind, srcField,
2145                        CI.getVariable()->getType(), flags,
2146                        /*ForCopyHelper*/ false, CI.getVariable(), *this);
2147   }
2148 
2149   cleanups.ForceCleanup();
2150 
2151   FinishFunction();
2152 
2153   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2154 }
2155 
2156 namespace {
2157 
2158 /// Emits the copy/dispose helper functions for a __block object of id type.
2159 class ObjectByrefHelpers final : public BlockByrefHelpers {
2160   BlockFieldFlags Flags;
2161 
2162 public:
2163   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2164     : BlockByrefHelpers(alignment), Flags(flags) {}
2165 
2166   void emitCopy(CodeGenFunction &CGF, Address destField,
2167                 Address srcField) override {
2168     destField = CGF.Builder.CreateElementBitCast(destField, CGF.Int8Ty);
2169 
2170     srcField = CGF.Builder.CreateElementBitCast(srcField, CGF.Int8PtrTy);
2171     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2172 
2173     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2174 
2175     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2176     llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
2177 
2178     llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
2179     CGF.EmitNounwindRuntimeCall(fn, args);
2180   }
2181 
2182   void emitDispose(CodeGenFunction &CGF, Address field) override {
2183     field = CGF.Builder.CreateElementBitCast(field, CGF.Int8PtrTy);
2184     llvm::Value *value = CGF.Builder.CreateLoad(field);
2185 
2186     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2187   }
2188 
2189   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2190     id.AddInteger(Flags.getBitMask());
2191   }
2192 };
2193 
2194 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2195 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2196 public:
2197   ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2198 
2199   void emitCopy(CodeGenFunction &CGF, Address destField,
2200                 Address srcField) override {
2201     CGF.EmitARCMoveWeak(destField, srcField);
2202   }
2203 
2204   void emitDispose(CodeGenFunction &CGF, Address field) override {
2205     CGF.EmitARCDestroyWeak(field);
2206   }
2207 
2208   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2209     // 0 is distinguishable from all pointers and byref flags
2210     id.AddInteger(0);
2211   }
2212 };
2213 
2214 /// Emits the copy/dispose helpers for an ARC __block __strong variable
2215 /// that's not of block-pointer type.
2216 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2217 public:
2218   ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2219 
2220   void emitCopy(CodeGenFunction &CGF, Address destField,
2221                 Address srcField) override {
2222     // Do a "move" by copying the value and then zeroing out the old
2223     // variable.
2224 
2225     llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2226 
2227     llvm::Value *null =
2228       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2229 
2230     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2231       CGF.Builder.CreateStore(null, destField);
2232       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2233       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2234       return;
2235     }
2236     CGF.Builder.CreateStore(value, destField);
2237     CGF.Builder.CreateStore(null, srcField);
2238   }
2239 
2240   void emitDispose(CodeGenFunction &CGF, Address field) override {
2241     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2242   }
2243 
2244   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2245     // 1 is distinguishable from all pointers and byref flags
2246     id.AddInteger(1);
2247   }
2248 };
2249 
2250 /// Emits the copy/dispose helpers for an ARC __block __strong
2251 /// variable that's of block-pointer type.
2252 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2253 public:
2254   ARCStrongBlockByrefHelpers(CharUnits alignment)
2255     : BlockByrefHelpers(alignment) {}
2256 
2257   void emitCopy(CodeGenFunction &CGF, Address destField,
2258                 Address srcField) override {
2259     // Do the copy with objc_retainBlock; that's all that
2260     // _Block_object_assign would do anyway, and we'd have to pass the
2261     // right arguments to make sure it doesn't get no-op'ed.
2262     llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2263     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2264     CGF.Builder.CreateStore(copy, destField);
2265   }
2266 
2267   void emitDispose(CodeGenFunction &CGF, Address field) override {
2268     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2269   }
2270 
2271   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2272     // 2 is distinguishable from all pointers and byref flags
2273     id.AddInteger(2);
2274   }
2275 };
2276 
2277 /// Emits the copy/dispose helpers for a __block variable with a
2278 /// nontrivial copy constructor or destructor.
2279 class CXXByrefHelpers final : public BlockByrefHelpers {
2280   QualType VarType;
2281   const Expr *CopyExpr;
2282 
2283 public:
2284   CXXByrefHelpers(CharUnits alignment, QualType type,
2285                   const Expr *copyExpr)
2286     : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2287 
2288   bool needsCopy() const override { return CopyExpr != nullptr; }
2289   void emitCopy(CodeGenFunction &CGF, Address destField,
2290                 Address srcField) override {
2291     if (!CopyExpr) return;
2292     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2293   }
2294 
2295   void emitDispose(CodeGenFunction &CGF, Address field) override {
2296     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2297     CGF.PushDestructorCleanup(VarType, field);
2298     CGF.PopCleanupBlocks(cleanupDepth);
2299   }
2300 
2301   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2302     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2303   }
2304 };
2305 
2306 /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2307 /// C struct.
2308 class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2309   QualType VarType;
2310 
2311 public:
2312   NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2313     : BlockByrefHelpers(alignment), VarType(type) {}
2314 
2315   void emitCopy(CodeGenFunction &CGF, Address destField,
2316                 Address srcField) override {
2317     CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2318                                    CGF.MakeAddrLValue(srcField, VarType));
2319   }
2320 
2321   bool needsDispose() const override {
2322     return VarType.isDestructedType();
2323   }
2324 
2325   void emitDispose(CodeGenFunction &CGF, Address field) override {
2326     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2327     CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2328     CGF.PopCleanupBlocks(cleanupDepth);
2329   }
2330 
2331   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2332     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2333   }
2334 };
2335 } // end anonymous namespace
2336 
2337 static llvm::Constant *
2338 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2339                         BlockByrefHelpers &generator) {
2340   ASTContext &Context = CGF.getContext();
2341 
2342   QualType ReturnTy = Context.VoidTy;
2343 
2344   FunctionArgList args;
2345   ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2346   args.push_back(&Dst);
2347 
2348   ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2349   args.push_back(&Src);
2350 
2351   const CGFunctionInfo &FI =
2352       CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2353 
2354   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2355 
2356   // FIXME: We'd like to put these into a mergable by content, with
2357   // internal linkage.
2358   llvm::Function *Fn =
2359     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2360                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
2361 
2362   SmallVector<QualType, 2> ArgTys;
2363   ArgTys.push_back(Context.VoidPtrTy);
2364   ArgTys.push_back(Context.VoidPtrTy);
2365 
2366   CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2367 
2368   CGF.StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
2369     // Create a scope with an artificial location for the body of this function.
2370   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
2371 
2372   if (generator.needsCopy()) {
2373     // dst->x
2374     Address destField = CGF.GetAddrOfLocalVar(&Dst);
2375     destField = Address(CGF.Builder.CreateLoad(destField), CGF.Int8Ty,
2376                         byrefInfo.ByrefAlignment);
2377     destField = CGF.Builder.CreateElementBitCast(destField, byrefInfo.Type);
2378     destField =
2379         CGF.emitBlockByrefAddress(destField, byrefInfo, false, "dest-object");
2380 
2381     // src->x
2382     Address srcField = CGF.GetAddrOfLocalVar(&Src);
2383     srcField = Address(CGF.Builder.CreateLoad(srcField), CGF.Int8Ty,
2384                        byrefInfo.ByrefAlignment);
2385     srcField = CGF.Builder.CreateElementBitCast(srcField, byrefInfo.Type);
2386     srcField =
2387         CGF.emitBlockByrefAddress(srcField, byrefInfo, false, "src-object");
2388 
2389     generator.emitCopy(CGF, destField, srcField);
2390   }
2391 
2392   CGF.FinishFunction();
2393 
2394   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2395 }
2396 
2397 /// Build the copy helper for a __block variable.
2398 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2399                                             const BlockByrefInfo &byrefInfo,
2400                                             BlockByrefHelpers &generator) {
2401   CodeGenFunction CGF(CGM);
2402   return generateByrefCopyHelper(CGF, byrefInfo, generator);
2403 }
2404 
2405 /// Generate code for a __block variable's dispose helper.
2406 static llvm::Constant *
2407 generateByrefDisposeHelper(CodeGenFunction &CGF,
2408                            const BlockByrefInfo &byrefInfo,
2409                            BlockByrefHelpers &generator) {
2410   ASTContext &Context = CGF.getContext();
2411   QualType R = Context.VoidTy;
2412 
2413   FunctionArgList args;
2414   ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2415                         ImplicitParamDecl::Other);
2416   args.push_back(&Src);
2417 
2418   const CGFunctionInfo &FI =
2419     CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2420 
2421   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2422 
2423   // FIXME: We'd like to put these into a mergable by content, with
2424   // internal linkage.
2425   llvm::Function *Fn =
2426     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2427                            "__Block_byref_object_dispose_",
2428                            &CGF.CGM.getModule());
2429 
2430   SmallVector<QualType, 1> ArgTys;
2431   ArgTys.push_back(Context.VoidPtrTy);
2432 
2433   CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2434 
2435   CGF.StartFunction(GlobalDecl(), R, Fn, FI, args);
2436     // Create a scope with an artificial location for the body of this function.
2437   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
2438 
2439   if (generator.needsDispose()) {
2440     Address addr = CGF.GetAddrOfLocalVar(&Src);
2441     addr = Address(CGF.Builder.CreateLoad(addr), CGF.Int8Ty,
2442                    byrefInfo.ByrefAlignment);
2443     addr = CGF.Builder.CreateElementBitCast(addr, byrefInfo.Type);
2444     addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2445 
2446     generator.emitDispose(CGF, addr);
2447   }
2448 
2449   CGF.FinishFunction();
2450 
2451   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2452 }
2453 
2454 /// Build the dispose helper for a __block variable.
2455 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2456                                                const BlockByrefInfo &byrefInfo,
2457                                                BlockByrefHelpers &generator) {
2458   CodeGenFunction CGF(CGM);
2459   return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2460 }
2461 
2462 /// Lazily build the copy and dispose helpers for a __block variable
2463 /// with the given information.
2464 template <class T>
2465 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2466                             T &&generator) {
2467   llvm::FoldingSetNodeID id;
2468   generator.Profile(id);
2469 
2470   void *insertPos;
2471   BlockByrefHelpers *node
2472     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2473   if (node) return static_cast<T*>(node);
2474 
2475   generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2476   generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2477 
2478   T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2479   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2480   return copy;
2481 }
2482 
2483 /// Build the copy and dispose helpers for the given __block variable
2484 /// emission.  Places the helpers in the global cache.  Returns null
2485 /// if no helpers are required.
2486 BlockByrefHelpers *
2487 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2488                                    const AutoVarEmission &emission) {
2489   const VarDecl &var = *emission.Variable;
2490   assert(var.isEscapingByref() &&
2491          "only escaping __block variables need byref helpers");
2492 
2493   QualType type = var.getType();
2494 
2495   auto &byrefInfo = getBlockByrefInfo(&var);
2496 
2497   // The alignment we care about for the purposes of uniquing byref
2498   // helpers is the alignment of the actual byref value field.
2499   CharUnits valueAlignment =
2500     byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2501 
2502   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2503     const Expr *copyExpr =
2504         CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2505     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2506 
2507     return ::buildByrefHelpers(
2508         CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2509   }
2510 
2511   // If type is a non-trivial C struct type that is non-trivial to
2512   // destructly move or destroy, build the copy and dispose helpers.
2513   if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2514       type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2515     return ::buildByrefHelpers(
2516         CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2517 
2518   // Otherwise, if we don't have a retainable type, there's nothing to do.
2519   // that the runtime does extra copies.
2520   if (!type->isObjCRetainableType()) return nullptr;
2521 
2522   Qualifiers qs = type.getQualifiers();
2523 
2524   // If we have lifetime, that dominates.
2525   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2526     switch (lifetime) {
2527     case Qualifiers::OCL_None: llvm_unreachable("impossible");
2528 
2529     // These are just bits as far as the runtime is concerned.
2530     case Qualifiers::OCL_ExplicitNone:
2531     case Qualifiers::OCL_Autoreleasing:
2532       return nullptr;
2533 
2534     // Tell the runtime that this is ARC __weak, called by the
2535     // byref routines.
2536     case Qualifiers::OCL_Weak:
2537       return ::buildByrefHelpers(CGM, byrefInfo,
2538                                  ARCWeakByrefHelpers(valueAlignment));
2539 
2540     // ARC __strong __block variables need to be retained.
2541     case Qualifiers::OCL_Strong:
2542       // Block pointers need to be copied, and there's no direct
2543       // transfer possible.
2544       if (type->isBlockPointerType()) {
2545         return ::buildByrefHelpers(CGM, byrefInfo,
2546                                    ARCStrongBlockByrefHelpers(valueAlignment));
2547 
2548       // Otherwise, we transfer ownership of the retain from the stack
2549       // to the heap.
2550       } else {
2551         return ::buildByrefHelpers(CGM, byrefInfo,
2552                                    ARCStrongByrefHelpers(valueAlignment));
2553       }
2554     }
2555     llvm_unreachable("fell out of lifetime switch!");
2556   }
2557 
2558   BlockFieldFlags flags;
2559   if (type->isBlockPointerType()) {
2560     flags |= BLOCK_FIELD_IS_BLOCK;
2561   } else if (CGM.getContext().isObjCNSObjectType(type) ||
2562              type->isObjCObjectPointerType()) {
2563     flags |= BLOCK_FIELD_IS_OBJECT;
2564   } else {
2565     return nullptr;
2566   }
2567 
2568   if (type.isObjCGCWeak())
2569     flags |= BLOCK_FIELD_IS_WEAK;
2570 
2571   return ::buildByrefHelpers(CGM, byrefInfo,
2572                              ObjectByrefHelpers(valueAlignment, flags));
2573 }
2574 
2575 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2576                                                const VarDecl *var,
2577                                                bool followForward) {
2578   auto &info = getBlockByrefInfo(var);
2579   return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2580 }
2581 
2582 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2583                                                const BlockByrefInfo &info,
2584                                                bool followForward,
2585                                                const llvm::Twine &name) {
2586   // Chase the forwarding address if requested.
2587   if (followForward) {
2588     Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
2589     baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.Type,
2590                        info.ByrefAlignment);
2591   }
2592 
2593   return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
2594 }
2595 
2596 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2597 ///   into:
2598 ///
2599 ///      struct {
2600 ///        void *__isa;
2601 ///        void *__forwarding;
2602 ///        int32_t __flags;
2603 ///        int32_t __size;
2604 ///        void *__copy_helper;       // only if needed
2605 ///        void *__destroy_helper;    // only if needed
2606 ///        void *__byref_variable_layout;// only if needed
2607 ///        char padding[X];           // only if needed
2608 ///        T x;
2609 ///      } x
2610 ///
2611 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2612   auto it = BlockByrefInfos.find(D);
2613   if (it != BlockByrefInfos.end())
2614     return it->second;
2615 
2616   llvm::StructType *byrefType =
2617     llvm::StructType::create(getLLVMContext(),
2618                              "struct.__block_byref_" + D->getNameAsString());
2619 
2620   QualType Ty = D->getType();
2621 
2622   CharUnits size;
2623   SmallVector<llvm::Type *, 8> types;
2624 
2625   // void *__isa;
2626   types.push_back(Int8PtrTy);
2627   size += getPointerSize();
2628 
2629   // void *__forwarding;
2630   types.push_back(llvm::PointerType::getUnqual(byrefType));
2631   size += getPointerSize();
2632 
2633   // int32_t __flags;
2634   types.push_back(Int32Ty);
2635   size += CharUnits::fromQuantity(4);
2636 
2637   // int32_t __size;
2638   types.push_back(Int32Ty);
2639   size += CharUnits::fromQuantity(4);
2640 
2641   // Note that this must match *exactly* the logic in buildByrefHelpers.
2642   bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2643   if (hasCopyAndDispose) {
2644     /// void *__copy_helper;
2645     types.push_back(Int8PtrTy);
2646     size += getPointerSize();
2647 
2648     /// void *__destroy_helper;
2649     types.push_back(Int8PtrTy);
2650     size += getPointerSize();
2651   }
2652 
2653   bool HasByrefExtendedLayout = false;
2654   Qualifiers::ObjCLifetime Lifetime = Qualifiers::OCL_None;
2655   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2656       HasByrefExtendedLayout) {
2657     /// void *__byref_variable_layout;
2658     types.push_back(Int8PtrTy);
2659     size += CharUnits::fromQuantity(PointerSizeInBytes);
2660   }
2661 
2662   // T x;
2663   llvm::Type *varTy = ConvertTypeForMem(Ty);
2664 
2665   bool packed = false;
2666   CharUnits varAlign = getContext().getDeclAlign(D);
2667   CharUnits varOffset = size.alignTo(varAlign);
2668 
2669   // We may have to insert padding.
2670   if (varOffset != size) {
2671     llvm::Type *paddingTy =
2672       llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2673 
2674     types.push_back(paddingTy);
2675     size = varOffset;
2676 
2677   // Conversely, we might have to prevent LLVM from inserting padding.
2678   } else if (CGM.getDataLayout().getABITypeAlignment(varTy) >
2679              uint64_t(varAlign.getQuantity())) {
2680     packed = true;
2681   }
2682   types.push_back(varTy);
2683 
2684   byrefType->setBody(types, packed);
2685 
2686   BlockByrefInfo info;
2687   info.Type = byrefType;
2688   info.FieldIndex = types.size() - 1;
2689   info.FieldOffset = varOffset;
2690   info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2691 
2692   auto pair = BlockByrefInfos.insert({D, info});
2693   assert(pair.second && "info was inserted recursively?");
2694   return pair.first->second;
2695 }
2696 
2697 /// Initialize the structural components of a __block variable, i.e.
2698 /// everything but the actual object.
2699 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2700   // Find the address of the local.
2701   Address addr = emission.Addr;
2702 
2703   // That's an alloca of the byref structure type.
2704   llvm::StructType *byrefType = cast<llvm::StructType>(addr.getElementType());
2705 
2706   unsigned nextHeaderIndex = 0;
2707   CharUnits nextHeaderOffset;
2708   auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2709                               const Twine &name) {
2710     auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
2711     Builder.CreateStore(value, fieldAddr);
2712 
2713     nextHeaderIndex++;
2714     nextHeaderOffset += fieldSize;
2715   };
2716 
2717   // Build the byref helpers if necessary.  This is null if we don't need any.
2718   BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2719 
2720   const VarDecl &D = *emission.Variable;
2721   QualType type = D.getType();
2722 
2723   bool HasByrefExtendedLayout = false;
2724   Qualifiers::ObjCLifetime ByrefLifetime = Qualifiers::OCL_None;
2725   bool ByRefHasLifetime =
2726     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2727 
2728   llvm::Value *V;
2729 
2730   // Initialize the 'isa', which is just 0 or 1.
2731   int isa = 0;
2732   if (type.isObjCGCWeak())
2733     isa = 1;
2734   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2735   storeHeaderField(V, getPointerSize(), "byref.isa");
2736 
2737   // Store the address of the variable into its own forwarding pointer.
2738   storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2739 
2740   // Blocks ABI:
2741   //   c) the flags field is set to either 0 if no helper functions are
2742   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2743   BlockFlags flags;
2744   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2745   if (ByRefHasLifetime) {
2746     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2747       else switch (ByrefLifetime) {
2748         case Qualifiers::OCL_Strong:
2749           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2750           break;
2751         case Qualifiers::OCL_Weak:
2752           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2753           break;
2754         case Qualifiers::OCL_ExplicitNone:
2755           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2756           break;
2757         case Qualifiers::OCL_None:
2758           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2759             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2760           break;
2761         default:
2762           break;
2763       }
2764     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2765       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2766       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2767         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2768       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2769         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2770         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2771           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2772         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2773           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2774         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2775           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2776         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2777           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2778         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2779           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2780       }
2781       printf("\n");
2782     }
2783   }
2784   storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2785                    getIntSize(), "byref.flags");
2786 
2787   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2788   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2789   storeHeaderField(V, getIntSize(), "byref.size");
2790 
2791   if (helpers) {
2792     storeHeaderField(helpers->CopyHelper, getPointerSize(),
2793                      "byref.copyHelper");
2794     storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2795                      "byref.disposeHelper");
2796   }
2797 
2798   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2799     auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2800     storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2801   }
2802 }
2803 
2804 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2805                                         bool CanThrow) {
2806   llvm::FunctionCallee F = CGM.getBlockObjectDispose();
2807   llvm::Value *args[] = {
2808     Builder.CreateBitCast(V, Int8PtrTy),
2809     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2810   };
2811 
2812   if (CanThrow)
2813     EmitRuntimeCallOrInvoke(F, args);
2814   else
2815     EmitNounwindRuntimeCall(F, args);
2816 }
2817 
2818 void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2819                                         BlockFieldFlags Flags,
2820                                         bool LoadBlockVarAddr, bool CanThrow) {
2821   EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2822                                         CanThrow);
2823 }
2824 
2825 /// Adjust the declaration of something from the blocks API.
2826 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2827                                          llvm::Constant *C) {
2828   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2829 
2830   if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2831     IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2832     TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2833     DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2834 
2835     assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2836             isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2837            "expected Function or GlobalVariable");
2838 
2839     const NamedDecl *ND = nullptr;
2840     for (const auto *Result : DC->lookup(&II))
2841       if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2842           (ND = dyn_cast<VarDecl>(Result)))
2843         break;
2844 
2845     // TODO: support static blocks runtime
2846     if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2847       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2848       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2849     } else {
2850       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2851       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2852     }
2853   }
2854 
2855   if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2856       GV->hasExternalLinkage())
2857     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2858 
2859   CGM.setDSOLocal(GV);
2860 }
2861 
2862 llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
2863   if (BlockObjectDispose)
2864     return BlockObjectDispose;
2865 
2866   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2867   llvm::FunctionType *fty
2868     = llvm::FunctionType::get(VoidTy, args, false);
2869   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2870   configureBlocksRuntimeObject(
2871       *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
2872   return BlockObjectDispose;
2873 }
2874 
2875 llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
2876   if (BlockObjectAssign)
2877     return BlockObjectAssign;
2878 
2879   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2880   llvm::FunctionType *fty
2881     = llvm::FunctionType::get(VoidTy, args, false);
2882   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2883   configureBlocksRuntimeObject(
2884       *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
2885   return BlockObjectAssign;
2886 }
2887 
2888 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2889   if (NSConcreteGlobalBlock)
2890     return NSConcreteGlobalBlock;
2891 
2892   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal(
2893       "_NSConcreteGlobalBlock", Int8PtrTy, LangAS::Default, nullptr);
2894   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2895   return NSConcreteGlobalBlock;
2896 }
2897 
2898 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2899   if (NSConcreteStackBlock)
2900     return NSConcreteStackBlock;
2901 
2902   NSConcreteStackBlock = GetOrCreateLLVMGlobal(
2903       "_NSConcreteStackBlock", Int8PtrTy, LangAS::Default, nullptr);
2904   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2905   return NSConcreteStackBlock;
2906 }
2907