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       // Since a __block variable cannot be captured by lambdas, its type and
561       // the capture field type should always match.
562       assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
563              "capture type differs from the variable type");
564       layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
565                                         Qualifiers::OCL_None, &CI,
566                                         CGM.VoidPtrTy, variable->getType()));
567       continue;
568     }
569 
570     // Otherwise, build a layout chunk with the size and alignment of
571     // the declaration.
572     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
573       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
574       continue;
575     }
576 
577     QualType VT = getCaptureFieldType(*CGF, CI);
578 
579     // If we have a lifetime qualifier, honor it for capture purposes.
580     // That includes *not* copying it if it's __unsafe_unretained.
581     Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
582     if (lifetime) {
583       switch (lifetime) {
584       case Qualifiers::OCL_None: llvm_unreachable("impossible");
585       case Qualifiers::OCL_ExplicitNone:
586       case Qualifiers::OCL_Autoreleasing:
587         break;
588 
589       case Qualifiers::OCL_Strong:
590       case Qualifiers::OCL_Weak:
591         info.NeedsCopyDispose = true;
592       }
593 
594     // Block pointers require copy/dispose.  So do Objective-C pointers.
595     } else if (VT->isObjCRetainableType()) {
596       // But honor the inert __unsafe_unretained qualifier, which doesn't
597       // actually make it into the type system.
598        if (VT->isObjCInertUnsafeUnretainedType()) {
599         lifetime = Qualifiers::OCL_ExplicitNone;
600       } else {
601         info.NeedsCopyDispose = true;
602         // used for mrr below.
603         lifetime = Qualifiers::OCL_Strong;
604       }
605 
606     // So do types that require non-trivial copy construction.
607     } else if (CI.hasCopyExpr()) {
608       info.NeedsCopyDispose = true;
609       info.HasCXXObject = true;
610       if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
611         info.CapturesNonExternalType = true;
612 
613     // So do C structs that require non-trivial copy construction or
614     // destruction.
615     } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
616                VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
617       info.NeedsCopyDispose = true;
618 
619     // And so do types with destructors.
620     } else if (CGM.getLangOpts().CPlusPlus) {
621       if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
622         if (!record->hasTrivialDestructor()) {
623           info.HasCXXObject = true;
624           info.NeedsCopyDispose = true;
625           if (!record->isExternallyVisible())
626             info.CapturesNonExternalType = true;
627         }
628       }
629     }
630 
631     CharUnits size = C.getTypeSizeInChars(VT);
632     CharUnits align = C.getDeclAlign(variable);
633 
634     maxFieldAlign = std::max(maxFieldAlign, align);
635 
636     llvm::Type *llvmType =
637       CGM.getTypes().ConvertTypeForMem(VT);
638 
639     layout.push_back(
640         BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
641   }
642 
643   // If that was everything, we're done here.
644   if (layout.empty()) {
645     info.StructureType =
646       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
647     info.CanBeGlobal = true;
648     return;
649   }
650 
651   // Sort the layout by alignment.  We have to use a stable sort here
652   // to get reproducible results.  There should probably be an
653   // llvm::array_pod_stable_sort.
654   std::stable_sort(layout.begin(), layout.end());
655 
656   // Needed for blocks layout info.
657   info.BlockHeaderForcedGapOffset = info.BlockSize;
658   info.BlockHeaderForcedGapSize = CharUnits::Zero();
659 
660   CharUnits &blockSize = info.BlockSize;
661   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
662 
663   // Assuming that the first byte in the header is maximally aligned,
664   // get the alignment of the first byte following the header.
665   CharUnits endAlign = getLowBit(blockSize);
666 
667   // If the end of the header isn't satisfactorily aligned for the
668   // maximum thing, look for things that are okay with the header-end
669   // alignment, and keep appending them until we get something that's
670   // aligned right.  This algorithm is only guaranteed optimal if
671   // that condition is satisfied at some point; otherwise we can get
672   // things like:
673   //   header                 // next byte has alignment 4
674   //   something_with_size_5; // next byte has alignment 1
675   //   something_with_alignment_8;
676   // which has 7 bytes of padding, as opposed to the naive solution
677   // which might have less (?).
678   if (endAlign < maxFieldAlign) {
679     SmallVectorImpl<BlockLayoutChunk>::iterator
680       li = layout.begin() + 1, le = layout.end();
681 
682     // Look for something that the header end is already
683     // satisfactorily aligned for.
684     for (; li != le && endAlign < li->Alignment; ++li)
685       ;
686 
687     // If we found something that's naturally aligned for the end of
688     // the header, keep adding things...
689     if (li != le) {
690       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
691       for (; li != le; ++li) {
692         assert(endAlign >= li->Alignment);
693 
694         li->setIndex(info, elementTypes.size(), blockSize);
695         elementTypes.push_back(li->Type);
696         blockSize += li->Size;
697         endAlign = getLowBit(blockSize);
698 
699         // ...until we get to the alignment of the maximum field.
700         if (endAlign >= maxFieldAlign) {
701           break;
702         }
703       }
704       // Don't re-append everything we just appended.
705       layout.erase(first, li);
706     }
707   }
708 
709   assert(endAlign == getLowBit(blockSize));
710 
711   // At this point, we just have to add padding if the end align still
712   // isn't aligned right.
713   if (endAlign < maxFieldAlign) {
714     CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
715     CharUnits padding = newBlockSize - blockSize;
716 
717     // If we haven't yet added any fields, remember that there was an
718     // initial gap; this need to go into the block layout bit map.
719     if (blockSize == info.BlockHeaderForcedGapOffset) {
720       info.BlockHeaderForcedGapSize = padding;
721     }
722 
723     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
724                                                 padding.getQuantity()));
725     blockSize = newBlockSize;
726     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
727   }
728 
729   assert(endAlign >= maxFieldAlign);
730   assert(endAlign == getLowBit(blockSize));
731   // Slam everything else on now.  This works because they have
732   // strictly decreasing alignment and we expect that size is always a
733   // multiple of alignment.
734   for (SmallVectorImpl<BlockLayoutChunk>::iterator
735          li = layout.begin(), le = layout.end(); li != le; ++li) {
736     if (endAlign < li->Alignment) {
737       // size may not be multiple of alignment. This can only happen with
738       // an over-aligned variable. We will be adding a padding field to
739       // make the size be multiple of alignment.
740       CharUnits padding = li->Alignment - endAlign;
741       elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
742                                                   padding.getQuantity()));
743       blockSize += padding;
744       endAlign = getLowBit(blockSize);
745     }
746     assert(endAlign >= li->Alignment);
747     li->setIndex(info, elementTypes.size(), blockSize);
748     elementTypes.push_back(li->Type);
749     blockSize += li->Size;
750     endAlign = getLowBit(blockSize);
751   }
752 
753   info.StructureType =
754     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
755 }
756 
757 /// Enter the scope of a block.  This should be run at the entrance to
758 /// a full-expression so that the block's cleanups are pushed at the
759 /// right place in the stack.
760 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
761   assert(CGF.HaveInsertPoint());
762 
763   // Allocate the block info and place it at the head of the list.
764   CGBlockInfo &blockInfo =
765     *new CGBlockInfo(block, CGF.CurFn->getName());
766   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
767   CGF.FirstBlockInfo = &blockInfo;
768 
769   // Compute information about the layout, etc., of this block,
770   // pushing cleanups as necessary.
771   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
772 
773   // Nothing else to do if it can be global.
774   if (blockInfo.CanBeGlobal) return;
775 
776   // Make the allocation for the block.
777   blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
778                                                 blockInfo.BlockAlign, "block");
779 
780   // If there are cleanups to emit, enter them (but inactive).
781   if (!blockInfo.NeedsCopyDispose) return;
782 
783   // Walk through the captures (in order) and find the ones not
784   // captured by constant.
785   for (const auto &CI : block->captures()) {
786     // Ignore __block captures; there's nothing special in the
787     // on-stack block that we need to do for them.
788     if (CI.isByRef()) continue;
789 
790     // Ignore variables that are constant-captured.
791     const VarDecl *variable = CI.getVariable();
792     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
793     if (capture.isConstant()) continue;
794 
795     // Ignore objects that aren't destructed.
796     QualType VT = getCaptureFieldType(CGF, CI);
797     QualType::DestructionKind dtorKind = VT.isDestructedType();
798     if (dtorKind == QualType::DK_none) continue;
799 
800     CodeGenFunction::Destroyer *destroyer;
801 
802     // Block captures count as local values and have imprecise semantics.
803     // They also can't be arrays, so need to worry about that.
804     //
805     // For const-qualified captures, emit clang.arc.use to ensure the captured
806     // object doesn't get released while we are still depending on its validity
807     // within the block.
808     if (VT.isConstQualified() &&
809         VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
810         CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
811       assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
812              "expected ObjC ARC to be enabled");
813       destroyer = CodeGenFunction::emitARCIntrinsicUse;
814     } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
815       destroyer = CodeGenFunction::destroyARCStrongImprecise;
816     } else {
817       destroyer = CGF.getDestroyer(dtorKind);
818     }
819 
820     // GEP down to the address.
821     Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
822                                                capture.getIndex(),
823                                                capture.getOffset());
824 
825     // We can use that GEP as the dominating IP.
826     if (!blockInfo.DominatingIP)
827       blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
828 
829     CleanupKind cleanupKind = InactiveNormalCleanup;
830     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
831     if (useArrayEHCleanup)
832       cleanupKind = InactiveNormalAndEHCleanup;
833 
834     CGF.pushDestroy(cleanupKind, addr, VT,
835                     destroyer, useArrayEHCleanup);
836 
837     // Remember where that cleanup was.
838     capture.setCleanup(CGF.EHStack.stable_begin());
839   }
840 }
841 
842 /// Enter a full-expression with a non-trivial number of objects to
843 /// clean up.  This is in this file because, at the moment, the only
844 /// kind of cleanup object is a BlockDecl*.
845 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
846   assert(E->getNumObjects() != 0);
847   for (const ExprWithCleanups::CleanupObject &C : E->getObjects())
848     enterBlockScope(*this, C);
849 }
850 
851 /// Find the layout for the given block in a linked list and remove it.
852 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
853                                            const BlockDecl *block) {
854   while (true) {
855     assert(head && *head);
856     CGBlockInfo *cur = *head;
857 
858     // If this is the block we're looking for, splice it out of the list.
859     if (cur->getBlockDecl() == block) {
860       *head = cur->NextBlockInfo;
861       return cur;
862     }
863 
864     head = &cur->NextBlockInfo;
865   }
866 }
867 
868 /// Destroy a chain of block layouts.
869 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
870   assert(head && "destroying an empty chain");
871   do {
872     CGBlockInfo *cur = head;
873     head = cur->NextBlockInfo;
874     delete cur;
875   } while (head != nullptr);
876 }
877 
878 /// Emit a block literal expression in the current function.
879 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
880   // If the block has no captures, we won't have a pre-computed
881   // layout for it.
882   if (!blockExpr->getBlockDecl()->hasCaptures()) {
883     // The block literal is emitted as a global variable, and the block invoke
884     // function has to be extracted from its initializer.
885     if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
886       return Block;
887     }
888     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
889     computeBlockInfo(CGM, this, blockInfo);
890     blockInfo.BlockExpression = blockExpr;
891     return EmitBlockLiteral(blockInfo);
892   }
893 
894   // Find the block info for this block and take ownership of it.
895   std::unique_ptr<CGBlockInfo> blockInfo;
896   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
897                                          blockExpr->getBlockDecl()));
898 
899   blockInfo->BlockExpression = blockExpr;
900   return EmitBlockLiteral(*blockInfo);
901 }
902 
903 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
904   bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
905   // Using the computed layout, generate the actual block function.
906   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
907   CodeGenFunction BlockCGF{CGM, true};
908   BlockCGF.SanOpts = SanOpts;
909   auto *InvokeFn = BlockCGF.GenerateBlockFunction(
910       CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
911 
912   // If there is nothing to capture, we can emit this as a global block.
913   if (blockInfo.CanBeGlobal)
914     return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
915 
916   // Otherwise, we have to emit this as a local block.
917 
918   Address blockAddr = blockInfo.LocalAddress;
919   assert(blockAddr.isValid() && "block has no address!");
920 
921   llvm::Constant *isa;
922   llvm::Constant *descriptor;
923   BlockFlags flags;
924   if (!IsOpenCL) {
925     // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
926     // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
927     // block just returns the original block and releasing it is a no-op.
928     llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
929                                    ? CGM.getNSConcreteGlobalBlock()
930                                    : CGM.getNSConcreteStackBlock();
931     isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
932 
933     // Build the block descriptor.
934     descriptor = buildBlockDescriptor(CGM, blockInfo);
935 
936     // Compute the initial on-stack block flags.
937     flags = BLOCK_HAS_SIGNATURE;
938     if (blockInfo.HasCapturedVariableLayout)
939       flags |= BLOCK_HAS_EXTENDED_LAYOUT;
940     if (blockInfo.needsCopyDisposeHelpers())
941       flags |= BLOCK_HAS_COPY_DISPOSE;
942     if (blockInfo.HasCXXObject)
943       flags |= BLOCK_HAS_CXX_OBJ;
944     if (blockInfo.UsesStret)
945       flags |= BLOCK_USE_STRET;
946     if (blockInfo.getBlockDecl()->doesNotEscape())
947       flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
948   }
949 
950   auto projectField =
951     [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
952       return Builder.CreateStructGEP(blockAddr, index, offset, name);
953     };
954   auto storeField =
955     [&](llvm::Value *value, unsigned index, CharUnits offset,
956         const Twine &name) {
957       Builder.CreateStore(value, projectField(index, offset, name));
958     };
959 
960   // Initialize the block header.
961   {
962     // We assume all the header fields are densely packed.
963     unsigned index = 0;
964     CharUnits offset;
965     auto addHeaderField =
966       [&](llvm::Value *value, CharUnits size, const Twine &name) {
967         storeField(value, index, offset, name);
968         offset += size;
969         index++;
970       };
971 
972     if (!IsOpenCL) {
973       addHeaderField(isa, getPointerSize(), "block.isa");
974       addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
975                      getIntSize(), "block.flags");
976       addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
977                      "block.reserved");
978     } else {
979       addHeaderField(
980           llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
981           getIntSize(), "block.size");
982       addHeaderField(
983           llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
984           getIntSize(), "block.align");
985     }
986     if (!IsOpenCL) {
987       addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
988                      getPointerSize(), "block.invoke");
989       addHeaderField(descriptor, getPointerSize(), "block.descriptor");
990     } else if (auto *Helper =
991                    CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
992       for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
993         addHeaderField(
994             I.first,
995             CharUnits::fromQuantity(
996                 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
997             I.second);
998       }
999     }
1000   }
1001 
1002   // Finally, capture all the values into the block.
1003   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1004 
1005   // First, 'this'.
1006   if (blockDecl->capturesCXXThis()) {
1007     Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
1008                                 "block.captured-this.addr");
1009     Builder.CreateStore(LoadCXXThis(), addr);
1010   }
1011 
1012   // Next, captured variables.
1013   for (const auto &CI : blockDecl->captures()) {
1014     const VarDecl *variable = CI.getVariable();
1015     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1016 
1017     // Ignore constant captures.
1018     if (capture.isConstant()) continue;
1019 
1020     QualType type = capture.fieldType();
1021 
1022     // This will be a [[type]]*, except that a byref entry will just be
1023     // an i8**.
1024     Address blockField =
1025       projectField(capture.getIndex(), capture.getOffset(), "block.captured");
1026 
1027     // Compute the address of the thing we're going to move into the
1028     // block literal.
1029     Address src = Address::invalid();
1030 
1031     if (blockDecl->isConversionFromLambda()) {
1032       // The lambda capture in a lambda's conversion-to-block-pointer is
1033       // special; we'll simply emit it directly.
1034       src = Address::invalid();
1035     } else if (CI.isByRef()) {
1036       if (BlockInfo && CI.isNested()) {
1037         // We need to use the capture from the enclosing block.
1038         const CGBlockInfo::Capture &enclosingCapture =
1039             BlockInfo->getCapture(variable);
1040 
1041         // This is a [[type]]*, except that a byref entry will just be an i8**.
1042         src = Builder.CreateStructGEP(LoadBlockStruct(),
1043                                       enclosingCapture.getIndex(),
1044                                       enclosingCapture.getOffset(),
1045                                       "block.capture.addr");
1046       } else {
1047         auto I = LocalDeclMap.find(variable);
1048         assert(I != LocalDeclMap.end());
1049         src = I->second;
1050       }
1051     } else {
1052       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
1053                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1054                           type.getNonReferenceType(), VK_LValue,
1055                           SourceLocation());
1056       src = EmitDeclRefLValue(&declRef).getAddress();
1057     };
1058 
1059     // For byrefs, we just write the pointer to the byref struct into
1060     // the block field.  There's no need to chase the forwarding
1061     // pointer at this point, since we're building something that will
1062     // live a shorter life than the stack byref anyway.
1063     if (CI.isByRef()) {
1064       // Get a void* that points to the byref struct.
1065       llvm::Value *byrefPointer;
1066       if (CI.isNested())
1067         byrefPointer = Builder.CreateLoad(src, "byref.capture");
1068       else
1069         byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
1070 
1071       // Write that void* into the capture field.
1072       Builder.CreateStore(byrefPointer, blockField);
1073 
1074     // If we have a copy constructor, evaluate that into the block field.
1075     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
1076       if (blockDecl->isConversionFromLambda()) {
1077         // If we have a lambda conversion, emit the expression
1078         // directly into the block instead.
1079         AggValueSlot Slot =
1080             AggValueSlot::forAddr(blockField, Qualifiers(),
1081                                   AggValueSlot::IsDestructed,
1082                                   AggValueSlot::DoesNotNeedGCBarriers,
1083                                   AggValueSlot::IsNotAliased,
1084                                   AggValueSlot::DoesNotOverlap);
1085         EmitAggExpr(copyExpr, Slot);
1086       } else {
1087         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
1088       }
1089 
1090     // If it's a reference variable, copy the reference into the block field.
1091     } else if (type->isReferenceType()) {
1092       Builder.CreateStore(src.getPointer(), blockField);
1093 
1094     // If type is const-qualified, copy the value into the block field.
1095     } else if (type.isConstQualified() &&
1096                type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1097                CGM.getCodeGenOpts().OptimizationLevel != 0) {
1098       llvm::Value *value = Builder.CreateLoad(src, "captured");
1099       Builder.CreateStore(value, blockField);
1100 
1101     // If this is an ARC __strong block-pointer variable, don't do a
1102     // block copy.
1103     //
1104     // TODO: this can be generalized into the normal initialization logic:
1105     // we should never need to do a block-copy when initializing a local
1106     // variable, because the local variable's lifetime should be strictly
1107     // contained within the stack block's.
1108     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1109                type->isBlockPointerType()) {
1110       // Load the block and do a simple retain.
1111       llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1112       value = EmitARCRetainNonBlock(value);
1113 
1114       // Do a primitive store to the block field.
1115       Builder.CreateStore(value, blockField);
1116 
1117     // Otherwise, fake up a POD copy into the block field.
1118     } else {
1119       // Fake up a new variable so that EmitScalarInit doesn't think
1120       // we're referring to the variable in its own initializer.
1121       ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1122                                             ImplicitParamDecl::Other);
1123 
1124       // We use one of these or the other depending on whether the
1125       // reference is nested.
1126       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
1127                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1128                           type, VK_LValue, SourceLocation());
1129 
1130       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1131                            &declRef, VK_RValue);
1132       // FIXME: Pass a specific location for the expr init so that the store is
1133       // attributed to a reasonable location - otherwise it may be attributed to
1134       // locations of subexpressions in the initialization.
1135       EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1136                      MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1137                      /*captured by init*/ false);
1138     }
1139 
1140     // Activate the cleanup if layout pushed one.
1141     if (!CI.isByRef()) {
1142       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1143       if (cleanup.isValid())
1144         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
1145     }
1146   }
1147 
1148   // Cast to the converted block-pointer type, which happens (somewhat
1149   // unfortunately) to be a pointer to function type.
1150   llvm::Value *result = Builder.CreatePointerCast(
1151       blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1152 
1153   if (IsOpenCL) {
1154     CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1155                                            result);
1156   }
1157 
1158   return result;
1159 }
1160 
1161 
1162 llvm::Type *CodeGenModule::getBlockDescriptorType() {
1163   if (BlockDescriptorType)
1164     return BlockDescriptorType;
1165 
1166   llvm::Type *UnsignedLongTy =
1167     getTypes().ConvertType(getContext().UnsignedLongTy);
1168 
1169   // struct __block_descriptor {
1170   //   unsigned long reserved;
1171   //   unsigned long block_size;
1172   //
1173   //   // later, the following will be added
1174   //
1175   //   struct {
1176   //     void (*copyHelper)();
1177   //     void (*copyHelper)();
1178   //   } helpers;                // !!! optional
1179   //
1180   //   const char *signature;   // the block signature
1181   //   const char *layout;      // reserved
1182   // };
1183   BlockDescriptorType = llvm::StructType::create(
1184       "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1185 
1186   // Now form a pointer to that.
1187   unsigned AddrSpace = 0;
1188   if (getLangOpts().OpenCL)
1189     AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1190   BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1191   return BlockDescriptorType;
1192 }
1193 
1194 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1195   assert(!getLangOpts().OpenCL && "OpenCL does not need this");
1196 
1197   if (GenericBlockLiteralType)
1198     return GenericBlockLiteralType;
1199 
1200   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1201 
1202   // struct __block_literal_generic {
1203   //   void *__isa;
1204   //   int __flags;
1205   //   int __reserved;
1206   //   void (*__invoke)(void *);
1207   //   struct __block_descriptor *__descriptor;
1208   // };
1209   GenericBlockLiteralType =
1210       llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1211                                IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1212 
1213   return GenericBlockLiteralType;
1214 }
1215 
1216 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1217                                           ReturnValueSlot ReturnValue) {
1218   const BlockPointerType *BPT =
1219     E->getCallee()->getType()->getAs<BlockPointerType>();
1220 
1221   llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1222   llvm::Value *FuncPtr = nullptr;
1223 
1224   if (!CGM.getLangOpts().OpenCL) {
1225     // Get a pointer to the generic block literal.
1226     llvm::Type *BlockLiteralTy =
1227         llvm::PointerType::get(CGM.getGenericBlockLiteralType(), 0);
1228 
1229     // Bitcast the callee to a block literal.
1230     BlockPtr =
1231         Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
1232 
1233     // Get the function pointer from the literal.
1234     FuncPtr =
1235         Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
1236   }
1237 
1238   // Add the block literal.
1239   CallArgList Args;
1240 
1241   QualType VoidPtrQualTy = getContext().VoidPtrTy;
1242   llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1243   if (getLangOpts().OpenCL) {
1244     GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
1245     VoidPtrQualTy =
1246         getContext().getPointerType(getContext().getAddrSpaceQualType(
1247             getContext().VoidTy, LangAS::opencl_generic));
1248   }
1249 
1250   BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1251   Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
1252 
1253   QualType FnType = BPT->getPointeeType();
1254 
1255   // And the rest of the arguments.
1256   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1257 
1258   // Load the function.
1259   llvm::Value *Func;
1260   if (CGM.getLangOpts().OpenCL)
1261     Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1262   else
1263     Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1264 
1265   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1266   const CGFunctionInfo &FnInfo =
1267     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1268 
1269   // Cast the function pointer to the right type.
1270   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1271 
1272   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1273   Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1274 
1275   // Prepare the callee.
1276   CGCallee Callee(CGCalleeInfo(), Func);
1277 
1278   // And call the block.
1279   return EmitCall(FnInfo, Callee, ReturnValue, Args);
1280 }
1281 
1282 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1283                                             bool isByRef) {
1284   assert(BlockInfo && "evaluating block ref without block information?");
1285   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1286 
1287   // Handle constant captures.
1288   if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1289 
1290   Address addr =
1291     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1292                             capture.getOffset(), "block.capture.addr");
1293 
1294   if (isByRef) {
1295     // addr should be a void** right now.  Load, then cast the result
1296     // to byref*.
1297 
1298     auto &byrefInfo = getBlockByrefInfo(variable);
1299     addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1300 
1301     auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1302     addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1303 
1304     addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1305                                  variable->getName());
1306   }
1307 
1308   if (capture.fieldType()->isReferenceType())
1309     addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1310 
1311   return addr;
1312 }
1313 
1314 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1315                                          llvm::Constant *Addr) {
1316   bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1317   (void)Ok;
1318   assert(Ok && "Trying to replace an already-existing global block!");
1319 }
1320 
1321 llvm::Constant *
1322 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1323                                     StringRef Name) {
1324   if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1325     return Block;
1326 
1327   CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1328   blockInfo.BlockExpression = BE;
1329 
1330   // Compute information about the layout, etc., of this block.
1331   computeBlockInfo(*this, nullptr, blockInfo);
1332 
1333   // Using that metadata, generate the actual block function.
1334   {
1335     CodeGenFunction::DeclMapTy LocalDeclMap;
1336     CodeGenFunction(*this).GenerateBlockFunction(
1337         GlobalDecl(), blockInfo, LocalDeclMap,
1338         /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1339   }
1340 
1341   return getAddrOfGlobalBlockIfEmitted(BE);
1342 }
1343 
1344 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1345                                         const CGBlockInfo &blockInfo,
1346                                         llvm::Constant *blockFn) {
1347   assert(blockInfo.CanBeGlobal);
1348   // Callers should detect this case on their own: calling this function
1349   // generally requires computing layout information, which is a waste of time
1350   // if we've already emitted this block.
1351   assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1352          "Refusing to re-emit a global block.");
1353 
1354   // Generate the constants for the block literal initializer.
1355   ConstantInitBuilder builder(CGM);
1356   auto fields = builder.beginStruct();
1357 
1358   bool IsOpenCL = CGM.getLangOpts().OpenCL;
1359   bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1360   if (!IsOpenCL) {
1361     // isa
1362     if (IsWindows)
1363       fields.addNullPointer(CGM.Int8PtrPtrTy);
1364     else
1365       fields.add(CGM.getNSConcreteGlobalBlock());
1366 
1367     // __flags
1368     BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1369     if (blockInfo.UsesStret)
1370       flags |= BLOCK_USE_STRET;
1371 
1372     fields.addInt(CGM.IntTy, flags.getBitMask());
1373 
1374     // Reserved
1375     fields.addInt(CGM.IntTy, 0);
1376 
1377     // Function
1378     fields.add(blockFn);
1379   } else {
1380     fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1381     fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1382   }
1383 
1384   if (!IsOpenCL) {
1385     // Descriptor
1386     fields.add(buildBlockDescriptor(CGM, blockInfo));
1387   } else if (auto *Helper =
1388                  CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1389     for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1390       fields.add(I);
1391     }
1392   }
1393 
1394   unsigned AddrSpace = 0;
1395   if (CGM.getContext().getLangOpts().OpenCL)
1396     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1397 
1398   llvm::Constant *literal = fields.finishAndCreateGlobal(
1399       "__block_literal_global", blockInfo.BlockAlign,
1400       /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1401 
1402   // Windows does not allow globals to be initialised to point to globals in
1403   // different DLLs.  Any such variables must run code to initialise them.
1404   if (IsWindows) {
1405     auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1406           {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1407         &CGM.getModule());
1408     llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1409           Init));
1410     b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1411         b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
1412     b.CreateRetVoid();
1413     // We can't use the normal LLVM global initialisation array, because we
1414     // need to specify that this runs early in library initialisation.
1415     auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1416         /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1417         Init, ".block_isa_init_ptr");
1418     InitVar->setSection(".CRT$XCLa");
1419     CGM.addUsedGlobal(InitVar);
1420   }
1421 
1422   // Return a constant of the appropriately-casted type.
1423   llvm::Type *RequiredType =
1424     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1425   llvm::Constant *Result =
1426       llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1427   CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1428   if (CGM.getContext().getLangOpts().OpenCL)
1429     CGM.getOpenCLRuntime().recordBlockInfo(
1430         blockInfo.BlockExpression,
1431         cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
1432   return Result;
1433 }
1434 
1435 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1436                                                unsigned argNum,
1437                                                llvm::Value *arg) {
1438   assert(BlockInfo && "not emitting prologue of block invocation function?!");
1439 
1440   // Allocate a stack slot like for any local variable to guarantee optimal
1441   // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1442   Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1443   Builder.CreateStore(arg, alloc);
1444   if (CGDebugInfo *DI = getDebugInfo()) {
1445     if (CGM.getCodeGenOpts().getDebugInfo() >=
1446         codegenoptions::LimitedDebugInfo) {
1447       DI->setLocation(D->getLocation());
1448       DI->EmitDeclareOfBlockLiteralArgVariable(
1449           *BlockInfo, D->getName(), argNum,
1450           cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1451     }
1452   }
1453 
1454   SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1455   ApplyDebugLocation Scope(*this, StartLoc);
1456 
1457   // Instead of messing around with LocalDeclMap, just set the value
1458   // directly as BlockPointer.
1459   BlockPointer = Builder.CreatePointerCast(
1460       arg,
1461       BlockInfo->StructureType->getPointerTo(
1462           getContext().getLangOpts().OpenCL
1463               ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1464               : 0),
1465       "block");
1466 }
1467 
1468 Address CodeGenFunction::LoadBlockStruct() {
1469   assert(BlockInfo && "not in a block invocation function!");
1470   assert(BlockPointer && "no block pointer set!");
1471   return Address(BlockPointer, BlockInfo->BlockAlign);
1472 }
1473 
1474 llvm::Function *
1475 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1476                                        const CGBlockInfo &blockInfo,
1477                                        const DeclMapTy &ldm,
1478                                        bool IsLambdaConversionToBlock,
1479                                        bool BuildGlobalBlock) {
1480   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1481 
1482   CurGD = GD;
1483 
1484   CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1485 
1486   BlockInfo = &blockInfo;
1487 
1488   // Arrange for local static and local extern declarations to appear
1489   // to be local to this function as well, in case they're directly
1490   // referenced in a block.
1491   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1492     const auto *var = dyn_cast<VarDecl>(i->first);
1493     if (var && !var->hasLocalStorage())
1494       setAddrOfLocalVar(var, i->second);
1495   }
1496 
1497   // Begin building the function declaration.
1498 
1499   // Build the argument list.
1500   FunctionArgList args;
1501 
1502   // The first argument is the block pointer.  Just take it as a void*
1503   // and cast it later.
1504   QualType selfTy = getContext().VoidPtrTy;
1505 
1506   // For OpenCL passed block pointer can be private AS local variable or
1507   // global AS program scope variable (for the case with and without captures).
1508   // Generic AS is used therefore to be able to accommodate both private and
1509   // generic AS in one implementation.
1510   if (getLangOpts().OpenCL)
1511     selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1512         getContext().VoidTy, LangAS::opencl_generic));
1513 
1514   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1515 
1516   ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1517                              SourceLocation(), II, selfTy,
1518                              ImplicitParamDecl::ObjCSelf);
1519   args.push_back(&SelfDecl);
1520 
1521   // Now add the rest of the parameters.
1522   args.append(blockDecl->param_begin(), blockDecl->param_end());
1523 
1524   // Create the function declaration.
1525   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1526   const CGFunctionInfo &fnInfo =
1527     CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1528   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1529     blockInfo.UsesStret = true;
1530 
1531   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1532 
1533   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1534   llvm::Function *fn = llvm::Function::Create(
1535       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1536   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1537 
1538   if (BuildGlobalBlock) {
1539     auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1540                             ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1541                             : VoidPtrTy;
1542     buildGlobalBlock(CGM, blockInfo,
1543                      llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1544   }
1545 
1546   // Begin generating the function.
1547   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1548                 blockDecl->getLocation(),
1549                 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1550 
1551   // Okay.  Undo some of what StartFunction did.
1552 
1553   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1554   // won't delete the dbg.declare intrinsics for captured variables.
1555   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1556   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1557     // Allocate a stack slot for it, so we can point the debugger to it
1558     Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1559                                       getPointerAlign(),
1560                                       "block.addr");
1561     // Set the DebugLocation to empty, so the store is recognized as a
1562     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1563     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1564     Builder.CreateStore(BlockPointer, Alloca);
1565     BlockPointerDbgLoc = Alloca.getPointer();
1566   }
1567 
1568   // If we have a C++ 'this' reference, go ahead and force it into
1569   // existence now.
1570   if (blockDecl->capturesCXXThis()) {
1571     Address addr =
1572       Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1573                               blockInfo.CXXThisOffset, "block.captured-this");
1574     CXXThisValue = Builder.CreateLoad(addr, "this");
1575   }
1576 
1577   // Also force all the constant captures.
1578   for (const auto &CI : blockDecl->captures()) {
1579     const VarDecl *variable = CI.getVariable();
1580     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1581     if (!capture.isConstant()) continue;
1582 
1583     CharUnits align = getContext().getDeclAlign(variable);
1584     Address alloca =
1585       CreateMemTemp(variable->getType(), align, "block.captured-const");
1586 
1587     Builder.CreateStore(capture.getConstant(), alloca);
1588 
1589     setAddrOfLocalVar(variable, alloca);
1590   }
1591 
1592   // Save a spot to insert the debug information for all the DeclRefExprs.
1593   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1594   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1595   --entry_ptr;
1596 
1597   if (IsLambdaConversionToBlock)
1598     EmitLambdaBlockInvokeBody();
1599   else {
1600     PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1601     incrementProfileCounter(blockDecl->getBody());
1602     EmitStmt(blockDecl->getBody());
1603   }
1604 
1605   // Remember where we were...
1606   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1607 
1608   // Go back to the entry.
1609   ++entry_ptr;
1610   Builder.SetInsertPoint(entry, entry_ptr);
1611 
1612   // Emit debug information for all the DeclRefExprs.
1613   // FIXME: also for 'this'
1614   if (CGDebugInfo *DI = getDebugInfo()) {
1615     for (const auto &CI : blockDecl->captures()) {
1616       const VarDecl *variable = CI.getVariable();
1617       DI->EmitLocation(Builder, variable->getLocation());
1618 
1619       if (CGM.getCodeGenOpts().getDebugInfo() >=
1620           codegenoptions::LimitedDebugInfo) {
1621         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1622         if (capture.isConstant()) {
1623           auto addr = LocalDeclMap.find(variable)->second;
1624           (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1625                                               Builder);
1626           continue;
1627         }
1628 
1629         DI->EmitDeclareOfBlockDeclRefVariable(
1630             variable, BlockPointerDbgLoc, Builder, blockInfo,
1631             entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1632       }
1633     }
1634     // Recover location if it was changed in the above loop.
1635     DI->EmitLocation(Builder,
1636                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1637   }
1638 
1639   // And resume where we left off.
1640   if (resume == nullptr)
1641     Builder.ClearInsertionPoint();
1642   else
1643     Builder.SetInsertPoint(resume);
1644 
1645   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1646 
1647   return fn;
1648 }
1649 
1650 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1651 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1652                                const LangOptions &LangOpts) {
1653   if (CI.getCopyExpr()) {
1654     assert(!CI.isByRef());
1655     // don't bother computing flags
1656     return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1657   }
1658   BlockFieldFlags Flags;
1659   if (CI.isByRef()) {
1660     Flags = BLOCK_FIELD_IS_BYREF;
1661     if (T.isObjCGCWeak())
1662       Flags |= BLOCK_FIELD_IS_WEAK;
1663     return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1664   }
1665 
1666   Flags = BLOCK_FIELD_IS_OBJECT;
1667   bool isBlockPointer = T->isBlockPointerType();
1668   if (isBlockPointer)
1669     Flags = BLOCK_FIELD_IS_BLOCK;
1670 
1671   switch (T.isNonTrivialToPrimitiveCopy()) {
1672   case QualType::PCK_Struct:
1673     return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1674                           BlockFieldFlags());
1675   case QualType::PCK_ARCWeak:
1676     // We need to register __weak direct captures with the runtime.
1677     return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1678   case QualType::PCK_ARCStrong:
1679     // We need to retain the copied value for __strong direct captures.
1680     // If it's a block pointer, we have to copy the block and assign that to
1681     // the destination pointer, so we might as well use _Block_object_assign.
1682     // Otherwise we can avoid that.
1683     return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1684                                           : BlockCaptureEntityKind::BlockObject,
1685                           Flags);
1686   case QualType::PCK_Trivial:
1687   case QualType::PCK_VolatileTrivial: {
1688     if (!T->isObjCRetainableType())
1689       // For all other types, the memcpy is fine.
1690       return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1691 
1692     // Special rules for ARC captures:
1693     Qualifiers QS = T.getQualifiers();
1694 
1695     // Non-ARC captures of retainable pointers are strong and
1696     // therefore require a call to _Block_object_assign.
1697     if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1698       return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1699 
1700     // Otherwise the memcpy is fine.
1701     return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1702   }
1703   }
1704   llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1705 }
1706 
1707 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1708 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1709                                   const LangOptions &LangOpts);
1710 
1711 /// Find the set of block captures that need to be explicitly copied or destroy.
1712 static void findBlockCapturedManagedEntities(
1713     const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1714     SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
1715   for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1716     const VarDecl *Variable = CI.getVariable();
1717     const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1718     if (Capture.isConstant())
1719       continue;
1720 
1721     QualType VT = Capture.fieldType();
1722     auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1723     auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, 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