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