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