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     assert(endAlign >= li->Alignment);
543     li->setIndex(info, elementTypes.size());
544     elementTypes.push_back(li->Type);
545     blockSize += li->Size;
546     endAlign = getLowBit(blockSize);
547   }
548 
549   info.StructureType =
550     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
551 }
552 
553 /// Enter the scope of a block.  This should be run at the entrance to
554 /// a full-expression so that the block's cleanups are pushed at the
555 /// right place in the stack.
556 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
557   assert(CGF.HaveInsertPoint());
558 
559   // Allocate the block info and place it at the head of the list.
560   CGBlockInfo &blockInfo =
561     *new CGBlockInfo(block, CGF.CurFn->getName());
562   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
563   CGF.FirstBlockInfo = &blockInfo;
564 
565   // Compute information about the layout, etc., of this block,
566   // pushing cleanups as necessary.
567   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
568 
569   // Nothing else to do if it can be global.
570   if (blockInfo.CanBeGlobal) return;
571 
572   // Make the allocation for the block.
573   blockInfo.Address =
574     CGF.CreateTempAlloca(blockInfo.StructureType, "block");
575   blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
576 
577   // If there are cleanups to emit, enter them (but inactive).
578   if (!blockInfo.NeedsCopyDispose) return;
579 
580   // Walk through the captures (in order) and find the ones not
581   // captured by constant.
582   for (const auto &CI : block->captures()) {
583     // Ignore __block captures; there's nothing special in the
584     // on-stack block that we need to do for them.
585     if (CI.isByRef()) continue;
586 
587     // Ignore variables that are constant-captured.
588     const VarDecl *variable = CI.getVariable();
589     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
590     if (capture.isConstant()) continue;
591 
592     // Ignore objects that aren't destructed.
593     QualType::DestructionKind dtorKind =
594       variable->getType().isDestructedType();
595     if (dtorKind == QualType::DK_none) continue;
596 
597     CodeGenFunction::Destroyer *destroyer;
598 
599     // Block captures count as local values and have imprecise semantics.
600     // They also can't be arrays, so need to worry about that.
601     if (dtorKind == QualType::DK_objc_strong_lifetime) {
602       destroyer = CodeGenFunction::destroyARCStrongImprecise;
603     } else {
604       destroyer = CGF.getDestroyer(dtorKind);
605     }
606 
607     // GEP down to the address.
608     llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
609                                                     capture.getIndex());
610 
611     // We can use that GEP as the dominating IP.
612     if (!blockInfo.DominatingIP)
613       blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
614 
615     CleanupKind cleanupKind = InactiveNormalCleanup;
616     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
617     if (useArrayEHCleanup)
618       cleanupKind = InactiveNormalAndEHCleanup;
619 
620     CGF.pushDestroy(cleanupKind, addr, variable->getType(),
621                     destroyer, useArrayEHCleanup);
622 
623     // Remember where that cleanup was.
624     capture.setCleanup(CGF.EHStack.stable_begin());
625   }
626 }
627 
628 /// Enter a full-expression with a non-trivial number of objects to
629 /// clean up.  This is in this file because, at the moment, the only
630 /// kind of cleanup object is a BlockDecl*.
631 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
632   assert(E->getNumObjects() != 0);
633   ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
634   for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
635          i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
636     enterBlockScope(*this, *i);
637   }
638 }
639 
640 /// Find the layout for the given block in a linked list and remove it.
641 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
642                                            const BlockDecl *block) {
643   while (true) {
644     assert(head && *head);
645     CGBlockInfo *cur = *head;
646 
647     // If this is the block we're looking for, splice it out of the list.
648     if (cur->getBlockDecl() == block) {
649       *head = cur->NextBlockInfo;
650       return cur;
651     }
652 
653     head = &cur->NextBlockInfo;
654   }
655 }
656 
657 /// Destroy a chain of block layouts.
658 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
659   assert(head && "destroying an empty chain");
660   do {
661     CGBlockInfo *cur = head;
662     head = cur->NextBlockInfo;
663     delete cur;
664   } while (head != nullptr);
665 }
666 
667 /// Emit a block literal expression in the current function.
668 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
669   // If the block has no captures, we won't have a pre-computed
670   // layout for it.
671   if (!blockExpr->getBlockDecl()->hasCaptures()) {
672     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
673     computeBlockInfo(CGM, this, blockInfo);
674     blockInfo.BlockExpression = blockExpr;
675     return EmitBlockLiteral(blockInfo);
676   }
677 
678   // Find the block info for this block and take ownership of it.
679   std::unique_ptr<CGBlockInfo> blockInfo;
680   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
681                                          blockExpr->getBlockDecl()));
682 
683   blockInfo->BlockExpression = blockExpr;
684   return EmitBlockLiteral(*blockInfo);
685 }
686 
687 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
688   // Using the computed layout, generate the actual block function.
689   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
690   llvm::Constant *blockFn
691     = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
692                                                        LocalDeclMap,
693                                                        isLambdaConv);
694   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
695 
696   // If there is nothing to capture, we can emit this as a global block.
697   if (blockInfo.CanBeGlobal)
698     return buildGlobalBlock(CGM, blockInfo, blockFn);
699 
700   // Otherwise, we have to emit this as a local block.
701 
702   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
703   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
704 
705   // Build the block descriptor.
706   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
707 
708   llvm::AllocaInst *blockAddr = blockInfo.Address;
709   assert(blockAddr && "block has no address!");
710 
711   // Compute the initial on-stack block flags.
712   BlockFlags flags = BLOCK_HAS_SIGNATURE;
713   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
714   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
715   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
716   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
717 
718   // Initialize the block literal.
719   Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
720   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
721                       Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
722   Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
723                       Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
724   Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
725                                                        "block.invoke"));
726   Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
727                                                           "block.descriptor"));
728 
729   // Finally, capture all the values into the block.
730   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
731 
732   // First, 'this'.
733   if (blockDecl->capturesCXXThis()) {
734     llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
735                                                 blockInfo.CXXThisIndex,
736                                                 "block.captured-this.addr");
737     Builder.CreateStore(LoadCXXThis(), addr);
738   }
739 
740   // Next, captured variables.
741   for (const auto &CI : blockDecl->captures()) {
742     const VarDecl *variable = CI.getVariable();
743     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
744 
745     // Ignore constant captures.
746     if (capture.isConstant()) continue;
747 
748     QualType type = variable->getType();
749     CharUnits align = getContext().getDeclAlign(variable);
750 
751     // This will be a [[type]]*, except that a byref entry will just be
752     // an i8**.
753     llvm::Value *blockField =
754       Builder.CreateStructGEP(blockAddr, capture.getIndex(),
755                               "block.captured");
756 
757     // Compute the address of the thing we're going to move into the
758     // block literal.
759     llvm::Value *src;
760     if (BlockInfo && CI.isNested()) {
761       // We need to use the capture from the enclosing block.
762       const CGBlockInfo::Capture &enclosingCapture =
763         BlockInfo->getCapture(variable);
764 
765       // This is a [[type]]*, except that a byref entry wil just be an i8**.
766       src = Builder.CreateStructGEP(LoadBlockStruct(),
767                                     enclosingCapture.getIndex(),
768                                     "block.capture.addr");
769     } else if (blockDecl->isConversionFromLambda()) {
770       // The lambda capture in a lambda's conversion-to-block-pointer is
771       // special; we'll simply emit it directly.
772       src = nullptr;
773     } else {
774       // Just look it up in the locals map, which will give us back a
775       // [[type]]*.  If that doesn't work, do the more elaborate DRE
776       // emission.
777       src = LocalDeclMap.lookup(variable);
778       if (!src) {
779         DeclRefExpr declRef(const_cast<VarDecl *>(variable),
780                             /*refersToEnclosing*/ CI.isNested(), type,
781                             VK_LValue, SourceLocation());
782         src = EmitDeclRefLValue(&declRef).getAddress();
783       }
784     }
785 
786     // For byrefs, we just write the pointer to the byref struct into
787     // the block field.  There's no need to chase the forwarding
788     // pointer at this point, since we're building something that will
789     // live a shorter life than the stack byref anyway.
790     if (CI.isByRef()) {
791       // Get a void* that points to the byref struct.
792       if (CI.isNested())
793         src = Builder.CreateAlignedLoad(src, align.getQuantity(),
794                                         "byref.capture");
795       else
796         src = Builder.CreateBitCast(src, VoidPtrTy);
797 
798       // Write that void* into the capture field.
799       Builder.CreateAlignedStore(src, blockField, align.getQuantity());
800 
801     // If we have a copy constructor, evaluate that into the block field.
802     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
803       if (blockDecl->isConversionFromLambda()) {
804         // If we have a lambda conversion, emit the expression
805         // directly into the block instead.
806         AggValueSlot Slot =
807             AggValueSlot::forAddr(blockField, align, Qualifiers(),
808                                   AggValueSlot::IsDestructed,
809                                   AggValueSlot::DoesNotNeedGCBarriers,
810                                   AggValueSlot::IsNotAliased);
811         EmitAggExpr(copyExpr, Slot);
812       } else {
813         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
814       }
815 
816     // If it's a reference variable, copy the reference into the block field.
817     } else if (type->isReferenceType()) {
818       llvm::Value *ref =
819         Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
820       Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
821 
822     // If this is an ARC __strong block-pointer variable, don't do a
823     // block copy.
824     //
825     // TODO: this can be generalized into the normal initialization logic:
826     // we should never need to do a block-copy when initializing a local
827     // variable, because the local variable's lifetime should be strictly
828     // contained within the stack block's.
829     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
830                type->isBlockPointerType()) {
831       // Load the block and do a simple retain.
832       LValue srcLV = MakeAddrLValue(src, type, align);
833       llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
834       value = EmitARCRetainNonBlock(value);
835 
836       // Do a primitive store to the block field.
837       LValue destLV = MakeAddrLValue(blockField, type, align);
838       EmitStoreOfScalar(value, destLV, /*init*/ true);
839 
840     // Otherwise, fake up a POD copy into the block field.
841     } else {
842       // Fake up a new variable so that EmitScalarInit doesn't think
843       // we're referring to the variable in its own initializer.
844       ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
845                                             SourceLocation(), /*name*/ nullptr,
846                                             type);
847 
848       // We use one of these or the other depending on whether the
849       // reference is nested.
850       DeclRefExpr declRef(const_cast<VarDecl*>(variable),
851                           /*refersToEnclosing*/ CI.isNested(), type,
852                           VK_LValue, SourceLocation());
853 
854       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
855                            &declRef, VK_RValue);
856       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
857                      MakeAddrLValue(blockField, type, align),
858                      /*captured by init*/ false);
859     }
860 
861     // Activate the cleanup if layout pushed one.
862     if (!CI.isByRef()) {
863       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
864       if (cleanup.isValid())
865         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
866     }
867   }
868 
869   // Cast to the converted block-pointer type, which happens (somewhat
870   // unfortunately) to be a pointer to function type.
871   llvm::Value *result =
872     Builder.CreateBitCast(blockAddr,
873                           ConvertType(blockInfo.getBlockExpr()->getType()));
874 
875   return result;
876 }
877 
878 
879 llvm::Type *CodeGenModule::getBlockDescriptorType() {
880   if (BlockDescriptorType)
881     return BlockDescriptorType;
882 
883   llvm::Type *UnsignedLongTy =
884     getTypes().ConvertType(getContext().UnsignedLongTy);
885 
886   // struct __block_descriptor {
887   //   unsigned long reserved;
888   //   unsigned long block_size;
889   //
890   //   // later, the following will be added
891   //
892   //   struct {
893   //     void (*copyHelper)();
894   //     void (*copyHelper)();
895   //   } helpers;                // !!! optional
896   //
897   //   const char *signature;   // the block signature
898   //   const char *layout;      // reserved
899   // };
900   BlockDescriptorType =
901     llvm::StructType::create("struct.__block_descriptor",
902                              UnsignedLongTy, UnsignedLongTy, NULL);
903 
904   // Now form a pointer to that.
905   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
906   return BlockDescriptorType;
907 }
908 
909 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
910   if (GenericBlockLiteralType)
911     return GenericBlockLiteralType;
912 
913   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
914 
915   // struct __block_literal_generic {
916   //   void *__isa;
917   //   int __flags;
918   //   int __reserved;
919   //   void (*__invoke)(void *);
920   //   struct __block_descriptor *__descriptor;
921   // };
922   GenericBlockLiteralType =
923     llvm::StructType::create("struct.__block_literal_generic",
924                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
925                              BlockDescPtrTy, NULL);
926 
927   return GenericBlockLiteralType;
928 }
929 
930 
931 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
932                                           ReturnValueSlot ReturnValue) {
933   const BlockPointerType *BPT =
934     E->getCallee()->getType()->getAs<BlockPointerType>();
935 
936   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
937 
938   // Get a pointer to the generic block literal.
939   llvm::Type *BlockLiteralTy =
940     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
941 
942   // Bitcast the callee to a block literal.
943   llvm::Value *BlockLiteral =
944     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
945 
946   // Get the function pointer from the literal.
947   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
948 
949   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
950 
951   // Add the block literal.
952   CallArgList Args;
953   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
954 
955   QualType FnType = BPT->getPointeeType();
956 
957   // And the rest of the arguments.
958   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
959                E->arg_begin(), E->arg_end());
960 
961   // Load the function.
962   llvm::Value *Func = Builder.CreateLoad(FuncPtr);
963 
964   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
965   const CGFunctionInfo &FnInfo =
966     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
967 
968   // Cast the function pointer to the right type.
969   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
970 
971   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
972   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
973 
974   // And call the block.
975   return EmitCall(FnInfo, Func, ReturnValue, Args);
976 }
977 
978 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
979                                                  bool isByRef) {
980   assert(BlockInfo && "evaluating block ref without block information?");
981   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
982 
983   // Handle constant captures.
984   if (capture.isConstant()) return LocalDeclMap[variable];
985 
986   llvm::Value *addr =
987     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
988                             "block.capture.addr");
989 
990   if (isByRef) {
991     // addr should be a void** right now.  Load, then cast the result
992     // to byref*.
993 
994     addr = Builder.CreateLoad(addr);
995     llvm::PointerType *byrefPointerType
996       = llvm::PointerType::get(BuildByRefType(variable), 0);
997     addr = Builder.CreateBitCast(addr, byrefPointerType,
998                                  "byref.addr");
999 
1000     // Follow the forwarding pointer.
1001     addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
1002     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
1003 
1004     // Cast back to byref* and GEP over to the actual object.
1005     addr = Builder.CreateBitCast(addr, byrefPointerType);
1006     addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
1007                                    variable->getNameAsString());
1008   }
1009 
1010   if (variable->getType()->isReferenceType())
1011     addr = Builder.CreateLoad(addr, "ref.tmp");
1012 
1013   return addr;
1014 }
1015 
1016 llvm::Constant *
1017 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1018                                     const char *name) {
1019   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1020   blockInfo.BlockExpression = blockExpr;
1021 
1022   // Compute information about the layout, etc., of this block.
1023   computeBlockInfo(*this, nullptr, blockInfo);
1024 
1025   // Using that metadata, generate the actual block function.
1026   llvm::Constant *blockFn;
1027   {
1028     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
1029     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1030                                                            blockInfo,
1031                                                            LocalDeclMap,
1032                                                            false);
1033   }
1034   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1035 
1036   return buildGlobalBlock(*this, blockInfo, blockFn);
1037 }
1038 
1039 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1040                                         const CGBlockInfo &blockInfo,
1041                                         llvm::Constant *blockFn) {
1042   assert(blockInfo.CanBeGlobal);
1043 
1044   // Generate the constants for the block literal initializer.
1045   llvm::Constant *fields[BlockHeaderSize];
1046 
1047   // isa
1048   fields[0] = CGM.getNSConcreteGlobalBlock();
1049 
1050   // __flags
1051   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1052   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1053 
1054   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1055 
1056   // Reserved
1057   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1058 
1059   // Function
1060   fields[3] = blockFn;
1061 
1062   // Descriptor
1063   fields[4] = buildBlockDescriptor(CGM, blockInfo);
1064 
1065   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1066 
1067   llvm::GlobalVariable *literal =
1068     new llvm::GlobalVariable(CGM.getModule(),
1069                              init->getType(),
1070                              /*constant*/ true,
1071                              llvm::GlobalVariable::InternalLinkage,
1072                              init,
1073                              "__block_literal_global");
1074   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1075 
1076   // Return a constant of the appropriately-casted type.
1077   llvm::Type *requiredType =
1078     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1079   return llvm::ConstantExpr::getBitCast(literal, requiredType);
1080 }
1081 
1082 llvm::Function *
1083 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1084                                        const CGBlockInfo &blockInfo,
1085                                        const DeclMapTy &ldm,
1086                                        bool IsLambdaConversionToBlock) {
1087   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1088 
1089   CurGD = GD;
1090 
1091   BlockInfo = &blockInfo;
1092 
1093   // Arrange for local static and local extern declarations to appear
1094   // to be local to this function as well, in case they're directly
1095   // referenced in a block.
1096   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1097     const auto *var = dyn_cast<VarDecl>(i->first);
1098     if (var && !var->hasLocalStorage())
1099       LocalDeclMap[var] = i->second;
1100   }
1101 
1102   // Begin building the function declaration.
1103 
1104   // Build the argument list.
1105   FunctionArgList args;
1106 
1107   // The first argument is the block pointer.  Just take it as a void*
1108   // and cast it later.
1109   QualType selfTy = getContext().VoidPtrTy;
1110   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1111 
1112   ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1113                              SourceLocation(), II, selfTy);
1114   args.push_back(&selfDecl);
1115 
1116   // Now add the rest of the parameters.
1117   for (auto i : blockDecl->params())
1118     args.push_back(i);
1119 
1120   // Create the function declaration.
1121   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1122   const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1123       fnType->getReturnType(), args, fnType->getExtInfo(),
1124       fnType->isVariadic());
1125   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1126     blockInfo.UsesStret = true;
1127 
1128   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1129 
1130   MangleBuffer name;
1131   CGM.getBlockMangledName(GD, name, blockDecl);
1132   llvm::Function *fn =
1133     llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1134                            name.getString(), &CGM.getModule());
1135   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1136 
1137   // Begin generating the function.
1138   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1139                 blockDecl->getLocation(),
1140                 blockInfo.getBlockExpr()->getBody()->getLocStart());
1141 
1142   // Okay.  Undo some of what StartFunction did.
1143 
1144   // Pull the 'self' reference out of the local decl map.
1145   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1146   LocalDeclMap.erase(&selfDecl);
1147   BlockPointer = Builder.CreateBitCast(blockAddr,
1148                                        blockInfo.StructureType->getPointerTo(),
1149                                        "block");
1150   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1151   // won't delete the dbg.declare intrinsics for captured variables.
1152   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1153   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1154     // Allocate a stack slot for it, so we can point the debugger to it
1155     llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1156                                                 "block.addr");
1157     unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1158     Alloca->setAlignment(Align);
1159     // Set the DebugLocation to empty, so the store is recognized as a
1160     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1161     NoLocation NL(*this, Builder);
1162     Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1163     BlockPointerDbgLoc = Alloca;
1164   }
1165 
1166   // If we have a C++ 'this' reference, go ahead and force it into
1167   // existence now.
1168   if (blockDecl->capturesCXXThis()) {
1169     llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1170                                                 blockInfo.CXXThisIndex,
1171                                                 "block.captured-this");
1172     CXXThisValue = Builder.CreateLoad(addr, "this");
1173   }
1174 
1175   // Also force all the constant captures.
1176   for (const auto &CI : blockDecl->captures()) {
1177     const VarDecl *variable = CI.getVariable();
1178     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1179     if (!capture.isConstant()) continue;
1180 
1181     unsigned align = getContext().getDeclAlign(variable).getQuantity();
1182 
1183     llvm::AllocaInst *alloca =
1184       CreateMemTemp(variable->getType(), "block.captured-const");
1185     alloca->setAlignment(align);
1186 
1187     Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
1188 
1189     LocalDeclMap[variable] = alloca;
1190   }
1191 
1192   // Save a spot to insert the debug information for all the DeclRefExprs.
1193   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1194   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1195   --entry_ptr;
1196 
1197   if (IsLambdaConversionToBlock)
1198     EmitLambdaBlockInvokeBody();
1199   else {
1200     PGO.assignRegionCounters(blockDecl, fn);
1201     RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
1202     Cnt.beginRegion(Builder);
1203     EmitStmt(blockDecl->getBody());
1204     PGO.emitInstrumentationData();
1205     PGO.destroyRegionCounters();
1206   }
1207 
1208   // Remember where we were...
1209   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1210 
1211   // Go back to the entry.
1212   ++entry_ptr;
1213   Builder.SetInsertPoint(entry, entry_ptr);
1214 
1215   // Emit debug information for all the DeclRefExprs.
1216   // FIXME: also for 'this'
1217   if (CGDebugInfo *DI = getDebugInfo()) {
1218     for (const auto &CI : blockDecl->captures()) {
1219       const VarDecl *variable = CI.getVariable();
1220       DI->EmitLocation(Builder, variable->getLocation());
1221 
1222       if (CGM.getCodeGenOpts().getDebugInfo()
1223             >= CodeGenOptions::LimitedDebugInfo) {
1224         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1225         if (capture.isConstant()) {
1226           DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1227                                         Builder);
1228           continue;
1229         }
1230 
1231         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
1232                                               Builder, blockInfo);
1233       }
1234     }
1235     // Recover location if it was changed in the above loop.
1236     DI->EmitLocation(Builder,
1237                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1238   }
1239 
1240   // And resume where we left off.
1241   if (resume == nullptr)
1242     Builder.ClearInsertionPoint();
1243   else
1244     Builder.SetInsertPoint(resume);
1245 
1246   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1247 
1248   return fn;
1249 }
1250 
1251 /*
1252     notes.push_back(HelperInfo());
1253     HelperInfo &note = notes.back();
1254     note.index = capture.getIndex();
1255     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1256     note.cxxbar_import = ci->getCopyExpr();
1257 
1258     if (ci->isByRef()) {
1259       note.flag = BLOCK_FIELD_IS_BYREF;
1260       if (type.isObjCGCWeak())
1261         note.flag |= BLOCK_FIELD_IS_WEAK;
1262     } else if (type->isBlockPointerType()) {
1263       note.flag = BLOCK_FIELD_IS_BLOCK;
1264     } else {
1265       note.flag = BLOCK_FIELD_IS_OBJECT;
1266     }
1267  */
1268 
1269 
1270 /// Generate the copy-helper function for a block closure object:
1271 ///   static void block_copy_helper(block_t *dst, block_t *src);
1272 /// The runtime will have previously initialized 'dst' by doing a
1273 /// bit-copy of 'src'.
1274 ///
1275 /// Note that this copies an entire block closure object to the heap;
1276 /// it should not be confused with a 'byref copy helper', which moves
1277 /// the contents of an individual __block variable to the heap.
1278 llvm::Constant *
1279 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1280   ASTContext &C = getContext();
1281 
1282   FunctionArgList args;
1283   ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1284                             C.VoidPtrTy);
1285   args.push_back(&dstDecl);
1286   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1287                             C.VoidPtrTy);
1288   args.push_back(&srcDecl);
1289 
1290   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1291       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1292 
1293   // FIXME: it would be nice if these were mergeable with things with
1294   // identical semantics.
1295   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1296 
1297   llvm::Function *Fn =
1298     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1299                            "__copy_helper_block_", &CGM.getModule());
1300 
1301   IdentifierInfo *II
1302     = &CGM.getContext().Idents.get("__copy_helper_block_");
1303 
1304   FunctionDecl *FD = FunctionDecl::Create(C,
1305                                           C.getTranslationUnitDecl(),
1306                                           SourceLocation(),
1307                                           SourceLocation(), II, C.VoidTy,
1308                                           nullptr, SC_Static,
1309                                           false,
1310                                           false);
1311   // Create a scope with an artificial location for the body of this function.
1312   ArtificialLocation AL(*this, Builder);
1313   StartFunction(FD, C.VoidTy, Fn, FI, args);
1314   AL.Emit();
1315 
1316   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1317 
1318   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1319   src = Builder.CreateLoad(src);
1320   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1321 
1322   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1323   dst = Builder.CreateLoad(dst);
1324   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1325 
1326   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1327 
1328   for (const auto &CI : blockDecl->captures()) {
1329     const VarDecl *variable = CI.getVariable();
1330     QualType type = variable->getType();
1331 
1332     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1333     if (capture.isConstant()) continue;
1334 
1335     const Expr *copyExpr = CI.getCopyExpr();
1336     BlockFieldFlags flags;
1337 
1338     bool useARCWeakCopy = false;
1339     bool useARCStrongCopy = false;
1340 
1341     if (copyExpr) {
1342       assert(!CI.isByRef());
1343       // don't bother computing flags
1344 
1345     } else if (CI.isByRef()) {
1346       flags = BLOCK_FIELD_IS_BYREF;
1347       if (type.isObjCGCWeak())
1348         flags |= BLOCK_FIELD_IS_WEAK;
1349 
1350     } else if (type->isObjCRetainableType()) {
1351       flags = BLOCK_FIELD_IS_OBJECT;
1352       bool isBlockPointer = type->isBlockPointerType();
1353       if (isBlockPointer)
1354         flags = BLOCK_FIELD_IS_BLOCK;
1355 
1356       // Special rules for ARC captures:
1357       if (getLangOpts().ObjCAutoRefCount) {
1358         Qualifiers qs = type.getQualifiers();
1359 
1360         // We need to register __weak direct captures with the runtime.
1361         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1362           useARCWeakCopy = true;
1363 
1364         // We need to retain the copied value for __strong direct captures.
1365         } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1366           // If it's a block pointer, we have to copy the block and
1367           // assign that to the destination pointer, so we might as
1368           // well use _Block_object_assign.  Otherwise we can avoid that.
1369           if (!isBlockPointer)
1370             useARCStrongCopy = true;
1371 
1372         // Otherwise the memcpy is fine.
1373         } else {
1374           continue;
1375         }
1376 
1377       // Non-ARC captures of retainable pointers are strong and
1378       // therefore require a call to _Block_object_assign.
1379       } else {
1380         // fall through
1381       }
1382     } else {
1383       continue;
1384     }
1385 
1386     unsigned index = capture.getIndex();
1387     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1388     llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
1389 
1390     // If there's an explicit copy expression, we do that.
1391     if (copyExpr) {
1392       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1393     } else if (useARCWeakCopy) {
1394       EmitARCCopyWeak(dstField, srcField);
1395     } else {
1396       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1397       if (useARCStrongCopy) {
1398         // At -O0, store null into the destination field (so that the
1399         // storeStrong doesn't over-release) and then call storeStrong.
1400         // This is a workaround to not having an initStrong call.
1401         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1402           auto *ty = cast<llvm::PointerType>(srcValue->getType());
1403           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1404           Builder.CreateStore(null, dstField);
1405           EmitARCStoreStrongCall(dstField, srcValue, true);
1406 
1407         // With optimization enabled, take advantage of the fact that
1408         // the blocks runtime guarantees a memcpy of the block data, and
1409         // just emit a retain of the src field.
1410         } else {
1411           EmitARCRetainNonBlock(srcValue);
1412 
1413           // We don't need this anymore, so kill it.  It's not quite
1414           // worth the annoyance to avoid creating it in the first place.
1415           cast<llvm::Instruction>(dstField)->eraseFromParent();
1416         }
1417       } else {
1418         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1419         llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1420         llvm::Value *args[] = {
1421           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1422         };
1423 
1424         bool copyCanThrow = false;
1425         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1426           const Expr *copyExpr =
1427             CGM.getContext().getBlockVarCopyInits(variable);
1428           if (copyExpr) {
1429             copyCanThrow = true; // FIXME: reuse the noexcept logic
1430           }
1431         }
1432 
1433         if (copyCanThrow) {
1434           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1435         } else {
1436           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1437         }
1438       }
1439     }
1440   }
1441 
1442   FinishFunction();
1443 
1444   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1445 }
1446 
1447 /// Generate the destroy-helper function for a block closure object:
1448 ///   static void block_destroy_helper(block_t *theBlock);
1449 ///
1450 /// Note that this destroys a heap-allocated block closure object;
1451 /// it should not be confused with a 'byref destroy helper', which
1452 /// destroys the heap-allocated contents of an individual __block
1453 /// variable.
1454 llvm::Constant *
1455 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1456   ASTContext &C = getContext();
1457 
1458   FunctionArgList args;
1459   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1460                             C.VoidPtrTy);
1461   args.push_back(&srcDecl);
1462 
1463   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1464       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1465 
1466   // FIXME: We'd like to put these into a mergable by content, with
1467   // internal linkage.
1468   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1469 
1470   llvm::Function *Fn =
1471     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1472                            "__destroy_helper_block_", &CGM.getModule());
1473 
1474   IdentifierInfo *II
1475     = &CGM.getContext().Idents.get("__destroy_helper_block_");
1476 
1477   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1478                                           SourceLocation(),
1479                                           SourceLocation(), II, C.VoidTy,
1480                                           nullptr, SC_Static,
1481                                           false, false);
1482   // Create a scope with an artificial location for the body of this function.
1483   ArtificialLocation AL(*this, Builder);
1484   StartFunction(FD, C.VoidTy, Fn, FI, args);
1485   AL.Emit();
1486 
1487   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1488 
1489   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1490   src = Builder.CreateLoad(src);
1491   src = Builder.CreateBitCast(src, structPtrTy, "block");
1492 
1493   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1494 
1495   CodeGenFunction::RunCleanupsScope cleanups(*this);
1496 
1497   for (const auto &CI : blockDecl->captures()) {
1498     const VarDecl *variable = CI.getVariable();
1499     QualType type = variable->getType();
1500 
1501     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1502     if (capture.isConstant()) continue;
1503 
1504     BlockFieldFlags flags;
1505     const CXXDestructorDecl *dtor = nullptr;
1506 
1507     bool useARCWeakDestroy = false;
1508     bool useARCStrongDestroy = false;
1509 
1510     if (CI.isByRef()) {
1511       flags = BLOCK_FIELD_IS_BYREF;
1512       if (type.isObjCGCWeak())
1513         flags |= BLOCK_FIELD_IS_WEAK;
1514     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1515       if (record->hasTrivialDestructor())
1516         continue;
1517       dtor = record->getDestructor();
1518     } else if (type->isObjCRetainableType()) {
1519       flags = BLOCK_FIELD_IS_OBJECT;
1520       if (type->isBlockPointerType())
1521         flags = BLOCK_FIELD_IS_BLOCK;
1522 
1523       // Special rules for ARC captures.
1524       if (getLangOpts().ObjCAutoRefCount) {
1525         Qualifiers qs = type.getQualifiers();
1526 
1527         // Don't generate special dispose logic for a captured object
1528         // unless it's __strong or __weak.
1529         if (!qs.hasStrongOrWeakObjCLifetime())
1530           continue;
1531 
1532         // Support __weak direct captures.
1533         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1534           useARCWeakDestroy = true;
1535 
1536         // Tools really want us to use objc_storeStrong here.
1537         else
1538           useARCStrongDestroy = true;
1539       }
1540     } else {
1541       continue;
1542     }
1543 
1544     unsigned index = capture.getIndex();
1545     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1546 
1547     // If there's an explicit copy expression, we do that.
1548     if (dtor) {
1549       PushDestructorCleanup(dtor, srcField);
1550 
1551     // If this is a __weak capture, emit the release directly.
1552     } else if (useARCWeakDestroy) {
1553       EmitARCDestroyWeak(srcField);
1554 
1555     // Destroy strong objects with a call if requested.
1556     } else if (useARCStrongDestroy) {
1557       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1558 
1559     // Otherwise we call _Block_object_dispose.  It wouldn't be too
1560     // hard to just emit this as a cleanup if we wanted to make sure
1561     // that things were done in reverse.
1562     } else {
1563       llvm::Value *value = Builder.CreateLoad(srcField);
1564       value = Builder.CreateBitCast(value, VoidPtrTy);
1565       BuildBlockRelease(value, flags);
1566     }
1567   }
1568 
1569   cleanups.ForceCleanup();
1570 
1571   FinishFunction();
1572 
1573   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1574 }
1575 
1576 namespace {
1577 
1578 /// Emits the copy/dispose helper functions for a __block object of id type.
1579 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1580   BlockFieldFlags Flags;
1581 
1582 public:
1583   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1584     : ByrefHelpers(alignment), Flags(flags) {}
1585 
1586   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1587                 llvm::Value *srcField) override {
1588     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1589 
1590     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1591     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1592 
1593     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1594 
1595     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1596     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1597 
1598     llvm::Value *args[] = { destField, srcValue, flagsVal };
1599     CGF.EmitNounwindRuntimeCall(fn, args);
1600   }
1601 
1602   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1603     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1604     llvm::Value *value = CGF.Builder.CreateLoad(field);
1605 
1606     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1607   }
1608 
1609   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1610     id.AddInteger(Flags.getBitMask());
1611   }
1612 };
1613 
1614 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1615 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1616 public:
1617   ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1618 
1619   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1620                 llvm::Value *srcField) override {
1621     CGF.EmitARCMoveWeak(destField, srcField);
1622   }
1623 
1624   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1625     CGF.EmitARCDestroyWeak(field);
1626   }
1627 
1628   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1629     // 0 is distinguishable from all pointers and byref flags
1630     id.AddInteger(0);
1631   }
1632 };
1633 
1634 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1635 /// that's not of block-pointer type.
1636 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1637 public:
1638   ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1639 
1640   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1641                 llvm::Value *srcField) override {
1642     // Do a "move" by copying the value and then zeroing out the old
1643     // variable.
1644 
1645     llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1646     value->setAlignment(Alignment.getQuantity());
1647 
1648     llvm::Value *null =
1649       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1650 
1651     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1652       llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1653       store->setAlignment(Alignment.getQuantity());
1654       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1655       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1656       return;
1657     }
1658     llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1659     store->setAlignment(Alignment.getQuantity());
1660 
1661     store = CGF.Builder.CreateStore(null, srcField);
1662     store->setAlignment(Alignment.getQuantity());
1663   }
1664 
1665   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1666     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1667   }
1668 
1669   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1670     // 1 is distinguishable from all pointers and byref flags
1671     id.AddInteger(1);
1672   }
1673 };
1674 
1675 /// Emits the copy/dispose helpers for an ARC __block __strong
1676 /// variable that's of block-pointer type.
1677 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1678 public:
1679   ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1680 
1681   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1682                 llvm::Value *srcField) override {
1683     // Do the copy with objc_retainBlock; that's all that
1684     // _Block_object_assign would do anyway, and we'd have to pass the
1685     // right arguments to make sure it doesn't get no-op'ed.
1686     llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1687     oldValue->setAlignment(Alignment.getQuantity());
1688 
1689     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1690 
1691     llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1692     store->setAlignment(Alignment.getQuantity());
1693   }
1694 
1695   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1696     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1697   }
1698 
1699   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1700     // 2 is distinguishable from all pointers and byref flags
1701     id.AddInteger(2);
1702   }
1703 };
1704 
1705 /// Emits the copy/dispose helpers for a __block variable with a
1706 /// nontrivial copy constructor or destructor.
1707 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1708   QualType VarType;
1709   const Expr *CopyExpr;
1710 
1711 public:
1712   CXXByrefHelpers(CharUnits alignment, QualType type,
1713                   const Expr *copyExpr)
1714     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1715 
1716   bool needsCopy() const override { return CopyExpr != nullptr; }
1717   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1718                 llvm::Value *srcField) override {
1719     if (!CopyExpr) return;
1720     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1721   }
1722 
1723   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1724     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1725     CGF.PushDestructorCleanup(VarType, field);
1726     CGF.PopCleanupBlocks(cleanupDepth);
1727   }
1728 
1729   void profileImpl(llvm::FoldingSetNodeID &id) const override {
1730     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1731   }
1732 };
1733 } // end anonymous namespace
1734 
1735 static llvm::Constant *
1736 generateByrefCopyHelper(CodeGenFunction &CGF,
1737                         llvm::StructType &byrefType,
1738                         unsigned valueFieldIndex,
1739                         CodeGenModule::ByrefHelpers &byrefInfo) {
1740   ASTContext &Context = CGF.getContext();
1741 
1742   QualType R = Context.VoidTy;
1743 
1744   FunctionArgList args;
1745   ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1746                         Context.VoidPtrTy);
1747   args.push_back(&dst);
1748 
1749   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1750                         Context.VoidPtrTy);
1751   args.push_back(&src);
1752 
1753   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1754       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1755 
1756   CodeGenTypes &Types = CGF.CGM.getTypes();
1757   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1758 
1759   // FIXME: We'd like to put these into a mergable by content, with
1760   // internal linkage.
1761   llvm::Function *Fn =
1762     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1763                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
1764 
1765   IdentifierInfo *II
1766     = &Context.Idents.get("__Block_byref_object_copy_");
1767 
1768   FunctionDecl *FD = FunctionDecl::Create(Context,
1769                                           Context.getTranslationUnitDecl(),
1770                                           SourceLocation(),
1771                                           SourceLocation(), II, R, nullptr,
1772                                           SC_Static,
1773                                           false, false);
1774 
1775   CGF.StartFunction(FD, R, Fn, FI, args);
1776 
1777   if (byrefInfo.needsCopy()) {
1778     llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1779 
1780     // dst->x
1781     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1782     destField = CGF.Builder.CreateLoad(destField);
1783     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1784     destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
1785 
1786     // src->x
1787     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1788     srcField = CGF.Builder.CreateLoad(srcField);
1789     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1790     srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
1791 
1792     byrefInfo.emitCopy(CGF, destField, srcField);
1793   }
1794 
1795   CGF.FinishFunction();
1796 
1797   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1798 }
1799 
1800 /// Build the copy helper for a __block variable.
1801 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1802                                             llvm::StructType &byrefType,
1803                                             unsigned byrefValueIndex,
1804                                             CodeGenModule::ByrefHelpers &info) {
1805   CodeGenFunction CGF(CGM);
1806   return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
1807 }
1808 
1809 /// Generate code for a __block variable's dispose helper.
1810 static llvm::Constant *
1811 generateByrefDisposeHelper(CodeGenFunction &CGF,
1812                            llvm::StructType &byrefType,
1813                            unsigned byrefValueIndex,
1814                            CodeGenModule::ByrefHelpers &byrefInfo) {
1815   ASTContext &Context = CGF.getContext();
1816   QualType R = Context.VoidTy;
1817 
1818   FunctionArgList args;
1819   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1820                         Context.VoidPtrTy);
1821   args.push_back(&src);
1822 
1823   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1824       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1825 
1826   CodeGenTypes &Types = CGF.CGM.getTypes();
1827   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1828 
1829   // FIXME: We'd like to put these into a mergable by content, with
1830   // internal linkage.
1831   llvm::Function *Fn =
1832     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1833                            "__Block_byref_object_dispose_",
1834                            &CGF.CGM.getModule());
1835 
1836   IdentifierInfo *II
1837     = &Context.Idents.get("__Block_byref_object_dispose_");
1838 
1839   FunctionDecl *FD = FunctionDecl::Create(Context,
1840                                           Context.getTranslationUnitDecl(),
1841                                           SourceLocation(),
1842                                           SourceLocation(), II, R, nullptr,
1843                                           SC_Static,
1844                                           false, false);
1845   CGF.StartFunction(FD, R, Fn, FI, args);
1846 
1847   if (byrefInfo.needsDispose()) {
1848     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1849     V = CGF.Builder.CreateLoad(V);
1850     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1851     V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
1852 
1853     byrefInfo.emitDispose(CGF, V);
1854   }
1855 
1856   CGF.FinishFunction();
1857 
1858   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1859 }
1860 
1861 /// Build the dispose helper for a __block variable.
1862 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1863                                               llvm::StructType &byrefType,
1864                                                unsigned byrefValueIndex,
1865                                             CodeGenModule::ByrefHelpers &info) {
1866   CodeGenFunction CGF(CGM);
1867   return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
1868 }
1869 
1870 /// Lazily build the copy and dispose helpers for a __block variable
1871 /// with the given information.
1872 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1873                                                llvm::StructType &byrefTy,
1874                                                unsigned byrefValueIndex,
1875                                                T &byrefInfo) {
1876   // Increase the field's alignment to be at least pointer alignment,
1877   // since the layout of the byref struct will guarantee at least that.
1878   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1879                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1880 
1881   llvm::FoldingSetNodeID id;
1882   byrefInfo.Profile(id);
1883 
1884   void *insertPos;
1885   CodeGenModule::ByrefHelpers *node
1886     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1887   if (node) return static_cast<T*>(node);
1888 
1889   byrefInfo.CopyHelper =
1890     buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1891   byrefInfo.DisposeHelper =
1892     buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
1893 
1894   T *copy = new (CGM.getContext()) T(byrefInfo);
1895   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1896   return copy;
1897 }
1898 
1899 /// Build the copy and dispose helpers for the given __block variable
1900 /// emission.  Places the helpers in the global cache.  Returns null
1901 /// if no helpers are required.
1902 CodeGenModule::ByrefHelpers *
1903 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1904                                    const AutoVarEmission &emission) {
1905   const VarDecl &var = *emission.Variable;
1906   QualType type = var.getType();
1907 
1908   unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1909 
1910   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1911     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1912     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1913 
1914     CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1915     return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1916   }
1917 
1918   // Otherwise, if we don't have a retainable type, there's nothing to do.
1919   // that the runtime does extra copies.
1920   if (!type->isObjCRetainableType()) return nullptr;
1921 
1922   Qualifiers qs = type.getQualifiers();
1923 
1924   // If we have lifetime, that dominates.
1925   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1926     assert(getLangOpts().ObjCAutoRefCount);
1927 
1928     switch (lifetime) {
1929     case Qualifiers::OCL_None: llvm_unreachable("impossible");
1930 
1931     // These are just bits as far as the runtime is concerned.
1932     case Qualifiers::OCL_ExplicitNone:
1933     case Qualifiers::OCL_Autoreleasing:
1934       return nullptr;
1935 
1936     // Tell the runtime that this is ARC __weak, called by the
1937     // byref routines.
1938     case Qualifiers::OCL_Weak: {
1939       ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1940       return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1941     }
1942 
1943     // ARC __strong __block variables need to be retained.
1944     case Qualifiers::OCL_Strong:
1945       // Block pointers need to be copied, and there's no direct
1946       // transfer possible.
1947       if (type->isBlockPointerType()) {
1948         ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1949         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1950 
1951       // Otherwise, we transfer ownership of the retain from the stack
1952       // to the heap.
1953       } else {
1954         ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1955         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1956       }
1957     }
1958     llvm_unreachable("fell out of lifetime switch!");
1959   }
1960 
1961   BlockFieldFlags flags;
1962   if (type->isBlockPointerType()) {
1963     flags |= BLOCK_FIELD_IS_BLOCK;
1964   } else if (CGM.getContext().isObjCNSObjectType(type) ||
1965              type->isObjCObjectPointerType()) {
1966     flags |= BLOCK_FIELD_IS_OBJECT;
1967   } else {
1968     return nullptr;
1969   }
1970 
1971   if (type.isObjCGCWeak())
1972     flags |= BLOCK_FIELD_IS_WEAK;
1973 
1974   ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1975   return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1976 }
1977 
1978 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1979   assert(ByRefValueInfo.count(VD) && "Did not find value!");
1980 
1981   return ByRefValueInfo.find(VD)->second.second;
1982 }
1983 
1984 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1985                                                      const VarDecl *V) {
1986   llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1987   Loc = Builder.CreateLoad(Loc);
1988   Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1989                                 V->getNameAsString());
1990   return Loc;
1991 }
1992 
1993 /// BuildByRefType - This routine changes a __block variable declared as T x
1994 ///   into:
1995 ///
1996 ///      struct {
1997 ///        void *__isa;
1998 ///        void *__forwarding;
1999 ///        int32_t __flags;
2000 ///        int32_t __size;
2001 ///        void *__copy_helper;       // only if needed
2002 ///        void *__destroy_helper;    // only if needed
2003 ///        void *__byref_variable_layout;// only if needed
2004 ///        char padding[X];           // only if needed
2005 ///        T x;
2006 ///      } x
2007 ///
2008 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2009   std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
2010   if (Info.first)
2011     return Info.first;
2012 
2013   QualType Ty = D->getType();
2014 
2015   SmallVector<llvm::Type *, 8> types;
2016 
2017   llvm::StructType *ByRefType =
2018     llvm::StructType::create(getLLVMContext(),
2019                              "struct.__block_byref_" + D->getNameAsString());
2020 
2021   // void *__isa;
2022   types.push_back(Int8PtrTy);
2023 
2024   // void *__forwarding;
2025   types.push_back(llvm::PointerType::getUnqual(ByRefType));
2026 
2027   // int32_t __flags;
2028   types.push_back(Int32Ty);
2029 
2030   // int32_t __size;
2031   types.push_back(Int32Ty);
2032   // Note that this must match *exactly* the logic in buildByrefHelpers.
2033   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2034   if (HasCopyAndDispose) {
2035     /// void *__copy_helper;
2036     types.push_back(Int8PtrTy);
2037 
2038     /// void *__destroy_helper;
2039     types.push_back(Int8PtrTy);
2040   }
2041   bool HasByrefExtendedLayout = false;
2042   Qualifiers::ObjCLifetime Lifetime;
2043   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2044       HasByrefExtendedLayout)
2045     /// void *__byref_variable_layout;
2046     types.push_back(Int8PtrTy);
2047 
2048   bool Packed = false;
2049   CharUnits Align = getContext().getDeclAlign(D);
2050   if (Align >
2051       getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
2052     // We have to insert padding.
2053 
2054     // The struct above has 2 32-bit integers.
2055     unsigned CurrentOffsetInBytes = 4 * 2;
2056 
2057     // And either 2, 3, 4 or 5 pointers.
2058     unsigned noPointers = 2;
2059     if (HasCopyAndDispose)
2060       noPointers += 2;
2061     if (HasByrefExtendedLayout)
2062       noPointers += 1;
2063 
2064     CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
2065 
2066     // Align the offset.
2067     unsigned AlignedOffsetInBytes =
2068       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2069 
2070     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2071     if (NumPaddingBytes > 0) {
2072       llvm::Type *Ty = Int8Ty;
2073       // FIXME: We need a sema error for alignment larger than the minimum of
2074       // the maximal stack alignment and the alignment of malloc on the system.
2075       if (NumPaddingBytes > 1)
2076         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2077 
2078       types.push_back(Ty);
2079 
2080       // We want a packed struct.
2081       Packed = true;
2082     }
2083   }
2084 
2085   // T x;
2086   types.push_back(ConvertTypeForMem(Ty));
2087 
2088   ByRefType->setBody(types, Packed);
2089 
2090   Info.first = ByRefType;
2091 
2092   Info.second = types.size() - 1;
2093 
2094   return Info.first;
2095 }
2096 
2097 /// Initialize the structural components of a __block variable, i.e.
2098 /// everything but the actual object.
2099 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2100   // Find the address of the local.
2101   llvm::Value *addr = emission.Address;
2102 
2103   // That's an alloca of the byref structure type.
2104   llvm::StructType *byrefType = cast<llvm::StructType>(
2105                  cast<llvm::PointerType>(addr->getType())->getElementType());
2106 
2107   // Build the byref helpers if necessary.  This is null if we don't need any.
2108   CodeGenModule::ByrefHelpers *helpers =
2109     buildByrefHelpers(*byrefType, emission);
2110 
2111   const VarDecl &D = *emission.Variable;
2112   QualType type = D.getType();
2113 
2114   bool HasByrefExtendedLayout;
2115   Qualifiers::ObjCLifetime ByrefLifetime;
2116   bool ByRefHasLifetime =
2117     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2118 
2119   llvm::Value *V;
2120 
2121   // Initialize the 'isa', which is just 0 or 1.
2122   int isa = 0;
2123   if (type.isObjCGCWeak())
2124     isa = 1;
2125   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2126   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2127 
2128   // Store the address of the variable into its own forwarding pointer.
2129   Builder.CreateStore(addr,
2130                       Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2131 
2132   // Blocks ABI:
2133   //   c) the flags field is set to either 0 if no helper functions are
2134   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2135   BlockFlags flags;
2136   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2137   if (ByRefHasLifetime) {
2138     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2139       else switch (ByrefLifetime) {
2140         case Qualifiers::OCL_Strong:
2141           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2142           break;
2143         case Qualifiers::OCL_Weak:
2144           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2145           break;
2146         case Qualifiers::OCL_ExplicitNone:
2147           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2148           break;
2149         case Qualifiers::OCL_None:
2150           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2151             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2152           break;
2153         default:
2154           break;
2155       }
2156     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2157       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2158       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2159         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2160       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2161         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2162         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2163           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2164         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2165           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2166         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2167           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2168         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2169           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2170         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2171           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2172       }
2173       printf("\n");
2174     }
2175   }
2176 
2177   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2178                       Builder.CreateStructGEP(addr, 2, "byref.flags"));
2179 
2180   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2181   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2182   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2183 
2184   if (helpers) {
2185     llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
2186     Builder.CreateStore(helpers->CopyHelper, copy_helper);
2187 
2188     llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
2189     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
2190   }
2191   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2192     llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2193     llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2194                                                          "byref.layout");
2195     // cast destination to pointer to source type.
2196     llvm::Type *DesTy = ByrefLayoutInfo->getType();
2197     DesTy = DesTy->getPointerTo();
2198     llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2199     Builder.CreateStore(ByrefLayoutInfo, BC);
2200   }
2201 }
2202 
2203 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2204   llvm::Value *F = CGM.getBlockObjectDispose();
2205   llvm::Value *args[] = {
2206     Builder.CreateBitCast(V, Int8PtrTy),
2207     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2208   };
2209   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2210 }
2211 
2212 namespace {
2213   struct CallBlockRelease : EHScopeStack::Cleanup {
2214     llvm::Value *Addr;
2215     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2216 
2217     void Emit(CodeGenFunction &CGF, Flags flags) override {
2218       // Should we be passing FIELD_IS_WEAK here?
2219       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2220     }
2221   };
2222 }
2223 
2224 /// Enter a cleanup to destroy a __block variable.  Note that this
2225 /// cleanup should be a no-op if the variable hasn't left the stack
2226 /// yet; if a cleanup is required for the variable itself, that needs
2227 /// to be done externally.
2228 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2229   // We don't enter this cleanup if we're in pure-GC mode.
2230   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2231     return;
2232 
2233   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2234 }
2235 
2236 /// Adjust the declaration of something from the blocks API.
2237 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2238                                          llvm::Constant *C) {
2239   if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2240 
2241   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2242   if (GV->isDeclaration() && GV->hasExternalLinkage())
2243     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2244 }
2245 
2246 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2247   if (BlockObjectDispose)
2248     return BlockObjectDispose;
2249 
2250   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2251   llvm::FunctionType *fty
2252     = llvm::FunctionType::get(VoidTy, args, false);
2253   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2254   configureBlocksRuntimeObject(*this, BlockObjectDispose);
2255   return BlockObjectDispose;
2256 }
2257 
2258 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2259   if (BlockObjectAssign)
2260     return BlockObjectAssign;
2261 
2262   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2263   llvm::FunctionType *fty
2264     = llvm::FunctionType::get(VoidTy, args, false);
2265   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2266   configureBlocksRuntimeObject(*this, BlockObjectAssign);
2267   return BlockObjectAssign;
2268 }
2269 
2270 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2271   if (NSConcreteGlobalBlock)
2272     return NSConcreteGlobalBlock;
2273 
2274   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2275                                                 Int8PtrTy->getPointerTo(),
2276                                                 nullptr);
2277   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2278   return NSConcreteGlobalBlock;
2279 }
2280 
2281 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2282   if (NSConcreteStackBlock)
2283     return NSConcreteStackBlock;
2284 
2285   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2286                                                Int8PtrTy->getPointerTo(),
2287                                                nullptr);
2288   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2289   return NSConcreteStackBlock;
2290 }
2291