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