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