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