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