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 "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "ConstantBuilder.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Module.h"
25 #include <algorithm>
26 #include <cstdio>
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
31 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
32   : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
33     HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
34     LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
35     DominatingIP(nullptr) {
36 
37   // Skip asm prefix, if any.  'name' is usually taken directly from
38   // the mangled name of the enclosing function.
39   if (!name.empty() && name[0] == '\01')
40     name = name.substr(1);
41 }
42 
43 // Anchor the vtable to this translation unit.
44 BlockByrefHelpers::~BlockByrefHelpers() {}
45 
46 /// Build the given block as a global block.
47 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
48                                         const CGBlockInfo &blockInfo,
49                                         llvm::Constant *blockFn);
50 
51 /// Build the helper function to copy a block.
52 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
53                                        const CGBlockInfo &blockInfo) {
54   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
55 }
56 
57 /// Build the helper function to dispose of a block.
58 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
59                                           const CGBlockInfo &blockInfo) {
60   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
61 }
62 
63 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
64 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
65 /// meta-data and contains stationary information about the block literal.
66 /// Its definition will have 4 (or optinally 6) words.
67 /// \code
68 /// struct Block_descriptor {
69 ///   unsigned long reserved;
70 ///   unsigned long size;  // size of Block_literal metadata in bytes.
71 ///   void *copy_func_helper_decl;  // optional copy helper.
72 ///   void *destroy_func_decl; // optioanl destructor helper.
73 ///   void *block_method_encoding_address; // @encode for block literal signature.
74 ///   void *block_layout_info; // encoding of captured block variables.
75 /// };
76 /// \endcode
77 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
78                                             const CGBlockInfo &blockInfo) {
79   ASTContext &C = CGM.getContext();
80 
81   llvm::IntegerType *ulong =
82     cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
83   llvm::PointerType *i8p = nullptr;
84   if (CGM.getLangOpts().OpenCL)
85     i8p =
86       llvm::Type::getInt8PtrTy(
87            CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
88   else
89     i8p = CGM.VoidPtrTy;
90 
91   ConstantBuilder builder(CGM);
92   auto elements = builder.beginStruct();
93 
94   // reserved
95   elements.addInt(ulong, 0);
96 
97   // Size
98   // FIXME: What is the right way to say this doesn't fit?  We should give
99   // a user diagnostic in that case.  Better fix would be to change the
100   // API to size_t.
101   elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
102 
103   // Optional copy/dispose helpers.
104   if (blockInfo.NeedsCopyDispose) {
105     // copy_func_helper_decl
106     elements.add(buildCopyHelper(CGM, blockInfo));
107 
108     // destroy_func_decl
109     elements.add(buildDisposeHelper(CGM, blockInfo));
110   }
111 
112   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
113   std::string typeAtEncoding =
114     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
115   elements.add(llvm::ConstantExpr::getBitCast(
116     CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
117 
118   // GC layout.
119   if (C.getLangOpts().ObjC1) {
120     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
121       elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
122     else
123       elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
124   }
125   else
126     elements.addNullPointer(i8p);
127 
128   unsigned AddrSpace = 0;
129   if (C.getLangOpts().OpenCL)
130     AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
131 
132   llvm::GlobalVariable *global =
133     elements.finishAndCreateGlobal("__block_descriptor_tmp",
134                                    CGM.getPointerAlign(),
135                                    /*constant*/ true,
136                                    llvm::GlobalValue::InternalLinkage,
137                                    AddrSpace);
138 
139   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
140 }
141 
142 /*
143   Purely notional variadic template describing the layout of a block.
144 
145   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
146   struct Block_literal {
147     /// Initialized to one of:
148     ///   extern void *_NSConcreteStackBlock[];
149     ///   extern void *_NSConcreteGlobalBlock[];
150     ///
151     /// In theory, we could start one off malloc'ed by setting
152     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
153     /// this isa:
154     ///   extern void *_NSConcreteMallocBlock[];
155     struct objc_class *isa;
156 
157     /// These are the flags (with corresponding bit number) that the
158     /// compiler is actually supposed to know about.
159     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
160     ///   descriptor provides copy and dispose helper functions
161     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
162     ///   object with a nontrivial destructor or copy constructor
163     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
164     ///   as global memory
165     ///  29. BLOCK_USE_STRET - indicates that the block function
166     ///   uses stret, which objc_msgSend needs to know about
167     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
168     ///   @encoded signature string
169     /// And we're not supposed to manipulate these:
170     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
171     ///   to malloc'ed memory
172     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
173     ///   to GC-allocated memory
174     /// Additionally, the bottom 16 bits are a reference count which
175     /// should be zero on the stack.
176     int flags;
177 
178     /// Reserved;  should be zero-initialized.
179     int reserved;
180 
181     /// Function pointer generated from block literal.
182     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
183 
184     /// Block description metadata generated from block literal.
185     struct Block_descriptor *block_descriptor;
186 
187     /// Captured values follow.
188     _CapturesTypes captures...;
189   };
190  */
191 
192 namespace {
193   /// A chunk of data that we actually have to capture in the block.
194   struct BlockLayoutChunk {
195     CharUnits Alignment;
196     CharUnits Size;
197     Qualifiers::ObjCLifetime Lifetime;
198     const BlockDecl::Capture *Capture; // null for 'this'
199     llvm::Type *Type;
200     QualType FieldType;
201 
202     BlockLayoutChunk(CharUnits align, CharUnits size,
203                      Qualifiers::ObjCLifetime lifetime,
204                      const BlockDecl::Capture *capture,
205                      llvm::Type *type, QualType fieldType)
206       : Alignment(align), Size(size), Lifetime(lifetime),
207         Capture(capture), Type(type), FieldType(fieldType) {}
208 
209     /// Tell the block info that this chunk has the given field index.
210     void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
211       if (!Capture) {
212         info.CXXThisIndex = index;
213         info.CXXThisOffset = offset;
214       } else {
215         auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
216         info.Captures.insert({Capture->getVariable(), C});
217       }
218     }
219   };
220 
221   /// Order by 1) all __strong together 2) next, all byfref together 3) next,
222   /// all __weak together. Preserve descending alignment in all situations.
223   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
224     if (left.Alignment != right.Alignment)
225       return left.Alignment > right.Alignment;
226 
227     auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
228       if (chunk.Capture && chunk.Capture->isByRef())
229         return 1;
230       if (chunk.Lifetime == Qualifiers::OCL_Strong)
231         return 0;
232       if (chunk.Lifetime == Qualifiers::OCL_Weak)
233         return 2;
234       return 3;
235     };
236 
237     return getPrefOrder(left) < getPrefOrder(right);
238   }
239 } // end anonymous namespace
240 
241 /// Determines if the given type is safe for constant capture in C++.
242 static bool isSafeForCXXConstantCapture(QualType type) {
243   const RecordType *recordType =
244     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
245 
246   // Only records can be unsafe.
247   if (!recordType) return true;
248 
249   const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
250 
251   // Maintain semantics for classes with non-trivial dtors or copy ctors.
252   if (!record->hasTrivialDestructor()) return false;
253   if (record->hasNonTrivialCopyConstructor()) return false;
254 
255   // Otherwise, we just have to make sure there aren't any mutable
256   // fields that might have changed since initialization.
257   return !record->hasMutableFields();
258 }
259 
260 /// It is illegal to modify a const object after initialization.
261 /// Therefore, if a const object has a constant initializer, we don't
262 /// actually need to keep storage for it in the block; we'll just
263 /// rematerialize it at the start of the block function.  This is
264 /// acceptable because we make no promises about address stability of
265 /// captured variables.
266 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
267                                             CodeGenFunction *CGF,
268                                             const VarDecl *var) {
269   // Return if this is a function paramter. We shouldn't try to
270   // rematerialize default arguments of function parameters.
271   if (isa<ParmVarDecl>(var))
272     return nullptr;
273 
274   QualType type = var->getType();
275 
276   // We can only do this if the variable is const.
277   if (!type.isConstQualified()) return nullptr;
278 
279   // Furthermore, in C++ we have to worry about mutable fields:
280   // C++ [dcl.type.cv]p4:
281   //   Except that any class member declared mutable can be
282   //   modified, any attempt to modify a const object during its
283   //   lifetime results in undefined behavior.
284   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
285     return nullptr;
286 
287   // If the variable doesn't have any initializer (shouldn't this be
288   // invalid?), it's not clear what we should do.  Maybe capture as
289   // zero?
290   const Expr *init = var->getInit();
291   if (!init) return nullptr;
292 
293   return CGM.EmitConstantInit(*var, CGF);
294 }
295 
296 /// Get the low bit of a nonzero character count.  This is the
297 /// alignment of the nth byte if the 0th byte is universally aligned.
298 static CharUnits getLowBit(CharUnits v) {
299   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
300 }
301 
302 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
303                              SmallVectorImpl<llvm::Type*> &elementTypes) {
304   // The header is basically 'struct { void *; int; int; void *; void *; }'.
305   // Assert that that struct is packed.
306   assert(CGM.getIntSize() <= CGM.getPointerSize());
307   assert(CGM.getIntAlign() <= CGM.getPointerAlign());
308   assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
309 
310   info.BlockAlign = CGM.getPointerAlign();
311   info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
312 
313   assert(elementTypes.empty());
314   elementTypes.push_back(CGM.VoidPtrTy);
315   elementTypes.push_back(CGM.IntTy);
316   elementTypes.push_back(CGM.IntTy);
317   elementTypes.push_back(CGM.VoidPtrTy);
318   elementTypes.push_back(CGM.getBlockDescriptorType());
319 }
320 
321 /// Compute the layout of the given block.  Attempts to lay the block
322 /// out with minimal space requirements.
323 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
324                              CGBlockInfo &info) {
325   ASTContext &C = CGM.getContext();
326   const BlockDecl *block = info.getBlockDecl();
327 
328   SmallVector<llvm::Type*, 8> elementTypes;
329   initializeForBlockHeader(CGM, info, elementTypes);
330 
331   if (!block->hasCaptures()) {
332     info.StructureType =
333       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
334     info.CanBeGlobal = true;
335     return;
336   }
337   else if (C.getLangOpts().ObjC1 &&
338            CGM.getLangOpts().getGC() == LangOptions::NonGC)
339     info.HasCapturedVariableLayout = true;
340 
341   // Collect the layout chunks.
342   SmallVector<BlockLayoutChunk, 16> layout;
343   layout.reserve(block->capturesCXXThis() +
344                  (block->capture_end() - block->capture_begin()));
345 
346   CharUnits maxFieldAlign;
347 
348   // First, 'this'.
349   if (block->capturesCXXThis()) {
350     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
351            "Can't capture 'this' outside a method");
352     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
353 
354     // Theoretically, this could be in a different address space, so
355     // don't assume standard pointer size/align.
356     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
357     std::pair<CharUnits,CharUnits> tinfo
358       = CGM.getContext().getTypeInfoInChars(thisType);
359     maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
360 
361     layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
362                                       Qualifiers::OCL_None,
363                                       nullptr, llvmType, thisType));
364   }
365 
366   // Next, all the block captures.
367   for (const auto &CI : block->captures()) {
368     const VarDecl *variable = CI.getVariable();
369 
370     if (CI.isByRef()) {
371       // We have to copy/dispose of the __block reference.
372       info.NeedsCopyDispose = true;
373 
374       // Just use void* instead of a pointer to the byref type.
375       CharUnits align = CGM.getPointerAlign();
376       maxFieldAlign = std::max(maxFieldAlign, align);
377 
378       layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
379                                         Qualifiers::OCL_None, &CI,
380                                         CGM.VoidPtrTy, variable->getType()));
381       continue;
382     }
383 
384     // Otherwise, build a layout chunk with the size and alignment of
385     // the declaration.
386     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
387       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
388       continue;
389     }
390 
391     // If we have a lifetime qualifier, honor it for capture purposes.
392     // That includes *not* copying it if it's __unsafe_unretained.
393     Qualifiers::ObjCLifetime lifetime =
394       variable->getType().getObjCLifetime();
395     if (lifetime) {
396       switch (lifetime) {
397       case Qualifiers::OCL_None: llvm_unreachable("impossible");
398       case Qualifiers::OCL_ExplicitNone:
399       case Qualifiers::OCL_Autoreleasing:
400         break;
401 
402       case Qualifiers::OCL_Strong:
403       case Qualifiers::OCL_Weak:
404         info.NeedsCopyDispose = true;
405       }
406 
407     // Block pointers require copy/dispose.  So do Objective-C pointers.
408     } else if (variable->getType()->isObjCRetainableType()) {
409       // But honor the inert __unsafe_unretained qualifier, which doesn't
410       // actually make it into the type system.
411        if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
412         lifetime = Qualifiers::OCL_ExplicitNone;
413       } else {
414         info.NeedsCopyDispose = true;
415         // used for mrr below.
416         lifetime = Qualifiers::OCL_Strong;
417       }
418 
419     // So do types that require non-trivial copy construction.
420     } else if (CI.hasCopyExpr()) {
421       info.NeedsCopyDispose = true;
422       info.HasCXXObject = true;
423 
424     // And so do types with destructors.
425     } else if (CGM.getLangOpts().CPlusPlus) {
426       if (const CXXRecordDecl *record =
427             variable->getType()->getAsCXXRecordDecl()) {
428         if (!record->hasTrivialDestructor()) {
429           info.HasCXXObject = true;
430           info.NeedsCopyDispose = true;
431         }
432       }
433     }
434 
435     QualType VT = variable->getType();
436 
437     // If the variable is captured by an enclosing block or lambda expression,
438     // use the type of the capture field.
439     if (CGF->BlockInfo && CI.isNested())
440       VT = CGF->BlockInfo->getCapture(variable).fieldType();
441     else if (auto *FD = CGF->LambdaCaptureFields.lookup(variable))
442       VT = FD->getType();
443 
444     CharUnits size = C.getTypeSizeInChars(VT);
445     CharUnits align = C.getDeclAlign(variable);
446 
447     maxFieldAlign = std::max(maxFieldAlign, align);
448 
449     llvm::Type *llvmType =
450       CGM.getTypes().ConvertTypeForMem(VT);
451 
452     layout.push_back(
453         BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
454   }
455 
456   // If that was everything, we're done here.
457   if (layout.empty()) {
458     info.StructureType =
459       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460     info.CanBeGlobal = true;
461     return;
462   }
463 
464   // Sort the layout by alignment.  We have to use a stable sort here
465   // to get reproducible results.  There should probably be an
466   // llvm::array_pod_stable_sort.
467   std::stable_sort(layout.begin(), layout.end());
468 
469   // Needed for blocks layout info.
470   info.BlockHeaderForcedGapOffset = info.BlockSize;
471   info.BlockHeaderForcedGapSize = CharUnits::Zero();
472 
473   CharUnits &blockSize = info.BlockSize;
474   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
475 
476   // Assuming that the first byte in the header is maximally aligned,
477   // get the alignment of the first byte following the header.
478   CharUnits endAlign = getLowBit(blockSize);
479 
480   // If the end of the header isn't satisfactorily aligned for the
481   // maximum thing, look for things that are okay with the header-end
482   // alignment, and keep appending them until we get something that's
483   // aligned right.  This algorithm is only guaranteed optimal if
484   // that condition is satisfied at some point; otherwise we can get
485   // things like:
486   //   header                 // next byte has alignment 4
487   //   something_with_size_5; // next byte has alignment 1
488   //   something_with_alignment_8;
489   // which has 7 bytes of padding, as opposed to the naive solution
490   // which might have less (?).
491   if (endAlign < maxFieldAlign) {
492     SmallVectorImpl<BlockLayoutChunk>::iterator
493       li = layout.begin() + 1, le = layout.end();
494 
495     // Look for something that the header end is already
496     // satisfactorily aligned for.
497     for (; li != le && endAlign < li->Alignment; ++li)
498       ;
499 
500     // If we found something that's naturally aligned for the end of
501     // the header, keep adding things...
502     if (li != le) {
503       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
504       for (; li != le; ++li) {
505         assert(endAlign >= li->Alignment);
506 
507         li->setIndex(info, elementTypes.size(), blockSize);
508         elementTypes.push_back(li->Type);
509         blockSize += li->Size;
510         endAlign = getLowBit(blockSize);
511 
512         // ...until we get to the alignment of the maximum field.
513         if (endAlign >= maxFieldAlign) {
514           break;
515         }
516       }
517       // Don't re-append everything we just appended.
518       layout.erase(first, li);
519     }
520   }
521 
522   assert(endAlign == getLowBit(blockSize));
523 
524   // At this point, we just have to add padding if the end align still
525   // isn't aligned right.
526   if (endAlign < maxFieldAlign) {
527     CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
528     CharUnits padding = newBlockSize - blockSize;
529 
530     // If we haven't yet added any fields, remember that there was an
531     // initial gap; this need to go into the block layout bit map.
532     if (blockSize == info.BlockHeaderForcedGapOffset) {
533       info.BlockHeaderForcedGapSize = padding;
534     }
535 
536     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
537                                                 padding.getQuantity()));
538     blockSize = newBlockSize;
539     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
540   }
541 
542   assert(endAlign >= maxFieldAlign);
543   assert(endAlign == getLowBit(blockSize));
544   // Slam everything else on now.  This works because they have
545   // strictly decreasing alignment and we expect that size is always a
546   // multiple of alignment.
547   for (SmallVectorImpl<BlockLayoutChunk>::iterator
548          li = layout.begin(), le = layout.end(); li != le; ++li) {
549     if (endAlign < li->Alignment) {
550       // size may not be multiple of alignment. This can only happen with
551       // an over-aligned variable. We will be adding a padding field to
552       // make the size be multiple of alignment.
553       CharUnits padding = li->Alignment - endAlign;
554       elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
555                                                   padding.getQuantity()));
556       blockSize += padding;
557       endAlign = getLowBit(blockSize);
558     }
559     assert(endAlign >= li->Alignment);
560     li->setIndex(info, elementTypes.size(), blockSize);
561     elementTypes.push_back(li->Type);
562     blockSize += li->Size;
563     endAlign = getLowBit(blockSize);
564   }
565 
566   info.StructureType =
567     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
568 }
569 
570 /// Enter the scope of a block.  This should be run at the entrance to
571 /// a full-expression so that the block's cleanups are pushed at the
572 /// right place in the stack.
573 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
574   assert(CGF.HaveInsertPoint());
575 
576   // Allocate the block info and place it at the head of the list.
577   CGBlockInfo &blockInfo =
578     *new CGBlockInfo(block, CGF.CurFn->getName());
579   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
580   CGF.FirstBlockInfo = &blockInfo;
581 
582   // Compute information about the layout, etc., of this block,
583   // pushing cleanups as necessary.
584   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
585 
586   // Nothing else to do if it can be global.
587   if (blockInfo.CanBeGlobal) return;
588 
589   // Make the allocation for the block.
590   blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
591                                                 blockInfo.BlockAlign, "block");
592 
593   // If there are cleanups to emit, enter them (but inactive).
594   if (!blockInfo.NeedsCopyDispose) return;
595 
596   // Walk through the captures (in order) and find the ones not
597   // captured by constant.
598   for (const auto &CI : block->captures()) {
599     // Ignore __block captures; there's nothing special in the
600     // on-stack block that we need to do for them.
601     if (CI.isByRef()) continue;
602 
603     // Ignore variables that are constant-captured.
604     const VarDecl *variable = CI.getVariable();
605     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
606     if (capture.isConstant()) continue;
607 
608     // Ignore objects that aren't destructed.
609     QualType::DestructionKind dtorKind =
610       variable->getType().isDestructedType();
611     if (dtorKind == QualType::DK_none) continue;
612 
613     CodeGenFunction::Destroyer *destroyer;
614 
615     // Block captures count as local values and have imprecise semantics.
616     // They also can't be arrays, so need to worry about that.
617     if (dtorKind == QualType::DK_objc_strong_lifetime) {
618       destroyer = CodeGenFunction::destroyARCStrongImprecise;
619     } else {
620       destroyer = CGF.getDestroyer(dtorKind);
621     }
622 
623     // GEP down to the address.
624     Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
625                                                capture.getIndex(),
626                                                capture.getOffset());
627 
628     // We can use that GEP as the dominating IP.
629     if (!blockInfo.DominatingIP)
630       blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
631 
632     CleanupKind cleanupKind = InactiveNormalCleanup;
633     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
634     if (useArrayEHCleanup)
635       cleanupKind = InactiveNormalAndEHCleanup;
636 
637     CGF.pushDestroy(cleanupKind, addr, variable->getType(),
638                     destroyer, useArrayEHCleanup);
639 
640     // Remember where that cleanup was.
641     capture.setCleanup(CGF.EHStack.stable_begin());
642   }
643 }
644 
645 /// Enter a full-expression with a non-trivial number of objects to
646 /// clean up.  This is in this file because, at the moment, the only
647 /// kind of cleanup object is a BlockDecl*.
648 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
649   assert(E->getNumObjects() != 0);
650   ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
651   for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
652          i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
653     enterBlockScope(*this, *i);
654   }
655 }
656 
657 /// Find the layout for the given block in a linked list and remove it.
658 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
659                                            const BlockDecl *block) {
660   while (true) {
661     assert(head && *head);
662     CGBlockInfo *cur = *head;
663 
664     // If this is the block we're looking for, splice it out of the list.
665     if (cur->getBlockDecl() == block) {
666       *head = cur->NextBlockInfo;
667       return cur;
668     }
669 
670     head = &cur->NextBlockInfo;
671   }
672 }
673 
674 /// Destroy a chain of block layouts.
675 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
676   assert(head && "destroying an empty chain");
677   do {
678     CGBlockInfo *cur = head;
679     head = cur->NextBlockInfo;
680     delete cur;
681   } while (head != nullptr);
682 }
683 
684 /// Emit a block literal expression in the current function.
685 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
686   // If the block has no captures, we won't have a pre-computed
687   // layout for it.
688   if (!blockExpr->getBlockDecl()->hasCaptures()) {
689     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
690     computeBlockInfo(CGM, this, blockInfo);
691     blockInfo.BlockExpression = blockExpr;
692     return EmitBlockLiteral(blockInfo);
693   }
694 
695   // Find the block info for this block and take ownership of it.
696   std::unique_ptr<CGBlockInfo> blockInfo;
697   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
698                                          blockExpr->getBlockDecl()));
699 
700   blockInfo->BlockExpression = blockExpr;
701   return EmitBlockLiteral(*blockInfo);
702 }
703 
704 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
705   // Using the computed layout, generate the actual block function.
706   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
707   llvm::Constant *blockFn
708     = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
709                                                        LocalDeclMap,
710                                                        isLambdaConv);
711   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
712 
713   // If there is nothing to capture, we can emit this as a global block.
714   if (blockInfo.CanBeGlobal)
715     return buildGlobalBlock(CGM, blockInfo, blockFn);
716 
717   // Otherwise, we have to emit this as a local block.
718 
719   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
720   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
721 
722   // Build the block descriptor.
723   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
724 
725   Address blockAddr = blockInfo.LocalAddress;
726   assert(blockAddr.isValid() && "block has no address!");
727 
728   // Compute the initial on-stack block flags.
729   BlockFlags flags = BLOCK_HAS_SIGNATURE;
730   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
731   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
732   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
733   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
734 
735   auto projectField =
736     [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
737       return Builder.CreateStructGEP(blockAddr, index, offset, name);
738     };
739   auto storeField =
740     [&](llvm::Value *value, unsigned index, CharUnits offset,
741         const Twine &name) {
742       Builder.CreateStore(value, projectField(index, offset, name));
743     };
744 
745   // Initialize the block header.
746   {
747     // We assume all the header fields are densely packed.
748     unsigned index = 0;
749     CharUnits offset;
750     auto addHeaderField =
751       [&](llvm::Value *value, CharUnits size, const Twine &name) {
752         storeField(value, index, offset, name);
753         offset += size;
754         index++;
755       };
756 
757     addHeaderField(isa, getPointerSize(), "block.isa");
758     addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
759                    getIntSize(), "block.flags");
760     addHeaderField(llvm::ConstantInt::get(IntTy, 0),
761                    getIntSize(), "block.reserved");
762     addHeaderField(blockFn, getPointerSize(), "block.invoke");
763     addHeaderField(descriptor, getPointerSize(), "block.descriptor");
764   }
765 
766   // Finally, capture all the values into the block.
767   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
768 
769   // First, 'this'.
770   if (blockDecl->capturesCXXThis()) {
771     Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
772                                 "block.captured-this.addr");
773     Builder.CreateStore(LoadCXXThis(), addr);
774   }
775 
776   // Next, captured variables.
777   for (const auto &CI : blockDecl->captures()) {
778     const VarDecl *variable = CI.getVariable();
779     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
780 
781     // Ignore constant captures.
782     if (capture.isConstant()) continue;
783 
784     QualType type = capture.fieldType();
785 
786     // This will be a [[type]]*, except that a byref entry will just be
787     // an i8**.
788     Address blockField =
789       projectField(capture.getIndex(), capture.getOffset(), "block.captured");
790 
791     // Compute the address of the thing we're going to move into the
792     // block literal.
793     Address src = Address::invalid();
794 
795     if (blockDecl->isConversionFromLambda()) {
796       // The lambda capture in a lambda's conversion-to-block-pointer is
797       // special; we'll simply emit it directly.
798       src = Address::invalid();
799     } else if (CI.isByRef()) {
800       if (BlockInfo && CI.isNested()) {
801         // We need to use the capture from the enclosing block.
802         const CGBlockInfo::Capture &enclosingCapture =
803             BlockInfo->getCapture(variable);
804 
805         // This is a [[type]]*, except that a byref entry wil just be an i8**.
806         src = Builder.CreateStructGEP(LoadBlockStruct(),
807                                       enclosingCapture.getIndex(),
808                                       enclosingCapture.getOffset(),
809                                       "block.capture.addr");
810       } else {
811         auto I = LocalDeclMap.find(variable);
812         assert(I != LocalDeclMap.end());
813         src = I->second;
814       }
815     } else {
816       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
817                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
818                           type.getNonReferenceType(), VK_LValue,
819                           SourceLocation());
820       src = EmitDeclRefLValue(&declRef).getAddress();
821     };
822 
823     // For byrefs, we just write the pointer to the byref struct into
824     // the block field.  There's no need to chase the forwarding
825     // pointer at this point, since we're building something that will
826     // live a shorter life than the stack byref anyway.
827     if (CI.isByRef()) {
828       // Get a void* that points to the byref struct.
829       llvm::Value *byrefPointer;
830       if (CI.isNested())
831         byrefPointer = Builder.CreateLoad(src, "byref.capture");
832       else
833         byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
834 
835       // Write that void* into the capture field.
836       Builder.CreateStore(byrefPointer, blockField);
837 
838     // If we have a copy constructor, evaluate that into the block field.
839     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
840       if (blockDecl->isConversionFromLambda()) {
841         // If we have a lambda conversion, emit the expression
842         // directly into the block instead.
843         AggValueSlot Slot =
844             AggValueSlot::forAddr(blockField, Qualifiers(),
845                                   AggValueSlot::IsDestructed,
846                                   AggValueSlot::DoesNotNeedGCBarriers,
847                                   AggValueSlot::IsNotAliased);
848         EmitAggExpr(copyExpr, Slot);
849       } else {
850         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
851       }
852 
853     // If it's a reference variable, copy the reference into the block field.
854     } else if (type->isReferenceType()) {
855       Builder.CreateStore(src.getPointer(), blockField);
856 
857     // If this is an ARC __strong block-pointer variable, don't do a
858     // block copy.
859     //
860     // TODO: this can be generalized into the normal initialization logic:
861     // we should never need to do a block-copy when initializing a local
862     // variable, because the local variable's lifetime should be strictly
863     // contained within the stack block's.
864     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
865                type->isBlockPointerType()) {
866       // Load the block and do a simple retain.
867       llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
868       value = EmitARCRetainNonBlock(value);
869 
870       // Do a primitive store to the block field.
871       Builder.CreateStore(value, blockField);
872 
873     // Otherwise, fake up a POD copy into the block field.
874     } else {
875       // Fake up a new variable so that EmitScalarInit doesn't think
876       // we're referring to the variable in its own initializer.
877       ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
878                                             SourceLocation(), /*name*/ nullptr,
879                                             type);
880 
881       // We use one of these or the other depending on whether the
882       // reference is nested.
883       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
884                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
885                           type, VK_LValue, SourceLocation());
886 
887       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
888                            &declRef, VK_RValue);
889       // FIXME: Pass a specific location for the expr init so that the store is
890       // attributed to a reasonable location - otherwise it may be attributed to
891       // locations of subexpressions in the initialization.
892       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
893                      MakeAddrLValue(blockField, type, AlignmentSource::Decl),
894                      /*captured by init*/ false);
895     }
896 
897     // Activate the cleanup if layout pushed one.
898     if (!CI.isByRef()) {
899       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
900       if (cleanup.isValid())
901         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
902     }
903   }
904 
905   // Cast to the converted block-pointer type, which happens (somewhat
906   // unfortunately) to be a pointer to function type.
907   llvm::Value *result =
908     Builder.CreateBitCast(blockAddr.getPointer(),
909                           ConvertType(blockInfo.getBlockExpr()->getType()));
910 
911   return result;
912 }
913 
914 
915 llvm::Type *CodeGenModule::getBlockDescriptorType() {
916   if (BlockDescriptorType)
917     return BlockDescriptorType;
918 
919   llvm::Type *UnsignedLongTy =
920     getTypes().ConvertType(getContext().UnsignedLongTy);
921 
922   // struct __block_descriptor {
923   //   unsigned long reserved;
924   //   unsigned long block_size;
925   //
926   //   // later, the following will be added
927   //
928   //   struct {
929   //     void (*copyHelper)();
930   //     void (*copyHelper)();
931   //   } helpers;                // !!! optional
932   //
933   //   const char *signature;   // the block signature
934   //   const char *layout;      // reserved
935   // };
936   BlockDescriptorType =
937     llvm::StructType::create("struct.__block_descriptor",
938                              UnsignedLongTy, UnsignedLongTy, nullptr);
939 
940   // Now form a pointer to that.
941   unsigned AddrSpace = 0;
942   if (getLangOpts().OpenCL)
943     AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
944   BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
945   return BlockDescriptorType;
946 }
947 
948 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
949   if (GenericBlockLiteralType)
950     return GenericBlockLiteralType;
951 
952   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
953 
954   // struct __block_literal_generic {
955   //   void *__isa;
956   //   int __flags;
957   //   int __reserved;
958   //   void (*__invoke)(void *);
959   //   struct __block_descriptor *__descriptor;
960   // };
961   GenericBlockLiteralType =
962     llvm::StructType::create("struct.__block_literal_generic",
963                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
964                              BlockDescPtrTy, nullptr);
965 
966   return GenericBlockLiteralType;
967 }
968 
969 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
970                                           ReturnValueSlot ReturnValue) {
971   const BlockPointerType *BPT =
972     E->getCallee()->getType()->getAs<BlockPointerType>();
973 
974   llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
975 
976   // Get a pointer to the generic block literal.
977   llvm::Type *BlockLiteralTy =
978     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
979 
980   // Bitcast the callee to a block literal.
981   BlockPtr = Builder.CreateBitCast(BlockPtr, BlockLiteralTy, "block.literal");
982 
983   // Get the function pointer from the literal.
984   llvm::Value *FuncPtr =
985     Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
986 
987   BlockPtr = Builder.CreateBitCast(BlockPtr, VoidPtrTy);
988 
989   // Add the block literal.
990   CallArgList Args;
991   Args.add(RValue::get(BlockPtr), getContext().VoidPtrTy);
992 
993   QualType FnType = BPT->getPointeeType();
994 
995   // And the rest of the arguments.
996   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
997 
998   // Load the function.
999   llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1000 
1001   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1002   const CGFunctionInfo &FnInfo =
1003     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1004 
1005   // Cast the function pointer to the right type.
1006   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1007 
1008   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1009   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
1010 
1011   // Prepare the callee.
1012   CGCallee Callee(CGCalleeInfo(), Func);
1013 
1014   // And call the block.
1015   return EmitCall(FnInfo, Callee, ReturnValue, Args);
1016 }
1017 
1018 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1019                                             bool isByRef) {
1020   assert(BlockInfo && "evaluating block ref without block information?");
1021   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1022 
1023   // Handle constant captures.
1024   if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1025 
1026   Address addr =
1027     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1028                             capture.getOffset(), "block.capture.addr");
1029 
1030   if (isByRef) {
1031     // addr should be a void** right now.  Load, then cast the result
1032     // to byref*.
1033 
1034     auto &byrefInfo = getBlockByrefInfo(variable);
1035     addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1036 
1037     auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1038     addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1039 
1040     addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1041                                  variable->getName());
1042   }
1043 
1044   if (auto refType = capture.fieldType()->getAs<ReferenceType>())
1045     addr = EmitLoadOfReference(addr, refType);
1046 
1047   return addr;
1048 }
1049 
1050 llvm::Constant *
1051 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1052                                     StringRef Name) {
1053   CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1054   blockInfo.BlockExpression = BE;
1055 
1056   // Compute information about the layout, etc., of this block.
1057   computeBlockInfo(*this, nullptr, blockInfo);
1058 
1059   // Using that metadata, generate the actual block function.
1060   llvm::Constant *blockFn;
1061   {
1062     CodeGenFunction::DeclMapTy LocalDeclMap;
1063     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1064                                                            blockInfo,
1065                                                            LocalDeclMap,
1066                                                            false);
1067   }
1068   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1069 
1070   return buildGlobalBlock(*this, blockInfo, blockFn);
1071 }
1072 
1073 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1074                                         const CGBlockInfo &blockInfo,
1075                                         llvm::Constant *blockFn) {
1076   assert(blockInfo.CanBeGlobal);
1077 
1078   // Generate the constants for the block literal initializer.
1079   ConstantBuilder builder(CGM);
1080   auto fields = builder.beginStruct();
1081 
1082   // isa
1083   fields.add(CGM.getNSConcreteGlobalBlock());
1084 
1085   // __flags
1086   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1087   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1088 
1089   fields.addInt(CGM.IntTy, flags.getBitMask());
1090 
1091   // Reserved
1092   fields.addInt(CGM.IntTy, 0);
1093 
1094   // Function
1095   fields.add(blockFn);
1096 
1097   // Descriptor
1098   fields.add(buildBlockDescriptor(CGM, blockInfo));
1099 
1100   llvm::Constant *literal =
1101     fields.finishAndCreateGlobal("__block_literal_global",
1102                                  blockInfo.BlockAlign,
1103                                  /*constant*/ true);
1104 
1105   // Return a constant of the appropriately-casted type.
1106   llvm::Type *requiredType =
1107     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1108   return llvm::ConstantExpr::getBitCast(literal, requiredType);
1109 }
1110 
1111 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1112                                                unsigned argNum,
1113                                                llvm::Value *arg) {
1114   assert(BlockInfo && "not emitting prologue of block invocation function?!");
1115 
1116   llvm::Value *localAddr = nullptr;
1117   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1118     // Allocate a stack slot to let the debug info survive the RA.
1119     Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1120     Builder.CreateStore(arg, alloc);
1121     localAddr = Builder.CreateLoad(alloc);
1122   }
1123 
1124   if (CGDebugInfo *DI = getDebugInfo()) {
1125     if (CGM.getCodeGenOpts().getDebugInfo() >=
1126         codegenoptions::LimitedDebugInfo) {
1127       DI->setLocation(D->getLocation());
1128       DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1129                                                localAddr, Builder);
1130     }
1131   }
1132 
1133   SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1134   ApplyDebugLocation Scope(*this, StartLoc);
1135 
1136   // Instead of messing around with LocalDeclMap, just set the value
1137   // directly as BlockPointer.
1138   BlockPointer = Builder.CreateBitCast(arg,
1139                                        BlockInfo->StructureType->getPointerTo(),
1140                                        "block");
1141 }
1142 
1143 Address CodeGenFunction::LoadBlockStruct() {
1144   assert(BlockInfo && "not in a block invocation function!");
1145   assert(BlockPointer && "no block pointer set!");
1146   return Address(BlockPointer, BlockInfo->BlockAlign);
1147 }
1148 
1149 llvm::Function *
1150 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1151                                        const CGBlockInfo &blockInfo,
1152                                        const DeclMapTy &ldm,
1153                                        bool IsLambdaConversionToBlock) {
1154   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1155 
1156   CurGD = GD;
1157 
1158   CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1159 
1160   BlockInfo = &blockInfo;
1161 
1162   // Arrange for local static and local extern declarations to appear
1163   // to be local to this function as well, in case they're directly
1164   // referenced in a block.
1165   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1166     const auto *var = dyn_cast<VarDecl>(i->first);
1167     if (var && !var->hasLocalStorage())
1168       setAddrOfLocalVar(var, i->second);
1169   }
1170 
1171   // Begin building the function declaration.
1172 
1173   // Build the argument list.
1174   FunctionArgList args;
1175 
1176   // The first argument is the block pointer.  Just take it as a void*
1177   // and cast it later.
1178   QualType selfTy = getContext().VoidPtrTy;
1179   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1180 
1181   ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1182                              SourceLocation(), II, selfTy);
1183   args.push_back(&selfDecl);
1184 
1185   // Now add the rest of the parameters.
1186   args.append(blockDecl->param_begin(), blockDecl->param_end());
1187 
1188   // Create the function declaration.
1189   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1190   const CGFunctionInfo &fnInfo =
1191     CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1192   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1193     blockInfo.UsesStret = true;
1194 
1195   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1196 
1197   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1198   llvm::Function *fn = llvm::Function::Create(
1199       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1200   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1201 
1202   // Begin generating the function.
1203   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1204                 blockDecl->getLocation(),
1205                 blockInfo.getBlockExpr()->getBody()->getLocStart());
1206 
1207   // Okay.  Undo some of what StartFunction did.
1208 
1209   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1210   // won't delete the dbg.declare intrinsics for captured variables.
1211   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1212   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1213     // Allocate a stack slot for it, so we can point the debugger to it
1214     Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1215                                       getPointerAlign(),
1216                                       "block.addr");
1217     // Set the DebugLocation to empty, so the store is recognized as a
1218     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1219     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1220     Builder.CreateStore(BlockPointer, Alloca);
1221     BlockPointerDbgLoc = Alloca.getPointer();
1222   }
1223 
1224   // If we have a C++ 'this' reference, go ahead and force it into
1225   // existence now.
1226   if (blockDecl->capturesCXXThis()) {
1227     Address addr =
1228       Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1229                               blockInfo.CXXThisOffset, "block.captured-this");
1230     CXXThisValue = Builder.CreateLoad(addr, "this");
1231   }
1232 
1233   // Also force all the constant captures.
1234   for (const auto &CI : blockDecl->captures()) {
1235     const VarDecl *variable = CI.getVariable();
1236     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1237     if (!capture.isConstant()) continue;
1238 
1239     CharUnits align = getContext().getDeclAlign(variable);
1240     Address alloca =
1241       CreateMemTemp(variable->getType(), align, "block.captured-const");
1242 
1243     Builder.CreateStore(capture.getConstant(), alloca);
1244 
1245     setAddrOfLocalVar(variable, alloca);
1246   }
1247 
1248   // Save a spot to insert the debug information for all the DeclRefExprs.
1249   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1250   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1251   --entry_ptr;
1252 
1253   if (IsLambdaConversionToBlock)
1254     EmitLambdaBlockInvokeBody();
1255   else {
1256     PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1257     incrementProfileCounter(blockDecl->getBody());
1258     EmitStmt(blockDecl->getBody());
1259   }
1260 
1261   // Remember where we were...
1262   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1263 
1264   // Go back to the entry.
1265   ++entry_ptr;
1266   Builder.SetInsertPoint(entry, entry_ptr);
1267 
1268   // Emit debug information for all the DeclRefExprs.
1269   // FIXME: also for 'this'
1270   if (CGDebugInfo *DI = getDebugInfo()) {
1271     for (const auto &CI : blockDecl->captures()) {
1272       const VarDecl *variable = CI.getVariable();
1273       DI->EmitLocation(Builder, variable->getLocation());
1274 
1275       if (CGM.getCodeGenOpts().getDebugInfo() >=
1276           codegenoptions::LimitedDebugInfo) {
1277         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1278         if (capture.isConstant()) {
1279           auto addr = LocalDeclMap.find(variable)->second;
1280           DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1281                                         Builder);
1282           continue;
1283         }
1284 
1285         DI->EmitDeclareOfBlockDeclRefVariable(
1286             variable, BlockPointerDbgLoc, Builder, blockInfo,
1287             entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1288       }
1289     }
1290     // Recover location if it was changed in the above loop.
1291     DI->EmitLocation(Builder,
1292                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1293   }
1294 
1295   // And resume where we left off.
1296   if (resume == nullptr)
1297     Builder.ClearInsertionPoint();
1298   else
1299     Builder.SetInsertPoint(resume);
1300 
1301   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1302 
1303   return fn;
1304 }
1305 
1306 /*
1307     notes.push_back(HelperInfo());
1308     HelperInfo &note = notes.back();
1309     note.index = capture.getIndex();
1310     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1311     note.cxxbar_import = ci->getCopyExpr();
1312 
1313     if (ci->isByRef()) {
1314       note.flag = BLOCK_FIELD_IS_BYREF;
1315       if (type.isObjCGCWeak())
1316         note.flag |= BLOCK_FIELD_IS_WEAK;
1317     } else if (type->isBlockPointerType()) {
1318       note.flag = BLOCK_FIELD_IS_BLOCK;
1319     } else {
1320       note.flag = BLOCK_FIELD_IS_OBJECT;
1321     }
1322  */
1323 
1324 /// Generate the copy-helper function for a block closure object:
1325 ///   static void block_copy_helper(block_t *dst, block_t *src);
1326 /// The runtime will have previously initialized 'dst' by doing a
1327 /// bit-copy of 'src'.
1328 ///
1329 /// Note that this copies an entire block closure object to the heap;
1330 /// it should not be confused with a 'byref copy helper', which moves
1331 /// the contents of an individual __block variable to the heap.
1332 llvm::Constant *
1333 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1334   ASTContext &C = getContext();
1335 
1336   FunctionArgList args;
1337   ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1338                             C.VoidPtrTy);
1339   args.push_back(&dstDecl);
1340   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1341                             C.VoidPtrTy);
1342   args.push_back(&srcDecl);
1343 
1344   const CGFunctionInfo &FI =
1345     CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1346 
1347   // FIXME: it would be nice if these were mergeable with things with
1348   // identical semantics.
1349   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1350 
1351   llvm::Function *Fn =
1352     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1353                            "__copy_helper_block_", &CGM.getModule());
1354 
1355   IdentifierInfo *II
1356     = &CGM.getContext().Idents.get("__copy_helper_block_");
1357 
1358   FunctionDecl *FD = FunctionDecl::Create(C,
1359                                           C.getTranslationUnitDecl(),
1360                                           SourceLocation(),
1361                                           SourceLocation(), II, C.VoidTy,
1362                                           nullptr, SC_Static,
1363                                           false,
1364                                           false);
1365 
1366   CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1367 
1368   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1369   StartFunction(FD, C.VoidTy, Fn, FI, args);
1370   // Create a scope with an artificial location for the body of this function.
1371   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1372   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1373 
1374   Address src = GetAddrOfLocalVar(&srcDecl);
1375   src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1376   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1377 
1378   Address dst = GetAddrOfLocalVar(&dstDecl);
1379   dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1380   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1381 
1382   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1383 
1384   for (const auto &CI : blockDecl->captures()) {
1385     const VarDecl *variable = CI.getVariable();
1386     QualType type = variable->getType();
1387 
1388     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1389     if (capture.isConstant()) continue;
1390 
1391     const Expr *copyExpr = CI.getCopyExpr();
1392     BlockFieldFlags flags;
1393 
1394     bool useARCWeakCopy = false;
1395     bool useARCStrongCopy = false;
1396 
1397     if (copyExpr) {
1398       assert(!CI.isByRef());
1399       // don't bother computing flags
1400 
1401     } else if (CI.isByRef()) {
1402       flags = BLOCK_FIELD_IS_BYREF;
1403       if (type.isObjCGCWeak())
1404         flags |= BLOCK_FIELD_IS_WEAK;
1405 
1406     } else if (type->isObjCRetainableType()) {
1407       flags = BLOCK_FIELD_IS_OBJECT;
1408       bool isBlockPointer = type->isBlockPointerType();
1409       if (isBlockPointer)
1410         flags = BLOCK_FIELD_IS_BLOCK;
1411 
1412       // Special rules for ARC captures:
1413       Qualifiers qs = type.getQualifiers();
1414 
1415       // We need to register __weak direct captures with the runtime.
1416       if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1417         useARCWeakCopy = true;
1418 
1419       // We need to retain the copied value for __strong direct captures.
1420       } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1421         // If it's a block pointer, we have to copy the block and
1422         // assign that to the destination pointer, so we might as
1423         // well use _Block_object_assign.  Otherwise we can avoid that.
1424         if (!isBlockPointer)
1425           useARCStrongCopy = true;
1426 
1427       // Non-ARC captures of retainable pointers are strong and
1428       // therefore require a call to _Block_object_assign.
1429       } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1430         // fall through
1431 
1432       // Otherwise the memcpy is fine.
1433       } else {
1434         continue;
1435       }
1436 
1437     // For all other types, the memcpy is fine.
1438     } else {
1439       continue;
1440     }
1441 
1442     unsigned index = capture.getIndex();
1443     Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1444     Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1445 
1446     // If there's an explicit copy expression, we do that.
1447     if (copyExpr) {
1448       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1449     } else if (useARCWeakCopy) {
1450       EmitARCCopyWeak(dstField, srcField);
1451     } else {
1452       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1453       if (useARCStrongCopy) {
1454         // At -O0, store null into the destination field (so that the
1455         // storeStrong doesn't over-release) and then call storeStrong.
1456         // This is a workaround to not having an initStrong call.
1457         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1458           auto *ty = cast<llvm::PointerType>(srcValue->getType());
1459           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1460           Builder.CreateStore(null, dstField);
1461           EmitARCStoreStrongCall(dstField, srcValue, true);
1462 
1463         // With optimization enabled, take advantage of the fact that
1464         // the blocks runtime guarantees a memcpy of the block data, and
1465         // just emit a retain of the src field.
1466         } else {
1467           EmitARCRetainNonBlock(srcValue);
1468 
1469           // We don't need this anymore, so kill it.  It's not quite
1470           // worth the annoyance to avoid creating it in the first place.
1471           cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1472         }
1473       } else {
1474         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1475         llvm::Value *dstAddr =
1476           Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1477         llvm::Value *args[] = {
1478           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1479         };
1480 
1481         bool copyCanThrow = false;
1482         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1483           const Expr *copyExpr =
1484             CGM.getContext().getBlockVarCopyInits(variable);
1485           if (copyExpr) {
1486             copyCanThrow = true; // FIXME: reuse the noexcept logic
1487           }
1488         }
1489 
1490         if (copyCanThrow) {
1491           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1492         } else {
1493           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1494         }
1495       }
1496     }
1497   }
1498 
1499   FinishFunction();
1500 
1501   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1502 }
1503 
1504 /// Generate the destroy-helper function for a block closure object:
1505 ///   static void block_destroy_helper(block_t *theBlock);
1506 ///
1507 /// Note that this destroys a heap-allocated block closure object;
1508 /// it should not be confused with a 'byref destroy helper', which
1509 /// destroys the heap-allocated contents of an individual __block
1510 /// variable.
1511 llvm::Constant *
1512 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1513   ASTContext &C = getContext();
1514 
1515   FunctionArgList args;
1516   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1517                             C.VoidPtrTy);
1518   args.push_back(&srcDecl);
1519 
1520   const CGFunctionInfo &FI =
1521     CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1522 
1523   // FIXME: We'd like to put these into a mergable by content, with
1524   // internal linkage.
1525   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1526 
1527   llvm::Function *Fn =
1528     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1529                            "__destroy_helper_block_", &CGM.getModule());
1530 
1531   IdentifierInfo *II
1532     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1533 
1534   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1535                                           SourceLocation(),
1536                                           SourceLocation(), II, C.VoidTy,
1537                                           nullptr, SC_Static,
1538                                           false, false);
1539 
1540   CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1541 
1542   // Create a scope with an artificial location for the body of this function.
1543   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1544   StartFunction(FD, C.VoidTy, Fn, FI, args);
1545   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1546 
1547   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1548 
1549   Address src = GetAddrOfLocalVar(&srcDecl);
1550   src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1551   src = Builder.CreateBitCast(src, structPtrTy, "block");
1552 
1553   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1554 
1555   CodeGenFunction::RunCleanupsScope cleanups(*this);
1556 
1557   for (const auto &CI : blockDecl->captures()) {
1558     const VarDecl *variable = CI.getVariable();
1559     QualType type = variable->getType();
1560 
1561     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1562     if (capture.isConstant()) continue;
1563 
1564     BlockFieldFlags flags;
1565     const CXXDestructorDecl *dtor = nullptr;
1566 
1567     bool useARCWeakDestroy = false;
1568     bool useARCStrongDestroy = false;
1569 
1570     if (CI.isByRef()) {
1571       flags = BLOCK_FIELD_IS_BYREF;
1572       if (type.isObjCGCWeak())
1573         flags |= BLOCK_FIELD_IS_WEAK;
1574     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1575       if (record->hasTrivialDestructor())
1576         continue;
1577       dtor = record->getDestructor();
1578     } else if (type->isObjCRetainableType()) {
1579       flags = BLOCK_FIELD_IS_OBJECT;
1580       if (type->isBlockPointerType())
1581         flags = BLOCK_FIELD_IS_BLOCK;
1582 
1583       // Special rules for ARC captures.
1584       Qualifiers qs = type.getQualifiers();
1585 
1586       // Use objc_storeStrong for __strong direct captures; the
1587       // dynamic tools really like it when we do this.
1588       if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1589         useARCStrongDestroy = true;
1590 
1591       // Support __weak direct captures.
1592       } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1593         useARCWeakDestroy = true;
1594 
1595       // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1596       } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1597         // fall through
1598 
1599       // Otherwise, we have nothing to do.
1600       } else {
1601         continue;
1602       }
1603     } else {
1604       continue;
1605     }
1606 
1607     Address srcField =
1608       Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1609 
1610     // If there's an explicit copy expression, we do that.
1611     if (dtor) {
1612       PushDestructorCleanup(dtor, srcField);
1613 
1614     // If this is a __weak capture, emit the release directly.
1615     } else if (useARCWeakDestroy) {
1616       EmitARCDestroyWeak(srcField);
1617 
1618     // Destroy strong objects with a call if requested.
1619     } else if (useARCStrongDestroy) {
1620       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1621 
1622     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1623     // hard to just emit this as a cleanup if we wanted to make sure
1624     // that things were done in reverse.
1625     } else {
1626       llvm::Value *value = Builder.CreateLoad(srcField);
1627       value = Builder.CreateBitCast(value, VoidPtrTy);
1628       BuildBlockRelease(value, flags);
1629     }
1630   }
1631 
1632   cleanups.ForceCleanup();
1633 
1634   FinishFunction();
1635 
1636   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1637 }
1638 
1639 namespace {
1640 
1641 /// Emits the copy/dispose helper functions for a __block object of id type.
1642 class ObjectByrefHelpers final : public BlockByrefHelpers {
1643   BlockFieldFlags Flags;
1644 
1645 public:
1646   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1647     : BlockByrefHelpers(alignment), Flags(flags) {}
1648 
1649   void emitCopy(CodeGenFunction &CGF, Address destField,
1650                 Address srcField) override {
1651     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1652 
1653     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1654     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1655 
1656     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1657 
1658     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1659     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1660 
1661     llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1662     CGF.EmitNounwindRuntimeCall(fn, args);
1663   }
1664 
1665   void emitDispose(CodeGenFunction &CGF, Address field) override {
1666     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1667     llvm::Value *value = CGF.Builder.CreateLoad(field);
1668 
1669     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1670   }
1671 
1672   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1673     id.AddInteger(Flags.getBitMask());
1674   }
1675 };
1676 
1677 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1678 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1679 public:
1680   ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1681 
1682   void emitCopy(CodeGenFunction &CGF, Address destField,
1683                 Address srcField) override {
1684     CGF.EmitARCMoveWeak(destField, srcField);
1685   }
1686 
1687   void emitDispose(CodeGenFunction &CGF, Address field) override {
1688     CGF.EmitARCDestroyWeak(field);
1689   }
1690 
1691   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1692     // 0 is distinguishable from all pointers and byref flags
1693     id.AddInteger(0);
1694   }
1695 };
1696 
1697 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1698 /// that's not of block-pointer type.
1699 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1700 public:
1701   ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1702 
1703   void emitCopy(CodeGenFunction &CGF, Address destField,
1704                 Address srcField) override {
1705     // Do a "move" by copying the value and then zeroing out the old
1706     // variable.
1707 
1708     llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1709 
1710     llvm::Value *null =
1711       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1712 
1713     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1714       CGF.Builder.CreateStore(null, destField);
1715       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1716       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1717       return;
1718     }
1719     CGF.Builder.CreateStore(value, destField);
1720     CGF.Builder.CreateStore(null, srcField);
1721   }
1722 
1723   void emitDispose(CodeGenFunction &CGF, Address field) override {
1724     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1725   }
1726 
1727   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1728     // 1 is distinguishable from all pointers and byref flags
1729     id.AddInteger(1);
1730   }
1731 };
1732 
1733 /// Emits the copy/dispose helpers for an ARC __block __strong
1734 /// variable that's of block-pointer type.
1735 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1736 public:
1737   ARCStrongBlockByrefHelpers(CharUnits alignment)
1738     : BlockByrefHelpers(alignment) {}
1739 
1740   void emitCopy(CodeGenFunction &CGF, Address destField,
1741                 Address srcField) override {
1742     // Do the copy with objc_retainBlock; that's all that
1743     // _Block_object_assign would do anyway, and we'd have to pass the
1744     // right arguments to make sure it doesn't get no-op'ed.
1745     llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1746     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1747     CGF.Builder.CreateStore(copy, destField);
1748   }
1749 
1750   void emitDispose(CodeGenFunction &CGF, Address field) override {
1751     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1752   }
1753 
1754   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1755     // 2 is distinguishable from all pointers and byref flags
1756     id.AddInteger(2);
1757   }
1758 };
1759 
1760 /// Emits the copy/dispose helpers for a __block variable with a
1761 /// nontrivial copy constructor or destructor.
1762 class CXXByrefHelpers final : public BlockByrefHelpers {
1763   QualType VarType;
1764   const Expr *CopyExpr;
1765 
1766 public:
1767   CXXByrefHelpers(CharUnits alignment, QualType type,
1768                   const Expr *copyExpr)
1769     : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1770 
1771   bool needsCopy() const override { return CopyExpr != nullptr; }
1772   void emitCopy(CodeGenFunction &CGF, Address destField,
1773                 Address srcField) override {
1774     if (!CopyExpr) return;
1775     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1776   }
1777 
1778   void emitDispose(CodeGenFunction &CGF, Address field) override {
1779     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1780     CGF.PushDestructorCleanup(VarType, field);
1781     CGF.PopCleanupBlocks(cleanupDepth);
1782   }
1783 
1784   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1785     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1786   }
1787 };
1788 } // end anonymous namespace
1789 
1790 static llvm::Constant *
1791 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1792                         BlockByrefHelpers &generator) {
1793   ASTContext &Context = CGF.getContext();
1794 
1795   QualType R = Context.VoidTy;
1796 
1797   FunctionArgList args;
1798   ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1799                         Context.VoidPtrTy);
1800   args.push_back(&dst);
1801 
1802   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1803                         Context.VoidPtrTy);
1804   args.push_back(&src);
1805 
1806   const CGFunctionInfo &FI =
1807     CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1808 
1809   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1810 
1811   // FIXME: We'd like to put these into a mergable by content, with
1812   // internal linkage.
1813   llvm::Function *Fn =
1814     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1815                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1816 
1817   IdentifierInfo *II
1818     = &Context.Idents.get("__Block_byref_object_copy_");
1819 
1820   FunctionDecl *FD = FunctionDecl::Create(Context,
1821                                           Context.getTranslationUnitDecl(),
1822                                           SourceLocation(),
1823                                           SourceLocation(), II, R, nullptr,
1824                                           SC_Static,
1825                                           false, false);
1826 
1827   CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1828 
1829   CGF.StartFunction(FD, R, Fn, FI, args);
1830 
1831   if (generator.needsCopy()) {
1832     llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1833 
1834     // dst->x
1835     Address destField = CGF.GetAddrOfLocalVar(&dst);
1836     destField = Address(CGF.Builder.CreateLoad(destField),
1837                         byrefInfo.ByrefAlignment);
1838     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1839     destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1840                                           "dest-object");
1841 
1842     // src->x
1843     Address srcField = CGF.GetAddrOfLocalVar(&src);
1844     srcField = Address(CGF.Builder.CreateLoad(srcField),
1845                        byrefInfo.ByrefAlignment);
1846     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1847     srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1848                                          "src-object");
1849 
1850     generator.emitCopy(CGF, destField, srcField);
1851   }
1852 
1853   CGF.FinishFunction();
1854 
1855   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1856 }
1857 
1858 /// Build the copy helper for a __block variable.
1859 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1860                                             const BlockByrefInfo &byrefInfo,
1861                                             BlockByrefHelpers &generator) {
1862   CodeGenFunction CGF(CGM);
1863   return generateByrefCopyHelper(CGF, byrefInfo, generator);
1864 }
1865 
1866 /// Generate code for a __block variable's dispose helper.
1867 static llvm::Constant *
1868 generateByrefDisposeHelper(CodeGenFunction &CGF,
1869                            const BlockByrefInfo &byrefInfo,
1870                            BlockByrefHelpers &generator) {
1871   ASTContext &Context = CGF.getContext();
1872   QualType R = Context.VoidTy;
1873 
1874   FunctionArgList args;
1875   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1876                         Context.VoidPtrTy);
1877   args.push_back(&src);
1878 
1879   const CGFunctionInfo &FI =
1880     CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1881 
1882   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1883 
1884   // FIXME: We'd like to put these into a mergable by content, with
1885   // internal linkage.
1886   llvm::Function *Fn =
1887     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1888                            "__Block_byref_object_dispose_",
1889                            &CGF.CGM.getModule());
1890 
1891   IdentifierInfo *II
1892     = &Context.Idents.get("__Block_byref_object_dispose_");
1893 
1894   FunctionDecl *FD = FunctionDecl::Create(Context,
1895                                           Context.getTranslationUnitDecl(),
1896                                           SourceLocation(),
1897                                           SourceLocation(), II, R, nullptr,
1898                                           SC_Static,
1899                                           false, false);
1900 
1901   CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1902 
1903   CGF.StartFunction(FD, R, Fn, FI, args);
1904 
1905   if (generator.needsDispose()) {
1906     Address addr = CGF.GetAddrOfLocalVar(&src);
1907     addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1908     auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1909     addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1910     addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1911 
1912     generator.emitDispose(CGF, addr);
1913   }
1914 
1915   CGF.FinishFunction();
1916 
1917   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1918 }
1919 
1920 /// Build the dispose helper for a __block variable.
1921 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1922                                                const BlockByrefInfo &byrefInfo,
1923                                                BlockByrefHelpers &generator) {
1924   CodeGenFunction CGF(CGM);
1925   return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1926 }
1927 
1928 /// Lazily build the copy and dispose helpers for a __block variable
1929 /// with the given information.
1930 template <class T>
1931 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1932                             T &&generator) {
1933   llvm::FoldingSetNodeID id;
1934   generator.Profile(id);
1935 
1936   void *insertPos;
1937   BlockByrefHelpers *node
1938     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1939   if (node) return static_cast<T*>(node);
1940 
1941   generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1942   generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1943 
1944   T *copy = new (CGM.getContext()) T(std::move(generator));
1945   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1946   return copy;
1947 }
1948 
1949 /// Build the copy and dispose helpers for the given __block variable
1950 /// emission.  Places the helpers in the global cache.  Returns null
1951 /// if no helpers are required.
1952 BlockByrefHelpers *
1953 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1954                                    const AutoVarEmission &emission) {
1955   const VarDecl &var = *emission.Variable;
1956   QualType type = var.getType();
1957 
1958   auto &byrefInfo = getBlockByrefInfo(&var);
1959 
1960   // The alignment we care about for the purposes of uniquing byref
1961   // helpers is the alignment of the actual byref value field.
1962   CharUnits valueAlignment =
1963     byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1964 
1965   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1966     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1967     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1968 
1969     return ::buildByrefHelpers(
1970         CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1971   }
1972 
1973   // Otherwise, if we don't have a retainable type, there's nothing to do.
1974   // that the runtime does extra copies.
1975   if (!type->isObjCRetainableType()) return nullptr;
1976 
1977   Qualifiers qs = type.getQualifiers();
1978 
1979   // If we have lifetime, that dominates.
1980   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1981     switch (lifetime) {
1982     case Qualifiers::OCL_None: llvm_unreachable("impossible");
1983 
1984     // These are just bits as far as the runtime is concerned.
1985     case Qualifiers::OCL_ExplicitNone:
1986     case Qualifiers::OCL_Autoreleasing:
1987       return nullptr;
1988 
1989     // Tell the runtime that this is ARC __weak, called by the
1990     // byref routines.
1991     case Qualifiers::OCL_Weak:
1992       return ::buildByrefHelpers(CGM, byrefInfo,
1993                                  ARCWeakByrefHelpers(valueAlignment));
1994 
1995     // ARC __strong __block variables need to be retained.
1996     case Qualifiers::OCL_Strong:
1997       // Block pointers need to be copied, and there's no direct
1998       // transfer possible.
1999       if (type->isBlockPointerType()) {
2000         return ::buildByrefHelpers(CGM, byrefInfo,
2001                                    ARCStrongBlockByrefHelpers(valueAlignment));
2002 
2003       // Otherwise, we transfer ownership of the retain from the stack
2004       // to the heap.
2005       } else {
2006         return ::buildByrefHelpers(CGM, byrefInfo,
2007                                    ARCStrongByrefHelpers(valueAlignment));
2008       }
2009     }
2010     llvm_unreachable("fell out of lifetime switch!");
2011   }
2012 
2013   BlockFieldFlags flags;
2014   if (type->isBlockPointerType()) {
2015     flags |= BLOCK_FIELD_IS_BLOCK;
2016   } else if (CGM.getContext().isObjCNSObjectType(type) ||
2017              type->isObjCObjectPointerType()) {
2018     flags |= BLOCK_FIELD_IS_OBJECT;
2019   } else {
2020     return nullptr;
2021   }
2022 
2023   if (type.isObjCGCWeak())
2024     flags |= BLOCK_FIELD_IS_WEAK;
2025 
2026   return ::buildByrefHelpers(CGM, byrefInfo,
2027                              ObjectByrefHelpers(valueAlignment, flags));
2028 }
2029 
2030 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2031                                                const VarDecl *var,
2032                                                bool followForward) {
2033   auto &info = getBlockByrefInfo(var);
2034   return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2035 }
2036 
2037 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2038                                                const BlockByrefInfo &info,
2039                                                bool followForward,
2040                                                const llvm::Twine &name) {
2041   // Chase the forwarding address if requested.
2042   if (followForward) {
2043     Address forwardingAddr =
2044       Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2045     baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2046   }
2047 
2048   return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2049                                  info.FieldOffset, name);
2050 }
2051 
2052 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2053 ///   into:
2054 ///
2055 ///      struct {
2056 ///        void *__isa;
2057 ///        void *__forwarding;
2058 ///        int32_t __flags;
2059 ///        int32_t __size;
2060 ///        void *__copy_helper;       // only if needed
2061 ///        void *__destroy_helper;    // only if needed
2062 ///        void *__byref_variable_layout;// only if needed
2063 ///        char padding[X];           // only if needed
2064 ///        T x;
2065 ///      } x
2066 ///
2067 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2068   auto it = BlockByrefInfos.find(D);
2069   if (it != BlockByrefInfos.end())
2070     return it->second;
2071 
2072   llvm::StructType *byrefType =
2073     llvm::StructType::create(getLLVMContext(),
2074                              "struct.__block_byref_" + D->getNameAsString());
2075 
2076   QualType Ty = D->getType();
2077 
2078   CharUnits size;
2079   SmallVector<llvm::Type *, 8> types;
2080 
2081   // void *__isa;
2082   types.push_back(Int8PtrTy);
2083   size += getPointerSize();
2084 
2085   // void *__forwarding;
2086   types.push_back(llvm::PointerType::getUnqual(byrefType));
2087   size += getPointerSize();
2088 
2089   // int32_t __flags;
2090   types.push_back(Int32Ty);
2091   size += CharUnits::fromQuantity(4);
2092 
2093   // int32_t __size;
2094   types.push_back(Int32Ty);
2095   size += CharUnits::fromQuantity(4);
2096 
2097   // Note that this must match *exactly* the logic in buildByrefHelpers.
2098   bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2099   if (hasCopyAndDispose) {
2100     /// void *__copy_helper;
2101     types.push_back(Int8PtrTy);
2102     size += getPointerSize();
2103 
2104     /// void *__destroy_helper;
2105     types.push_back(Int8PtrTy);
2106     size += getPointerSize();
2107   }
2108 
2109   bool HasByrefExtendedLayout = false;
2110   Qualifiers::ObjCLifetime Lifetime;
2111   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2112       HasByrefExtendedLayout) {
2113     /// void *__byref_variable_layout;
2114     types.push_back(Int8PtrTy);
2115     size += CharUnits::fromQuantity(PointerSizeInBytes);
2116   }
2117 
2118   // T x;
2119   llvm::Type *varTy = ConvertTypeForMem(Ty);
2120 
2121   bool packed = false;
2122   CharUnits varAlign = getContext().getDeclAlign(D);
2123   CharUnits varOffset = size.alignTo(varAlign);
2124 
2125   // We may have to insert padding.
2126   if (varOffset != size) {
2127     llvm::Type *paddingTy =
2128       llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2129 
2130     types.push_back(paddingTy);
2131     size = varOffset;
2132 
2133   // Conversely, we might have to prevent LLVM from inserting padding.
2134   } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2135                > varAlign.getQuantity()) {
2136     packed = true;
2137   }
2138   types.push_back(varTy);
2139 
2140   byrefType->setBody(types, packed);
2141 
2142   BlockByrefInfo info;
2143   info.Type = byrefType;
2144   info.FieldIndex = types.size() - 1;
2145   info.FieldOffset = varOffset;
2146   info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2147 
2148   auto pair = BlockByrefInfos.insert({D, info});
2149   assert(pair.second && "info was inserted recursively?");
2150   return pair.first->second;
2151 }
2152 
2153 /// Initialize the structural components of a __block variable, i.e.
2154 /// everything but the actual object.
2155 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2156   // Find the address of the local.
2157   Address addr = emission.Addr;
2158 
2159   // That's an alloca of the byref structure type.
2160   llvm::StructType *byrefType = cast<llvm::StructType>(
2161     cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2162 
2163   unsigned nextHeaderIndex = 0;
2164   CharUnits nextHeaderOffset;
2165   auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2166                               const Twine &name) {
2167     auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2168                                              nextHeaderOffset, name);
2169     Builder.CreateStore(value, fieldAddr);
2170 
2171     nextHeaderIndex++;
2172     nextHeaderOffset += fieldSize;
2173   };
2174 
2175   // Build the byref helpers if necessary.  This is null if we don't need any.
2176   BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2177 
2178   const VarDecl &D = *emission.Variable;
2179   QualType type = D.getType();
2180 
2181   bool HasByrefExtendedLayout;
2182   Qualifiers::ObjCLifetime ByrefLifetime;
2183   bool ByRefHasLifetime =
2184     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2185 
2186   llvm::Value *V;
2187 
2188   // Initialize the 'isa', which is just 0 or 1.
2189   int isa = 0;
2190   if (type.isObjCGCWeak())
2191     isa = 1;
2192   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2193   storeHeaderField(V, getPointerSize(), "byref.isa");
2194 
2195   // Store the address of the variable into its own forwarding pointer.
2196   storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2197 
2198   // Blocks ABI:
2199   //   c) the flags field is set to either 0 if no helper functions are
2200   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2201   BlockFlags flags;
2202   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2203   if (ByRefHasLifetime) {
2204     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2205       else switch (ByrefLifetime) {
2206         case Qualifiers::OCL_Strong:
2207           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2208           break;
2209         case Qualifiers::OCL_Weak:
2210           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2211           break;
2212         case Qualifiers::OCL_ExplicitNone:
2213           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2214           break;
2215         case Qualifiers::OCL_None:
2216           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2217             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2218           break;
2219         default:
2220           break;
2221       }
2222     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2223       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2224       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2225         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2226       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2227         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2228         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2229           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2230         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2231           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2232         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2233           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2234         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2235           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2236         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2237           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2238       }
2239       printf("\n");
2240     }
2241   }
2242   storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2243                    getIntSize(), "byref.flags");
2244 
2245   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2246   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2247   storeHeaderField(V, getIntSize(), "byref.size");
2248 
2249   if (helpers) {
2250     storeHeaderField(helpers->CopyHelper, getPointerSize(),
2251                      "byref.copyHelper");
2252     storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2253                      "byref.disposeHelper");
2254   }
2255 
2256   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2257     auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2258     storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2259   }
2260 }
2261 
2262 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2263   llvm::Value *F = CGM.getBlockObjectDispose();
2264   llvm::Value *args[] = {
2265     Builder.CreateBitCast(V, Int8PtrTy),
2266     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2267   };
2268   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2269 }
2270 
2271 namespace {
2272   /// Release a __block variable.
2273   struct CallBlockRelease final : EHScopeStack::Cleanup {
2274     llvm::Value *Addr;
2275     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2276 
2277     void Emit(CodeGenFunction &CGF, Flags flags) override {
2278       // Should we be passing FIELD_IS_WEAK here?
2279       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2280     }
2281   };
2282 } // end anonymous namespace
2283 
2284 /// Enter a cleanup to destroy a __block variable.  Note that this
2285 /// cleanup should be a no-op if the variable hasn't left the stack
2286 /// yet; if a cleanup is required for the variable itself, that needs
2287 /// to be done externally.
2288 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2289   // We don't enter this cleanup if we're in pure-GC mode.
2290   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2291     return;
2292 
2293   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2294                                         emission.Addr.getPointer());
2295 }
2296 
2297 /// Adjust the declaration of something from the blocks API.
2298 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2299                                          llvm::Constant *C) {
2300   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2301 
2302   if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2303     IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2304     TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2305     DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2306 
2307     assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2308             isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2309            "expected Function or GlobalVariable");
2310 
2311     const NamedDecl *ND = nullptr;
2312     for (const auto &Result : DC->lookup(&II))
2313       if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2314           (ND = dyn_cast<VarDecl>(Result)))
2315         break;
2316 
2317     // TODO: support static blocks runtime
2318     if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2319       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2320       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2321     } else {
2322       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2323       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2324     }
2325   }
2326 
2327   if (!CGM.getLangOpts().BlocksRuntimeOptional)
2328     return;
2329 
2330   if (GV->isDeclaration() && GV->hasExternalLinkage())
2331     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2332 }
2333 
2334 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2335   if (BlockObjectDispose)
2336     return BlockObjectDispose;
2337 
2338   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2339   llvm::FunctionType *fty
2340     = llvm::FunctionType::get(VoidTy, args, false);
2341   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2342   configureBlocksRuntimeObject(*this, BlockObjectDispose);
2343   return BlockObjectDispose;
2344 }
2345 
2346 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2347   if (BlockObjectAssign)
2348     return BlockObjectAssign;
2349 
2350   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2351   llvm::FunctionType *fty
2352     = llvm::FunctionType::get(VoidTy, args, false);
2353   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2354   configureBlocksRuntimeObject(*this, BlockObjectAssign);
2355   return BlockObjectAssign;
2356 }
2357 
2358 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2359   if (NSConcreteGlobalBlock)
2360     return NSConcreteGlobalBlock;
2361 
2362   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2363                                                 Int8PtrTy->getPointerTo(),
2364                                                 nullptr);
2365   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2366   return NSConcreteGlobalBlock;
2367 }
2368 
2369 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2370   if (NSConcreteStackBlock)
2371     return NSConcreteStackBlock;
2372 
2373   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2374                                                Int8PtrTy->getPointerTo(),
2375                                                nullptr);
2376   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2377   return NSConcreteStackBlock;
2378 }
2379