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