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