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