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