clang  mainline
CGBlocks.cpp
Go to the documentation of this file.
00001 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit blocks.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CGBlocks.h"
00015 #include "CGDebugInfo.h"
00016 #include "CGObjCRuntime.h"
00017 #include "CodeGenFunction.h"
00018 #include "CodeGenModule.h"
00019 #include "clang/AST/DeclObjC.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/Module.h"
00024 #include <algorithm>
00025 #include <cstdio>
00026 
00027 using namespace clang;
00028 using namespace CodeGen;
00029 
00030 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
00031   : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
00032     HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
00033     StructureType(nullptr), Block(block),
00034     DominatingIP(nullptr) {
00035 
00036   // Skip asm prefix, if any.  'name' is usually taken directly from
00037   // the mangled name of the enclosing function.
00038   if (!name.empty() && name[0] == '\01')
00039     name = name.substr(1);
00040 }
00041 
00042 // Anchor the vtable to this translation unit.
00043 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
00044 
00045 /// Build the given block as a global block.
00046 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
00047                                         const CGBlockInfo &blockInfo,
00048                                         llvm::Constant *blockFn);
00049 
00050 /// Build the helper function to copy a block.
00051 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
00052                                        const CGBlockInfo &blockInfo) {
00053   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
00054 }
00055 
00056 /// Build the helper function to dispose of a block.
00057 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
00058                                           const CGBlockInfo &blockInfo) {
00059   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
00060 }
00061 
00062 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
00063 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
00064 /// meta-data and contains stationary information about the block literal.
00065 /// Its definition will have 4 (or optinally 6) words.
00066 /// \code
00067 /// struct Block_descriptor {
00068 ///   unsigned long reserved;
00069 ///   unsigned long size;  // size of Block_literal metadata in bytes.
00070 ///   void *copy_func_helper_decl;  // optional copy helper.
00071 ///   void *destroy_func_decl; // optioanl destructor helper.
00072 ///   void *block_method_encoding_address; // @encode for block literal signature.
00073 ///   void *block_layout_info; // encoding of captured block variables.
00074 /// };
00075 /// \endcode
00076 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
00077                                             const CGBlockInfo &blockInfo) {
00078   ASTContext &C = CGM.getContext();
00079 
00080   llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
00081   llvm::Type *i8p = NULL;
00082   if (CGM.getLangOpts().OpenCL)
00083     i8p = 
00084       llvm::Type::getInt8PtrTy(
00085            CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
00086   else
00087     i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
00088 
00089   SmallVector<llvm::Constant*, 6> elements;
00090 
00091   // reserved
00092   elements.push_back(llvm::ConstantInt::get(ulong, 0));
00093 
00094   // Size
00095   // FIXME: What is the right way to say this doesn't fit?  We should give
00096   // a user diagnostic in that case.  Better fix would be to change the
00097   // API to size_t.
00098   elements.push_back(llvm::ConstantInt::get(ulong,
00099                                             blockInfo.BlockSize.getQuantity()));
00100 
00101   // Optional copy/dispose helpers.
00102   if (blockInfo.NeedsCopyDispose) {
00103     // copy_func_helper_decl
00104     elements.push_back(buildCopyHelper(CGM, blockInfo));
00105 
00106     // destroy_func_decl
00107     elements.push_back(buildDisposeHelper(CGM, blockInfo));
00108   }
00109 
00110   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
00111   std::string typeAtEncoding =
00112     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
00113   elements.push_back(llvm::ConstantExpr::getBitCast(
00114                           CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
00115   
00116   // GC layout.
00117   if (C.getLangOpts().ObjC1) {
00118     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
00119       elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
00120     else
00121       elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
00122   }
00123   else
00124     elements.push_back(llvm::Constant::getNullValue(i8p));
00125 
00126   llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
00127 
00128   llvm::GlobalVariable *global =
00129     new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
00130                              llvm::GlobalValue::InternalLinkage,
00131                              init, "__block_descriptor_tmp");
00132 
00133   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
00134 }
00135 
00136 /*
00137   Purely notional variadic template describing the layout of a block.
00138 
00139   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
00140   struct Block_literal {
00141     /// Initialized to one of:
00142     ///   extern void *_NSConcreteStackBlock[];
00143     ///   extern void *_NSConcreteGlobalBlock[];
00144     ///
00145     /// In theory, we could start one off malloc'ed by setting
00146     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
00147     /// this isa:
00148     ///   extern void *_NSConcreteMallocBlock[];
00149     struct objc_class *isa;
00150 
00151     /// These are the flags (with corresponding bit number) that the
00152     /// compiler is actually supposed to know about.
00153     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
00154     ///   descriptor provides copy and dispose helper functions
00155     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
00156     ///   object with a nontrivial destructor or copy constructor
00157     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
00158     ///   as global memory
00159     ///  29. BLOCK_USE_STRET - indicates that the block function
00160     ///   uses stret, which objc_msgSend needs to know about
00161     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
00162     ///   @encoded signature string
00163     /// And we're not supposed to manipulate these:
00164     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
00165     ///   to malloc'ed memory
00166     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
00167     ///   to GC-allocated memory
00168     /// Additionally, the bottom 16 bits are a reference count which
00169     /// should be zero on the stack.
00170     int flags;
00171 
00172     /// Reserved;  should be zero-initialized.
00173     int reserved;
00174 
00175     /// Function pointer generated from block literal.
00176     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
00177 
00178     /// Block description metadata generated from block literal.
00179     struct Block_descriptor *block_descriptor;
00180 
00181     /// Captured values follow.
00182     _CapturesTypes captures...;
00183   };
00184  */
00185 
00186 /// The number of fields in a block header.
00187 const unsigned BlockHeaderSize = 5;
00188 
00189 namespace {
00190   /// A chunk of data that we actually have to capture in the block.
00191   struct BlockLayoutChunk {
00192     CharUnits Alignment;
00193     CharUnits Size;
00194     Qualifiers::ObjCLifetime Lifetime;
00195     const BlockDecl::Capture *Capture; // null for 'this'
00196     llvm::Type *Type;
00197 
00198     BlockLayoutChunk(CharUnits align, CharUnits size,
00199                      Qualifiers::ObjCLifetime lifetime,
00200                      const BlockDecl::Capture *capture,
00201                      llvm::Type *type)
00202       : Alignment(align), Size(size), Lifetime(lifetime),
00203         Capture(capture), Type(type) {}
00204 
00205     /// Tell the block info that this chunk has the given field index.
00206     void setIndex(CGBlockInfo &info, unsigned index) {
00207       if (!Capture)
00208         info.CXXThisIndex = index;
00209       else
00210         info.Captures[Capture->getVariable()]
00211           = CGBlockInfo::Capture::makeIndex(index);
00212     }
00213   };
00214 
00215   /// Order by 1) all __strong together 2) next, all byfref together 3) next,
00216   /// all __weak together. Preserve descending alignment in all situations.
00217   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
00218     CharUnits LeftValue, RightValue;
00219     bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
00220     bool RightByref = right.Capture ? right.Capture->isByRef() : false;
00221     
00222     if (left.Lifetime == Qualifiers::OCL_Strong &&
00223         left.Alignment >= right.Alignment)
00224       LeftValue = CharUnits::fromQuantity(64);
00225     else if (LeftByref && left.Alignment >= right.Alignment)
00226       LeftValue = CharUnits::fromQuantity(32);
00227     else if (left.Lifetime == Qualifiers::OCL_Weak &&
00228              left.Alignment >= right.Alignment)
00229       LeftValue = CharUnits::fromQuantity(16);
00230     else
00231       LeftValue = left.Alignment;
00232     if (right.Lifetime == Qualifiers::OCL_Strong &&
00233         right.Alignment >= left.Alignment)
00234       RightValue = CharUnits::fromQuantity(64);
00235     else if (RightByref && right.Alignment >= left.Alignment)
00236       RightValue = CharUnits::fromQuantity(32);
00237     else if (right.Lifetime == Qualifiers::OCL_Weak &&
00238              right.Alignment >= left.Alignment)
00239       RightValue = CharUnits::fromQuantity(16);
00240     else
00241       RightValue = right.Alignment;
00242     
00243       return LeftValue > RightValue;
00244   }
00245 }
00246 
00247 /// Determines if the given type is safe for constant capture in C++.
00248 static bool isSafeForCXXConstantCapture(QualType type) {
00249   const RecordType *recordType =
00250     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
00251 
00252   // Only records can be unsafe.
00253   if (!recordType) return true;
00254 
00255   const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
00256 
00257   // Maintain semantics for classes with non-trivial dtors or copy ctors.
00258   if (!record->hasTrivialDestructor()) return false;
00259   if (record->hasNonTrivialCopyConstructor()) return false;
00260 
00261   // Otherwise, we just have to make sure there aren't any mutable
00262   // fields that might have changed since initialization.
00263   return !record->hasMutableFields();
00264 }
00265 
00266 /// It is illegal to modify a const object after initialization.
00267 /// Therefore, if a const object has a constant initializer, we don't
00268 /// actually need to keep storage for it in the block; we'll just
00269 /// rematerialize it at the start of the block function.  This is
00270 /// acceptable because we make no promises about address stability of
00271 /// captured variables.
00272 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
00273                                             CodeGenFunction *CGF,
00274                                             const VarDecl *var) {
00275   QualType type = var->getType();
00276 
00277   // We can only do this if the variable is const.
00278   if (!type.isConstQualified()) return nullptr;
00279 
00280   // Furthermore, in C++ we have to worry about mutable fields:
00281   // C++ [dcl.type.cv]p4:
00282   //   Except that any class member declared mutable can be
00283   //   modified, any attempt to modify a const object during its
00284   //   lifetime results in undefined behavior.
00285   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
00286     return nullptr;
00287 
00288   // If the variable doesn't have any initializer (shouldn't this be
00289   // invalid?), it's not clear what we should do.  Maybe capture as
00290   // zero?
00291   const Expr *init = var->getInit();
00292   if (!init) return nullptr;
00293 
00294   return CGM.EmitConstantInit(*var, CGF);
00295 }
00296 
00297 /// Get the low bit of a nonzero character count.  This is the
00298 /// alignment of the nth byte if the 0th byte is universally aligned.
00299 static CharUnits getLowBit(CharUnits v) {
00300   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
00301 }
00302 
00303 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
00304                              SmallVectorImpl<llvm::Type*> &elementTypes) {
00305   ASTContext &C = CGM.getContext();
00306 
00307   // The header is basically a 'struct { void *; int; int; void *; void *; }'.
00308   CharUnits ptrSize, ptrAlign, intSize, intAlign;
00309   std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
00310   std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
00311 
00312   // Are there crazy embedded platforms where this isn't true?
00313   assert(intSize <= ptrSize && "layout assumptions horribly violated");
00314 
00315   CharUnits headerSize = ptrSize;
00316   if (2 * intSize < ptrAlign) headerSize += ptrSize;
00317   else headerSize += 2 * intSize;
00318   headerSize += 2 * ptrSize;
00319 
00320   info.BlockAlign = ptrAlign;
00321   info.BlockSize = headerSize;
00322 
00323   assert(elementTypes.empty());
00324   llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
00325   llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
00326   elementTypes.push_back(i8p);
00327   elementTypes.push_back(intTy);
00328   elementTypes.push_back(intTy);
00329   elementTypes.push_back(i8p);
00330   elementTypes.push_back(CGM.getBlockDescriptorType());
00331 
00332   assert(elementTypes.size() == BlockHeaderSize);
00333 }
00334 
00335 /// Compute the layout of the given block.  Attempts to lay the block
00336 /// out with minimal space requirements.
00337 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
00338                              CGBlockInfo &info) {
00339   ASTContext &C = CGM.getContext();
00340   const BlockDecl *block = info.getBlockDecl();
00341 
00342   SmallVector<llvm::Type*, 8> elementTypes;
00343   initializeForBlockHeader(CGM, info, elementTypes);
00344 
00345   if (!block->hasCaptures()) {
00346     info.StructureType =
00347       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
00348     info.CanBeGlobal = true;
00349     return;
00350   }
00351   else if (C.getLangOpts().ObjC1 &&
00352            CGM.getLangOpts().getGC() == LangOptions::NonGC)
00353     info.HasCapturedVariableLayout = true;
00354   
00355   // Collect the layout chunks.
00356   SmallVector<BlockLayoutChunk, 16> layout;
00357   layout.reserve(block->capturesCXXThis() +
00358                  (block->capture_end() - block->capture_begin()));
00359 
00360   CharUnits maxFieldAlign;
00361 
00362   // First, 'this'.
00363   if (block->capturesCXXThis()) {
00364     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
00365            "Can't capture 'this' outside a method");
00366     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
00367 
00368     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
00369     std::pair<CharUnits,CharUnits> tinfo
00370       = CGM.getContext().getTypeInfoInChars(thisType);
00371     maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
00372 
00373     layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
00374                                       Qualifiers::OCL_None,
00375                                       nullptr, llvmType));
00376   }
00377 
00378   // Next, all the block captures.
00379   for (const auto &CI : block->captures()) {
00380     const VarDecl *variable = CI.getVariable();
00381 
00382     if (CI.isByRef()) {
00383       // We have to copy/dispose of the __block reference.
00384       info.NeedsCopyDispose = true;
00385 
00386       // Just use void* instead of a pointer to the byref type.
00387       QualType byRefPtrTy = C.VoidPtrTy;
00388 
00389       llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
00390       std::pair<CharUnits,CharUnits> tinfo
00391         = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
00392       maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
00393 
00394       layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
00395                                         Qualifiers::OCL_None, &CI, llvmType));
00396       continue;
00397     }
00398 
00399     // Otherwise, build a layout chunk with the size and alignment of
00400     // the declaration.
00401     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
00402       info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
00403       continue;
00404     }
00405 
00406     // If we have a lifetime qualifier, honor it for capture purposes.
00407     // That includes *not* copying it if it's __unsafe_unretained.
00408     Qualifiers::ObjCLifetime lifetime =
00409       variable->getType().getObjCLifetime();
00410     if (lifetime) {
00411       switch (lifetime) {
00412       case Qualifiers::OCL_None: llvm_unreachable("impossible");
00413       case Qualifiers::OCL_ExplicitNone:
00414       case Qualifiers::OCL_Autoreleasing:
00415         break;
00416 
00417       case Qualifiers::OCL_Strong:
00418       case Qualifiers::OCL_Weak:
00419         info.NeedsCopyDispose = true;
00420       }
00421 
00422     // Block pointers require copy/dispose.  So do Objective-C pointers.
00423     } else if (variable->getType()->isObjCRetainableType()) {
00424       info.NeedsCopyDispose = true;
00425       // used for mrr below.
00426       lifetime = Qualifiers::OCL_Strong;
00427 
00428     // So do types that require non-trivial copy construction.
00429     } else if (CI.hasCopyExpr()) {
00430       info.NeedsCopyDispose = true;
00431       info.HasCXXObject = true;
00432 
00433     // And so do types with destructors.
00434     } else if (CGM.getLangOpts().CPlusPlus) {
00435       if (const CXXRecordDecl *record =
00436             variable->getType()->getAsCXXRecordDecl()) {
00437         if (!record->hasTrivialDestructor()) {
00438           info.HasCXXObject = true;
00439           info.NeedsCopyDispose = true;
00440         }
00441       }
00442     }
00443 
00444     QualType VT = variable->getType();
00445     CharUnits size = C.getTypeSizeInChars(VT);
00446     CharUnits align = C.getDeclAlign(variable);
00447     
00448     maxFieldAlign = std::max(maxFieldAlign, align);
00449 
00450     llvm::Type *llvmType =
00451       CGM.getTypes().ConvertTypeForMem(VT);
00452     
00453     layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
00454   }
00455 
00456   // If that was everything, we're done here.
00457   if (layout.empty()) {
00458     info.StructureType =
00459       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
00460     info.CanBeGlobal = true;
00461     return;
00462   }
00463 
00464   // Sort the layout by alignment.  We have to use a stable sort here
00465   // to get reproducible results.  There should probably be an
00466   // llvm::array_pod_stable_sort.
00467   std::stable_sort(layout.begin(), layout.end());
00468   
00469   // Needed for blocks layout info.
00470   info.BlockHeaderForcedGapOffset = info.BlockSize;
00471   info.BlockHeaderForcedGapSize = CharUnits::Zero();
00472   
00473   CharUnits &blockSize = info.BlockSize;
00474   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
00475 
00476   // Assuming that the first byte in the header is maximally aligned,
00477   // get the alignment of the first byte following the header.
00478   CharUnits endAlign = getLowBit(blockSize);
00479 
00480   // If the end of the header isn't satisfactorily aligned for the
00481   // maximum thing, look for things that are okay with the header-end
00482   // alignment, and keep appending them until we get something that's
00483   // aligned right.  This algorithm is only guaranteed optimal if
00484   // that condition is satisfied at some point; otherwise we can get
00485   // things like:
00486   //   header                 // next byte has alignment 4
00487   //   something_with_size_5; // next byte has alignment 1
00488   //   something_with_alignment_8;
00489   // which has 7 bytes of padding, as opposed to the naive solution
00490   // which might have less (?).
00491   if (endAlign < maxFieldAlign) {
00492     SmallVectorImpl<BlockLayoutChunk>::iterator
00493       li = layout.begin() + 1, le = layout.end();
00494 
00495     // Look for something that the header end is already
00496     // satisfactorily aligned for.
00497     for (; li != le && endAlign < li->Alignment; ++li)
00498       ;
00499 
00500     // If we found something that's naturally aligned for the end of
00501     // the header, keep adding things...
00502     if (li != le) {
00503       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
00504       for (; li != le; ++li) {
00505         assert(endAlign >= li->Alignment);
00506 
00507         li->setIndex(info, elementTypes.size());
00508         elementTypes.push_back(li->Type);
00509         blockSize += li->Size;
00510         endAlign = getLowBit(blockSize);
00511 
00512         // ...until we get to the alignment of the maximum field.
00513         if (endAlign >= maxFieldAlign) {
00514           if (li == first) {
00515             // No user field was appended. So, a gap was added.
00516             // Save total gap size for use in block layout bit map.
00517             info.BlockHeaderForcedGapSize = li->Size;
00518           }
00519           break;
00520         }
00521       }
00522       // Don't re-append everything we just appended.
00523       layout.erase(first, li);
00524     }
00525   }
00526 
00527   assert(endAlign == getLowBit(blockSize));
00528   
00529   // At this point, we just have to add padding if the end align still
00530   // isn't aligned right.
00531   if (endAlign < maxFieldAlign) {
00532     CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
00533     CharUnits padding = newBlockSize - blockSize;
00534 
00535     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
00536                                                 padding.getQuantity()));
00537     blockSize = newBlockSize;
00538     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
00539   }
00540 
00541   assert(endAlign >= maxFieldAlign);
00542   assert(endAlign == getLowBit(blockSize));
00543   // Slam everything else on now.  This works because they have
00544   // strictly decreasing alignment and we expect that size is always a
00545   // multiple of alignment.
00546   for (SmallVectorImpl<BlockLayoutChunk>::iterator
00547          li = layout.begin(), le = layout.end(); li != le; ++li) {
00548     if (endAlign < li->Alignment) {
00549       // size may not be multiple of alignment. This can only happen with
00550       // an over-aligned variable. We will be adding a padding field to
00551       // make the size be multiple of alignment.
00552       CharUnits padding = li->Alignment - endAlign;
00553       elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
00554                                                   padding.getQuantity()));
00555       blockSize += padding;
00556       endAlign = getLowBit(blockSize);
00557     }
00558     assert(endAlign >= li->Alignment);
00559     li->setIndex(info, elementTypes.size());
00560     elementTypes.push_back(li->Type);
00561     blockSize += li->Size;
00562     endAlign = getLowBit(blockSize);
00563   }
00564 
00565   info.StructureType =
00566     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
00567 }
00568 
00569 /// Enter the scope of a block.  This should be run at the entrance to
00570 /// a full-expression so that the block's cleanups are pushed at the
00571 /// right place in the stack.
00572 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
00573   assert(CGF.HaveInsertPoint());
00574 
00575   // Allocate the block info and place it at the head of the list.
00576   CGBlockInfo &blockInfo =
00577     *new CGBlockInfo(block, CGF.CurFn->getName());
00578   blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
00579   CGF.FirstBlockInfo = &blockInfo;
00580 
00581   // Compute information about the layout, etc., of this block,
00582   // pushing cleanups as necessary.
00583   computeBlockInfo(CGF.CGM, &CGF, blockInfo);
00584 
00585   // Nothing else to do if it can be global.
00586   if (blockInfo.CanBeGlobal) return;
00587 
00588   // Make the allocation for the block.
00589   blockInfo.Address =
00590     CGF.CreateTempAlloca(blockInfo.StructureType, "block");
00591   blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
00592 
00593   // If there are cleanups to emit, enter them (but inactive).
00594   if (!blockInfo.NeedsCopyDispose) return;
00595 
00596   // Walk through the captures (in order) and find the ones not
00597   // captured by constant.
00598   for (const auto &CI : block->captures()) {
00599     // Ignore __block captures; there's nothing special in the
00600     // on-stack block that we need to do for them.
00601     if (CI.isByRef()) continue;
00602 
00603     // Ignore variables that are constant-captured.
00604     const VarDecl *variable = CI.getVariable();
00605     CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
00606     if (capture.isConstant()) continue;
00607 
00608     // Ignore objects that aren't destructed.
00609     QualType::DestructionKind dtorKind =
00610       variable->getType().isDestructedType();
00611     if (dtorKind == QualType::DK_none) continue;
00612 
00613     CodeGenFunction::Destroyer *destroyer;
00614 
00615     // Block captures count as local values and have imprecise semantics.
00616     // They also can't be arrays, so need to worry about that.
00617     if (dtorKind == QualType::DK_objc_strong_lifetime) {
00618       destroyer = CodeGenFunction::destroyARCStrongImprecise;
00619     } else {
00620       destroyer = CGF.getDestroyer(dtorKind);
00621     }
00622 
00623     // GEP down to the address.
00624     llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
00625                                                     capture.getIndex());
00626 
00627     // We can use that GEP as the dominating IP.
00628     if (!blockInfo.DominatingIP)
00629       blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
00630 
00631     CleanupKind cleanupKind = InactiveNormalCleanup;
00632     bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
00633     if (useArrayEHCleanup) 
00634       cleanupKind = InactiveNormalAndEHCleanup;
00635 
00636     CGF.pushDestroy(cleanupKind, addr, variable->getType(),
00637                     destroyer, useArrayEHCleanup);
00638 
00639     // Remember where that cleanup was.
00640     capture.setCleanup(CGF.EHStack.stable_begin());
00641   }
00642 }
00643 
00644 /// Enter a full-expression with a non-trivial number of objects to
00645 /// clean up.  This is in this file because, at the moment, the only
00646 /// kind of cleanup object is a BlockDecl*.
00647 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
00648   assert(E->getNumObjects() != 0);
00649   ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
00650   for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
00651          i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
00652     enterBlockScope(*this, *i);
00653   }
00654 }
00655 
00656 /// Find the layout for the given block in a linked list and remove it.
00657 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
00658                                            const BlockDecl *block) {
00659   while (true) {
00660     assert(head && *head);
00661     CGBlockInfo *cur = *head;
00662 
00663     // If this is the block we're looking for, splice it out of the list.
00664     if (cur->getBlockDecl() == block) {
00665       *head = cur->NextBlockInfo;
00666       return cur;
00667     }
00668 
00669     head = &cur->NextBlockInfo;
00670   }
00671 }
00672 
00673 /// Destroy a chain of block layouts.
00674 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
00675   assert(head && "destroying an empty chain");
00676   do {
00677     CGBlockInfo *cur = head;
00678     head = cur->NextBlockInfo;
00679     delete cur;
00680   } while (head != nullptr);
00681 }
00682 
00683 /// Emit a block literal expression in the current function.
00684 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
00685   // If the block has no captures, we won't have a pre-computed
00686   // layout for it.
00687   if (!blockExpr->getBlockDecl()->hasCaptures()) {
00688     CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
00689     computeBlockInfo(CGM, this, blockInfo);
00690     blockInfo.BlockExpression = blockExpr;
00691     return EmitBlockLiteral(blockInfo);
00692   }
00693 
00694   // Find the block info for this block and take ownership of it.
00695   std::unique_ptr<CGBlockInfo> blockInfo;
00696   blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
00697                                          blockExpr->getBlockDecl()));
00698 
00699   blockInfo->BlockExpression = blockExpr;
00700   return EmitBlockLiteral(*blockInfo);
00701 }
00702 
00703 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
00704   // Using the computed layout, generate the actual block function.
00705   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
00706   llvm::Constant *blockFn
00707     = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
00708                                                        LocalDeclMap,
00709                                                        isLambdaConv);
00710   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
00711 
00712   // If there is nothing to capture, we can emit this as a global block.
00713   if (blockInfo.CanBeGlobal)
00714     return buildGlobalBlock(CGM, blockInfo, blockFn);
00715 
00716   // Otherwise, we have to emit this as a local block.
00717 
00718   llvm::Constant *isa = CGM.getNSConcreteStackBlock();
00719   isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
00720 
00721   // Build the block descriptor.
00722   llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
00723 
00724   llvm::AllocaInst *blockAddr = blockInfo.Address;
00725   assert(blockAddr && "block has no address!");
00726 
00727   // Compute the initial on-stack block flags.
00728   BlockFlags flags = BLOCK_HAS_SIGNATURE;
00729   if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
00730   if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
00731   if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
00732   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
00733 
00734   // Initialize the block literal.
00735   Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
00736   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
00737                       Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
00738   Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
00739                       Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
00740   Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
00741                                                        "block.invoke"));
00742   Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
00743                                                           "block.descriptor"));
00744 
00745   // Finally, capture all the values into the block.
00746   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
00747 
00748   // First, 'this'.
00749   if (blockDecl->capturesCXXThis()) {
00750     llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
00751                                                 blockInfo.CXXThisIndex,
00752                                                 "block.captured-this.addr");
00753     Builder.CreateStore(LoadCXXThis(), addr);
00754   }
00755 
00756   // Next, captured variables.
00757   for (const auto &CI : blockDecl->captures()) {
00758     const VarDecl *variable = CI.getVariable();
00759     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
00760 
00761     // Ignore constant captures.
00762     if (capture.isConstant()) continue;
00763 
00764     QualType type = variable->getType();
00765     CharUnits align = getContext().getDeclAlign(variable);
00766 
00767     // This will be a [[type]]*, except that a byref entry will just be
00768     // an i8**.
00769     llvm::Value *blockField =
00770       Builder.CreateStructGEP(blockAddr, capture.getIndex(),
00771                               "block.captured");
00772 
00773     // Compute the address of the thing we're going to move into the
00774     // block literal.
00775     llvm::Value *src;
00776     if (BlockInfo && CI.isNested()) {
00777       // We need to use the capture from the enclosing block.
00778       const CGBlockInfo::Capture &enclosingCapture =
00779         BlockInfo->getCapture(variable);
00780 
00781       // This is a [[type]]*, except that a byref entry wil just be an i8**.
00782       src = Builder.CreateStructGEP(LoadBlockStruct(),
00783                                     enclosingCapture.getIndex(),
00784                                     "block.capture.addr");
00785     } else if (blockDecl->isConversionFromLambda()) {
00786       // The lambda capture in a lambda's conversion-to-block-pointer is
00787       // special; we'll simply emit it directly.
00788       src = nullptr;
00789     } else {
00790       // Just look it up in the locals map, which will give us back a
00791       // [[type]]*.  If that doesn't work, do the more elaborate DRE
00792       // emission.
00793       src = LocalDeclMap.lookup(variable);
00794       if (!src) {
00795         DeclRefExpr declRef(
00796             const_cast<VarDecl *>(variable),
00797             /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
00798             VK_LValue, SourceLocation());
00799         src = EmitDeclRefLValue(&declRef).getAddress();
00800       }
00801     }
00802 
00803     // For byrefs, we just write the pointer to the byref struct into
00804     // the block field.  There's no need to chase the forwarding
00805     // pointer at this point, since we're building something that will
00806     // live a shorter life than the stack byref anyway.
00807     if (CI.isByRef()) {
00808       // Get a void* that points to the byref struct.
00809       if (CI.isNested())
00810         src = Builder.CreateAlignedLoad(src, align.getQuantity(),
00811                                         "byref.capture");
00812       else
00813         src = Builder.CreateBitCast(src, VoidPtrTy);
00814 
00815       // Write that void* into the capture field.
00816       Builder.CreateAlignedStore(src, blockField, align.getQuantity());
00817 
00818     // If we have a copy constructor, evaluate that into the block field.
00819     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
00820       if (blockDecl->isConversionFromLambda()) {
00821         // If we have a lambda conversion, emit the expression
00822         // directly into the block instead.
00823         AggValueSlot Slot =
00824             AggValueSlot::forAddr(blockField, align, Qualifiers(),
00825                                   AggValueSlot::IsDestructed,
00826                                   AggValueSlot::DoesNotNeedGCBarriers,
00827                                   AggValueSlot::IsNotAliased);
00828         EmitAggExpr(copyExpr, Slot);
00829       } else {
00830         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
00831       }
00832 
00833     // If it's a reference variable, copy the reference into the block field.
00834     } else if (type->isReferenceType()) {
00835       llvm::Value *ref =
00836         Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
00837       Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
00838 
00839     // If this is an ARC __strong block-pointer variable, don't do a
00840     // block copy.
00841     //
00842     // TODO: this can be generalized into the normal initialization logic:
00843     // we should never need to do a block-copy when initializing a local
00844     // variable, because the local variable's lifetime should be strictly
00845     // contained within the stack block's.
00846     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
00847                type->isBlockPointerType()) {
00848       // Load the block and do a simple retain.
00849       LValue srcLV = MakeAddrLValue(src, type, align);
00850       llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
00851       value = EmitARCRetainNonBlock(value);
00852 
00853       // Do a primitive store to the block field.
00854       LValue destLV = MakeAddrLValue(blockField, type, align);
00855       EmitStoreOfScalar(value, destLV, /*init*/ true);
00856 
00857     // Otherwise, fake up a POD copy into the block field.
00858     } else {
00859       // Fake up a new variable so that EmitScalarInit doesn't think
00860       // we're referring to the variable in its own initializer.
00861       ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
00862                                             SourceLocation(), /*name*/ nullptr,
00863                                             type);
00864 
00865       // We use one of these or the other depending on whether the
00866       // reference is nested.
00867       DeclRefExpr declRef(const_cast<VarDecl *>(variable),
00868                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
00869                           type, VK_LValue, SourceLocation());
00870 
00871       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
00872                            &declRef, VK_RValue);
00873       // FIXME: Pass a specific location for the expr init so that the store is
00874       // attributed to a reasonable location - otherwise it may be attributed to
00875       // locations of subexpressions in the initialization.
00876       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
00877                      MakeAddrLValue(blockField, type, align),
00878                      /*captured by init*/ false);
00879     }
00880 
00881     // Activate the cleanup if layout pushed one.
00882     if (!CI.isByRef()) {
00883       EHScopeStack::stable_iterator cleanup = capture.getCleanup();
00884       if (cleanup.isValid())
00885         ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
00886     }
00887   }
00888 
00889   // Cast to the converted block-pointer type, which happens (somewhat
00890   // unfortunately) to be a pointer to function type.
00891   llvm::Value *result =
00892     Builder.CreateBitCast(blockAddr,
00893                           ConvertType(blockInfo.getBlockExpr()->getType()));
00894 
00895   return result;
00896 }
00897 
00898 
00899 llvm::Type *CodeGenModule::getBlockDescriptorType() {
00900   if (BlockDescriptorType)
00901     return BlockDescriptorType;
00902 
00903   llvm::Type *UnsignedLongTy =
00904     getTypes().ConvertType(getContext().UnsignedLongTy);
00905 
00906   // struct __block_descriptor {
00907   //   unsigned long reserved;
00908   //   unsigned long block_size;
00909   //
00910   //   // later, the following will be added
00911   //
00912   //   struct {
00913   //     void (*copyHelper)();
00914   //     void (*copyHelper)();
00915   //   } helpers;                // !!! optional
00916   //
00917   //   const char *signature;   // the block signature
00918   //   const char *layout;      // reserved
00919   // };
00920   BlockDescriptorType =
00921     llvm::StructType::create("struct.__block_descriptor",
00922                              UnsignedLongTy, UnsignedLongTy, nullptr);
00923 
00924   // Now form a pointer to that.
00925   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
00926   return BlockDescriptorType;
00927 }
00928 
00929 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
00930   if (GenericBlockLiteralType)
00931     return GenericBlockLiteralType;
00932 
00933   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
00934 
00935   // struct __block_literal_generic {
00936   //   void *__isa;
00937   //   int __flags;
00938   //   int __reserved;
00939   //   void (*__invoke)(void *);
00940   //   struct __block_descriptor *__descriptor;
00941   // };
00942   GenericBlockLiteralType =
00943     llvm::StructType::create("struct.__block_literal_generic",
00944                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
00945                              BlockDescPtrTy, nullptr);
00946 
00947   return GenericBlockLiteralType;
00948 }
00949 
00950 
00951 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E, 
00952                                           ReturnValueSlot ReturnValue) {
00953   const BlockPointerType *BPT =
00954     E->getCallee()->getType()->getAs<BlockPointerType>();
00955 
00956   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
00957 
00958   // Get a pointer to the generic block literal.
00959   llvm::Type *BlockLiteralTy =
00960     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
00961 
00962   // Bitcast the callee to a block literal.
00963   llvm::Value *BlockLiteral =
00964     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
00965 
00966   // Get the function pointer from the literal.
00967   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
00968 
00969   BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
00970 
00971   // Add the block literal.
00972   CallArgList Args;
00973   Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
00974 
00975   QualType FnType = BPT->getPointeeType();
00976 
00977   // And the rest of the arguments.
00978   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
00979                E->arg_begin(), E->arg_end());
00980 
00981   // Load the function.
00982   llvm::Value *Func = Builder.CreateLoad(FuncPtr);
00983 
00984   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
00985   const CGFunctionInfo &FnInfo =
00986     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
00987 
00988   // Cast the function pointer to the right type.
00989   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
00990 
00991   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
00992   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
00993 
00994   // And call the block.
00995   return EmitCall(FnInfo, Func, ReturnValue, Args);
00996 }
00997 
00998 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
00999                                                  bool isByRef) {
01000   assert(BlockInfo && "evaluating block ref without block information?");
01001   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
01002 
01003   // Handle constant captures.
01004   if (capture.isConstant()) return LocalDeclMap[variable];
01005 
01006   llvm::Value *addr =
01007     Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
01008                             "block.capture.addr");
01009 
01010   if (isByRef) {
01011     // addr should be a void** right now.  Load, then cast the result
01012     // to byref*.
01013 
01014     addr = Builder.CreateLoad(addr);
01015     llvm::PointerType *byrefPointerType
01016       = llvm::PointerType::get(BuildByRefType(variable), 0);
01017     addr = Builder.CreateBitCast(addr, byrefPointerType,
01018                                  "byref.addr");
01019 
01020     // Follow the forwarding pointer.
01021     addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
01022     addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
01023 
01024     // Cast back to byref* and GEP over to the actual object.
01025     addr = Builder.CreateBitCast(addr, byrefPointerType);
01026     addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable), 
01027                                    variable->getNameAsString());
01028   }
01029 
01030   if (variable->getType()->isReferenceType())
01031     addr = Builder.CreateLoad(addr, "ref.tmp");
01032 
01033   return addr;
01034 }
01035 
01036 llvm::Constant *
01037 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
01038                                     const char *name) {
01039   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
01040   blockInfo.BlockExpression = blockExpr;
01041 
01042   // Compute information about the layout, etc., of this block.
01043   computeBlockInfo(*this, nullptr, blockInfo);
01044 
01045   // Using that metadata, generate the actual block function.
01046   llvm::Constant *blockFn;
01047   {
01048     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
01049     blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
01050                                                            blockInfo,
01051                                                            LocalDeclMap,
01052                                                            false);
01053   }
01054   blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
01055 
01056   return buildGlobalBlock(*this, blockInfo, blockFn);
01057 }
01058 
01059 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
01060                                         const CGBlockInfo &blockInfo,
01061                                         llvm::Constant *blockFn) {
01062   assert(blockInfo.CanBeGlobal);
01063 
01064   // Generate the constants for the block literal initializer.
01065   llvm::Constant *fields[BlockHeaderSize];
01066 
01067   // isa
01068   fields[0] = CGM.getNSConcreteGlobalBlock();
01069 
01070   // __flags
01071   BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
01072   if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
01073                                       
01074   fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
01075 
01076   // Reserved
01077   fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
01078 
01079   // Function
01080   fields[3] = blockFn;
01081 
01082   // Descriptor
01083   fields[4] = buildBlockDescriptor(CGM, blockInfo);
01084 
01085   llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
01086 
01087   llvm::GlobalVariable *literal =
01088     new llvm::GlobalVariable(CGM.getModule(),
01089                              init->getType(),
01090                              /*constant*/ true,
01091                              llvm::GlobalVariable::InternalLinkage,
01092                              init,
01093                              "__block_literal_global");
01094   literal->setAlignment(blockInfo.BlockAlign.getQuantity());
01095 
01096   // Return a constant of the appropriately-casted type.
01097   llvm::Type *requiredType =
01098     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
01099   return llvm::ConstantExpr::getBitCast(literal, requiredType);
01100 }
01101 
01102 llvm::Function *
01103 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
01104                                        const CGBlockInfo &blockInfo,
01105                                        const DeclMapTy &ldm,
01106                                        bool IsLambdaConversionToBlock) {
01107   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01108 
01109   CurGD = GD;
01110 
01111   CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
01112   
01113   BlockInfo = &blockInfo;
01114 
01115   // Arrange for local static and local extern declarations to appear
01116   // to be local to this function as well, in case they're directly
01117   // referenced in a block.
01118   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
01119     const auto *var = dyn_cast<VarDecl>(i->first);
01120     if (var && !var->hasLocalStorage())
01121       LocalDeclMap[var] = i->second;
01122   }
01123 
01124   // Begin building the function declaration.
01125 
01126   // Build the argument list.
01127   FunctionArgList args;
01128 
01129   // The first argument is the block pointer.  Just take it as a void*
01130   // and cast it later.
01131   QualType selfTy = getContext().VoidPtrTy;
01132   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
01133 
01134   ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
01135                              SourceLocation(), II, selfTy);
01136   args.push_back(&selfDecl);
01137 
01138   // Now add the rest of the parameters.
01139   args.append(blockDecl->param_begin(), blockDecl->param_end());
01140 
01141   // Create the function declaration.
01142   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
01143   const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
01144       fnType->getReturnType(), args, fnType->getExtInfo(),
01145       fnType->isVariadic());
01146   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
01147     blockInfo.UsesStret = true;
01148 
01149   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
01150 
01151   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
01152   llvm::Function *fn = llvm::Function::Create(
01153       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
01154   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
01155 
01156   // Begin generating the function.
01157   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
01158                 blockDecl->getLocation(),
01159                 blockInfo.getBlockExpr()->getBody()->getLocStart());
01160 
01161   // Okay.  Undo some of what StartFunction did.
01162   
01163   // Pull the 'self' reference out of the local decl map.
01164   llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
01165   LocalDeclMap.erase(&selfDecl);
01166   BlockPointer = Builder.CreateBitCast(blockAddr,
01167                                        blockInfo.StructureType->getPointerTo(),
01168                                        "block");
01169   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
01170   // won't delete the dbg.declare intrinsics for captured variables.
01171   llvm::Value *BlockPointerDbgLoc = BlockPointer;
01172   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
01173     // Allocate a stack slot for it, so we can point the debugger to it
01174     llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
01175                                                 "block.addr");
01176     unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
01177     Alloca->setAlignment(Align);
01178     // Set the DebugLocation to empty, so the store is recognized as a
01179     // frame setup instruction by llvm::DwarfDebug::beginFunction().
01180     auto NL = ApplyDebugLocation::CreateEmpty(*this);
01181     Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
01182     BlockPointerDbgLoc = Alloca;
01183   }
01184 
01185   // If we have a C++ 'this' reference, go ahead and force it into
01186   // existence now.
01187   if (blockDecl->capturesCXXThis()) {
01188     llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
01189                                                 blockInfo.CXXThisIndex,
01190                                                 "block.captured-this");
01191     CXXThisValue = Builder.CreateLoad(addr, "this");
01192   }
01193 
01194   // Also force all the constant captures.
01195   for (const auto &CI : blockDecl->captures()) {
01196     const VarDecl *variable = CI.getVariable();
01197     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01198     if (!capture.isConstant()) continue;
01199 
01200     unsigned align = getContext().getDeclAlign(variable).getQuantity();
01201 
01202     llvm::AllocaInst *alloca =
01203       CreateMemTemp(variable->getType(), "block.captured-const");
01204     alloca->setAlignment(align);
01205 
01206     Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
01207 
01208     LocalDeclMap[variable] = alloca;
01209   }
01210 
01211   // Save a spot to insert the debug information for all the DeclRefExprs.
01212   llvm::BasicBlock *entry = Builder.GetInsertBlock();
01213   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
01214   --entry_ptr;
01215 
01216   if (IsLambdaConversionToBlock)
01217     EmitLambdaBlockInvokeBody();
01218   else {
01219     PGO.assignRegionCounters(blockDecl, fn);
01220     RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
01221     Cnt.beginRegion(Builder);
01222     EmitStmt(blockDecl->getBody());
01223   }
01224 
01225   // Remember where we were...
01226   llvm::BasicBlock *resume = Builder.GetInsertBlock();
01227 
01228   // Go back to the entry.
01229   ++entry_ptr;
01230   Builder.SetInsertPoint(entry, entry_ptr);
01231 
01232   // Emit debug information for all the DeclRefExprs.
01233   // FIXME: also for 'this'
01234   if (CGDebugInfo *DI = getDebugInfo()) {
01235     for (const auto &CI : blockDecl->captures()) {
01236       const VarDecl *variable = CI.getVariable();
01237       DI->EmitLocation(Builder, variable->getLocation());
01238 
01239       if (CGM.getCodeGenOpts().getDebugInfo()
01240             >= CodeGenOptions::LimitedDebugInfo) {
01241         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01242         if (capture.isConstant()) {
01243           DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
01244                                         Builder);
01245           continue;
01246         }
01247 
01248         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
01249                                               Builder, blockInfo,
01250                                               entry_ptr == entry->end()
01251                                               ? nullptr : entry_ptr);
01252       }
01253     }
01254     // Recover location if it was changed in the above loop.
01255     DI->EmitLocation(Builder,
01256                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
01257   }
01258 
01259   // And resume where we left off.
01260   if (resume == nullptr)
01261     Builder.ClearInsertionPoint();
01262   else
01263     Builder.SetInsertPoint(resume);
01264 
01265   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
01266 
01267   return fn;
01268 }
01269 
01270 /*
01271     notes.push_back(HelperInfo());
01272     HelperInfo &note = notes.back();
01273     note.index = capture.getIndex();
01274     note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
01275     note.cxxbar_import = ci->getCopyExpr();
01276 
01277     if (ci->isByRef()) {
01278       note.flag = BLOCK_FIELD_IS_BYREF;
01279       if (type.isObjCGCWeak())
01280         note.flag |= BLOCK_FIELD_IS_WEAK;
01281     } else if (type->isBlockPointerType()) {
01282       note.flag = BLOCK_FIELD_IS_BLOCK;
01283     } else {
01284       note.flag = BLOCK_FIELD_IS_OBJECT;
01285     }
01286  */
01287 
01288 
01289 /// Generate the copy-helper function for a block closure object:
01290 ///   static void block_copy_helper(block_t *dst, block_t *src);
01291 /// The runtime will have previously initialized 'dst' by doing a
01292 /// bit-copy of 'src'.
01293 ///
01294 /// Note that this copies an entire block closure object to the heap;
01295 /// it should not be confused with a 'byref copy helper', which moves
01296 /// the contents of an individual __block variable to the heap.
01297 llvm::Constant *
01298 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
01299   ASTContext &C = getContext();
01300 
01301   FunctionArgList args;
01302   ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
01303                             C.VoidPtrTy);
01304   args.push_back(&dstDecl);
01305   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
01306                             C.VoidPtrTy);
01307   args.push_back(&srcDecl);
01308 
01309   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
01310       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
01311 
01312   // FIXME: it would be nice if these were mergeable with things with
01313   // identical semantics.
01314   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
01315 
01316   llvm::Function *Fn =
01317     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01318                            "__copy_helper_block_", &CGM.getModule());
01319 
01320   IdentifierInfo *II
01321     = &CGM.getContext().Idents.get("__copy_helper_block_");
01322 
01323   FunctionDecl *FD = FunctionDecl::Create(C,
01324                                           C.getTranslationUnitDecl(),
01325                                           SourceLocation(),
01326                                           SourceLocation(), II, C.VoidTy,
01327                                           nullptr, SC_Static,
01328                                           false,
01329                                           false);
01330   auto NL = ApplyDebugLocation::CreateEmpty(*this);
01331   StartFunction(FD, C.VoidTy, Fn, FI, args);
01332   // Create a scope with an artificial location for the body of this function.
01333   auto AL = ApplyDebugLocation::CreateArtificial(*this);
01334   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
01335 
01336   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
01337   src = Builder.CreateLoad(src);
01338   src = Builder.CreateBitCast(src, structPtrTy, "block.source");
01339 
01340   llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
01341   dst = Builder.CreateLoad(dst);
01342   dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
01343 
01344   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01345 
01346   for (const auto &CI : blockDecl->captures()) {
01347     const VarDecl *variable = CI.getVariable();
01348     QualType type = variable->getType();
01349 
01350     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01351     if (capture.isConstant()) continue;
01352 
01353     const Expr *copyExpr = CI.getCopyExpr();
01354     BlockFieldFlags flags;
01355 
01356     bool useARCWeakCopy = false;
01357     bool useARCStrongCopy = false;
01358 
01359     if (copyExpr) {
01360       assert(!CI.isByRef());
01361       // don't bother computing flags
01362 
01363     } else if (CI.isByRef()) {
01364       flags = BLOCK_FIELD_IS_BYREF;
01365       if (type.isObjCGCWeak())
01366         flags |= BLOCK_FIELD_IS_WEAK;
01367 
01368     } else if (type->isObjCRetainableType()) {
01369       flags = BLOCK_FIELD_IS_OBJECT;
01370       bool isBlockPointer = type->isBlockPointerType();
01371       if (isBlockPointer)
01372         flags = BLOCK_FIELD_IS_BLOCK;
01373 
01374       // Special rules for ARC captures:
01375       if (getLangOpts().ObjCAutoRefCount) {
01376         Qualifiers qs = type.getQualifiers();
01377 
01378         // We need to register __weak direct captures with the runtime.
01379         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
01380           useARCWeakCopy = true;
01381 
01382         // We need to retain the copied value for __strong direct captures.
01383         } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
01384           // If it's a block pointer, we have to copy the block and
01385           // assign that to the destination pointer, so we might as
01386           // well use _Block_object_assign.  Otherwise we can avoid that.
01387           if (!isBlockPointer)
01388             useARCStrongCopy = true;
01389 
01390         // Otherwise the memcpy is fine.
01391         } else {
01392           continue;
01393         }
01394 
01395       // Non-ARC captures of retainable pointers are strong and
01396       // therefore require a call to _Block_object_assign.
01397       } else {
01398         // fall through
01399       }
01400     } else {
01401       continue;
01402     }
01403 
01404     unsigned index = capture.getIndex();
01405     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
01406     llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
01407 
01408     // If there's an explicit copy expression, we do that.
01409     if (copyExpr) {
01410       EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
01411     } else if (useARCWeakCopy) {
01412       EmitARCCopyWeak(dstField, srcField);
01413     } else {
01414       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
01415       if (useARCStrongCopy) {
01416         // At -O0, store null into the destination field (so that the
01417         // storeStrong doesn't over-release) and then call storeStrong.
01418         // This is a workaround to not having an initStrong call.
01419         if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
01420           auto *ty = cast<llvm::PointerType>(srcValue->getType());
01421           llvm::Value *null = llvm::ConstantPointerNull::get(ty);
01422           Builder.CreateStore(null, dstField);
01423           EmitARCStoreStrongCall(dstField, srcValue, true);
01424 
01425         // With optimization enabled, take advantage of the fact that
01426         // the blocks runtime guarantees a memcpy of the block data, and
01427         // just emit a retain of the src field.
01428         } else {
01429           EmitARCRetainNonBlock(srcValue);
01430 
01431           // We don't need this anymore, so kill it.  It's not quite
01432           // worth the annoyance to avoid creating it in the first place.
01433           cast<llvm::Instruction>(dstField)->eraseFromParent();
01434         }
01435       } else {
01436         srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
01437         llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
01438         llvm::Value *args[] = {
01439           dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
01440         };
01441 
01442         bool copyCanThrow = false;
01443         if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
01444           const Expr *copyExpr =
01445             CGM.getContext().getBlockVarCopyInits(variable);
01446           if (copyExpr) {
01447             copyCanThrow = true; // FIXME: reuse the noexcept logic
01448           }
01449         }
01450 
01451         if (copyCanThrow) {
01452           EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
01453         } else {
01454           EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
01455         }
01456       }
01457     }
01458   }
01459 
01460   FinishFunction();
01461 
01462   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
01463 }
01464 
01465 /// Generate the destroy-helper function for a block closure object:
01466 ///   static void block_destroy_helper(block_t *theBlock);
01467 ///
01468 /// Note that this destroys a heap-allocated block closure object;
01469 /// it should not be confused with a 'byref destroy helper', which
01470 /// destroys the heap-allocated contents of an individual __block
01471 /// variable.
01472 llvm::Constant *
01473 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
01474   ASTContext &C = getContext();
01475 
01476   FunctionArgList args;
01477   ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
01478                             C.VoidPtrTy);
01479   args.push_back(&srcDecl);
01480 
01481   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
01482       C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
01483 
01484   // FIXME: We'd like to put these into a mergable by content, with
01485   // internal linkage.
01486   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
01487 
01488   llvm::Function *Fn =
01489     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01490                            "__destroy_helper_block_", &CGM.getModule());
01491 
01492   IdentifierInfo *II
01493     = &CGM.getContext().Idents.get("__destroy_helper_block_");
01494 
01495   FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
01496                                           SourceLocation(),
01497                                           SourceLocation(), II, C.VoidTy,
01498                                           nullptr, SC_Static,
01499                                           false, false);
01500   // Create a scope with an artificial location for the body of this function.
01501   auto NL = ApplyDebugLocation::CreateEmpty(*this);
01502   StartFunction(FD, C.VoidTy, Fn, FI, args);
01503   auto AL = ApplyDebugLocation::CreateArtificial(*this);
01504 
01505   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
01506 
01507   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
01508   src = Builder.CreateLoad(src);
01509   src = Builder.CreateBitCast(src, structPtrTy, "block");
01510 
01511   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01512 
01513   CodeGenFunction::RunCleanupsScope cleanups(*this);
01514 
01515   for (const auto &CI : blockDecl->captures()) {
01516     const VarDecl *variable = CI.getVariable();
01517     QualType type = variable->getType();
01518 
01519     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01520     if (capture.isConstant()) continue;
01521 
01522     BlockFieldFlags flags;
01523     const CXXDestructorDecl *dtor = nullptr;
01524 
01525     bool useARCWeakDestroy = false;
01526     bool useARCStrongDestroy = false;
01527 
01528     if (CI.isByRef()) {
01529       flags = BLOCK_FIELD_IS_BYREF;
01530       if (type.isObjCGCWeak())
01531         flags |= BLOCK_FIELD_IS_WEAK;
01532     } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
01533       if (record->hasTrivialDestructor())
01534         continue;
01535       dtor = record->getDestructor();
01536     } else if (type->isObjCRetainableType()) {
01537       flags = BLOCK_FIELD_IS_OBJECT;
01538       if (type->isBlockPointerType())
01539         flags = BLOCK_FIELD_IS_BLOCK;
01540 
01541       // Special rules for ARC captures.
01542       if (getLangOpts().ObjCAutoRefCount) {
01543         Qualifiers qs = type.getQualifiers();
01544 
01545         // Don't generate special dispose logic for a captured object
01546         // unless it's __strong or __weak.
01547         if (!qs.hasStrongOrWeakObjCLifetime())
01548           continue;
01549 
01550         // Support __weak direct captures.
01551         if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
01552           useARCWeakDestroy = true;
01553 
01554         // Tools really want us to use objc_storeStrong here.
01555         else
01556           useARCStrongDestroy = true;
01557       }
01558     } else {
01559       continue;
01560     }
01561 
01562     unsigned index = capture.getIndex();
01563     llvm::Value *srcField = Builder.CreateStructGEP(src, index);
01564 
01565     // If there's an explicit copy expression, we do that.
01566     if (dtor) {
01567       PushDestructorCleanup(dtor, srcField);
01568 
01569     // If this is a __weak capture, emit the release directly.
01570     } else if (useARCWeakDestroy) {
01571       EmitARCDestroyWeak(srcField);
01572 
01573     // Destroy strong objects with a call if requested.
01574     } else if (useARCStrongDestroy) {
01575       EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
01576 
01577     // Otherwise we call _Block_object_dispose.  It wouldn't be too
01578     // hard to just emit this as a cleanup if we wanted to make sure
01579     // that things were done in reverse.
01580     } else {
01581       llvm::Value *value = Builder.CreateLoad(srcField);
01582       value = Builder.CreateBitCast(value, VoidPtrTy);
01583       BuildBlockRelease(value, flags);
01584     }
01585   }
01586 
01587   cleanups.ForceCleanup();
01588 
01589   FinishFunction();
01590 
01591   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
01592 }
01593 
01594 namespace {
01595 
01596 /// Emits the copy/dispose helper functions for a __block object of id type.
01597 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
01598   BlockFieldFlags Flags;
01599 
01600 public:
01601   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
01602     : ByrefHelpers(alignment), Flags(flags) {}
01603 
01604   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01605                 llvm::Value *srcField) override {
01606     destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
01607 
01608     srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
01609     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
01610 
01611     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
01612 
01613     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
01614     llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
01615 
01616     llvm::Value *args[] = { destField, srcValue, flagsVal };
01617     CGF.EmitNounwindRuntimeCall(fn, args);
01618   }
01619 
01620   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01621     field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
01622     llvm::Value *value = CGF.Builder.CreateLoad(field);
01623 
01624     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
01625   }
01626 
01627   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01628     id.AddInteger(Flags.getBitMask());
01629   }
01630 };
01631 
01632 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
01633 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
01634 public:
01635   ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
01636 
01637   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01638                 llvm::Value *srcField) override {
01639     CGF.EmitARCMoveWeak(destField, srcField);
01640   }
01641 
01642   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01643     CGF.EmitARCDestroyWeak(field);
01644   }
01645 
01646   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01647     // 0 is distinguishable from all pointers and byref flags
01648     id.AddInteger(0);
01649   }
01650 };
01651 
01652 /// Emits the copy/dispose helpers for an ARC __block __strong variable
01653 /// that's not of block-pointer type.
01654 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
01655 public:
01656   ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
01657 
01658   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01659                 llvm::Value *srcField) override {
01660     // Do a "move" by copying the value and then zeroing out the old
01661     // variable.
01662 
01663     llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
01664     value->setAlignment(Alignment.getQuantity());
01665     
01666     llvm::Value *null =
01667       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
01668 
01669     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
01670       llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
01671       store->setAlignment(Alignment.getQuantity());
01672       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
01673       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
01674       return;
01675     }
01676     llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
01677     store->setAlignment(Alignment.getQuantity());
01678 
01679     store = CGF.Builder.CreateStore(null, srcField);
01680     store->setAlignment(Alignment.getQuantity());
01681   }
01682 
01683   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01684     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
01685   }
01686 
01687   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01688     // 1 is distinguishable from all pointers and byref flags
01689     id.AddInteger(1);
01690   }
01691 };
01692 
01693 /// Emits the copy/dispose helpers for an ARC __block __strong
01694 /// variable that's of block-pointer type.
01695 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
01696 public:
01697   ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
01698 
01699   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01700                 llvm::Value *srcField) override {
01701     // Do the copy with objc_retainBlock; that's all that
01702     // _Block_object_assign would do anyway, and we'd have to pass the
01703     // right arguments to make sure it doesn't get no-op'ed.
01704     llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
01705     oldValue->setAlignment(Alignment.getQuantity());
01706 
01707     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
01708 
01709     llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
01710     store->setAlignment(Alignment.getQuantity());
01711   }
01712 
01713   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01714     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
01715   }
01716 
01717   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01718     // 2 is distinguishable from all pointers and byref flags
01719     id.AddInteger(2);
01720   }
01721 };
01722 
01723 /// Emits the copy/dispose helpers for a __block variable with a
01724 /// nontrivial copy constructor or destructor.
01725 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
01726   QualType VarType;
01727   const Expr *CopyExpr;
01728 
01729 public:
01730   CXXByrefHelpers(CharUnits alignment, QualType type,
01731                   const Expr *copyExpr)
01732     : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
01733 
01734   bool needsCopy() const override { return CopyExpr != nullptr; }
01735   void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
01736                 llvm::Value *srcField) override {
01737     if (!CopyExpr) return;
01738     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
01739   }
01740 
01741   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
01742     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
01743     CGF.PushDestructorCleanup(VarType, field);
01744     CGF.PopCleanupBlocks(cleanupDepth);
01745   }
01746 
01747   void profileImpl(llvm::FoldingSetNodeID &id) const override {
01748     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
01749   }
01750 };
01751 } // end anonymous namespace
01752 
01753 static llvm::Constant *
01754 generateByrefCopyHelper(CodeGenFunction &CGF,
01755                         llvm::StructType &byrefType,
01756                         unsigned valueFieldIndex,
01757                         CodeGenModule::ByrefHelpers &byrefInfo) {
01758   ASTContext &Context = CGF.getContext();
01759 
01760   QualType R = Context.VoidTy;
01761 
01762   FunctionArgList args;
01763   ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
01764                         Context.VoidPtrTy);
01765   args.push_back(&dst);
01766 
01767   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
01768                         Context.VoidPtrTy);
01769   args.push_back(&src);
01770 
01771   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
01772       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
01773 
01774   CodeGenTypes &Types = CGF.CGM.getTypes();
01775   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
01776 
01777   // FIXME: We'd like to put these into a mergable by content, with
01778   // internal linkage.
01779   llvm::Function *Fn =
01780     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01781                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
01782 
01783   IdentifierInfo *II
01784     = &Context.Idents.get("__Block_byref_object_copy_");
01785 
01786   FunctionDecl *FD = FunctionDecl::Create(Context,
01787                                           Context.getTranslationUnitDecl(),
01788                                           SourceLocation(),
01789                                           SourceLocation(), II, R, nullptr,
01790                                           SC_Static,
01791                                           false, false);
01792 
01793   CGF.StartFunction(FD, R, Fn, FI, args);
01794 
01795   if (byrefInfo.needsCopy()) {
01796     llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
01797 
01798     // dst->x
01799     llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
01800     destField = CGF.Builder.CreateLoad(destField);
01801     destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
01802     destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
01803 
01804     // src->x
01805     llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
01806     srcField = CGF.Builder.CreateLoad(srcField);
01807     srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
01808     srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
01809 
01810     byrefInfo.emitCopy(CGF, destField, srcField);
01811   }  
01812 
01813   CGF.FinishFunction();
01814 
01815   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
01816 }
01817 
01818 /// Build the copy helper for a __block variable.
01819 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
01820                                             llvm::StructType &byrefType,
01821                                             unsigned byrefValueIndex,
01822                                             CodeGenModule::ByrefHelpers &info) {
01823   CodeGenFunction CGF(CGM);
01824   return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
01825 }
01826 
01827 /// Generate code for a __block variable's dispose helper.
01828 static llvm::Constant *
01829 generateByrefDisposeHelper(CodeGenFunction &CGF,
01830                            llvm::StructType &byrefType,
01831                            unsigned byrefValueIndex,
01832                            CodeGenModule::ByrefHelpers &byrefInfo) {
01833   ASTContext &Context = CGF.getContext();
01834   QualType R = Context.VoidTy;
01835 
01836   FunctionArgList args;
01837   ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
01838                         Context.VoidPtrTy);
01839   args.push_back(&src);
01840 
01841   const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
01842       R, args, FunctionType::ExtInfo(), /*variadic=*/false);
01843 
01844   CodeGenTypes &Types = CGF.CGM.getTypes();
01845   llvm::FunctionType *LTy = Types.GetFunctionType(FI);
01846 
01847   // FIXME: We'd like to put these into a mergable by content, with
01848   // internal linkage.
01849   llvm::Function *Fn =
01850     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
01851                            "__Block_byref_object_dispose_",
01852                            &CGF.CGM.getModule());
01853 
01854   IdentifierInfo *II
01855     = &Context.Idents.get("__Block_byref_object_dispose_");
01856 
01857   FunctionDecl *FD = FunctionDecl::Create(Context,
01858                                           Context.getTranslationUnitDecl(),
01859                                           SourceLocation(),
01860                                           SourceLocation(), II, R, nullptr,
01861                                           SC_Static,
01862                                           false, false);
01863   CGF.StartFunction(FD, R, Fn, FI, args);
01864 
01865   if (byrefInfo.needsDispose()) {
01866     llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
01867     V = CGF.Builder.CreateLoad(V);
01868     V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
01869     V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
01870 
01871     byrefInfo.emitDispose(CGF, V);
01872   }
01873 
01874   CGF.FinishFunction();
01875 
01876   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
01877 }
01878 
01879 /// Build the dispose helper for a __block variable.
01880 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
01881                                               llvm::StructType &byrefType,
01882                                                unsigned byrefValueIndex,
01883                                             CodeGenModule::ByrefHelpers &info) {
01884   CodeGenFunction CGF(CGM);
01885   return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
01886 }
01887 
01888 /// Lazily build the copy and dispose helpers for a __block variable
01889 /// with the given information.
01890 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
01891                                                llvm::StructType &byrefTy,
01892                                                unsigned byrefValueIndex,
01893                                                T &byrefInfo) {
01894   // Increase the field's alignment to be at least pointer alignment,
01895   // since the layout of the byref struct will guarantee at least that.
01896   byrefInfo.Alignment = std::max(byrefInfo.Alignment,
01897                               CharUnits::fromQuantity(CGM.PointerAlignInBytes));
01898 
01899   llvm::FoldingSetNodeID id;
01900   byrefInfo.Profile(id);
01901 
01902   void *insertPos;
01903   CodeGenModule::ByrefHelpers *node
01904     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
01905   if (node) return static_cast<T*>(node);
01906 
01907   byrefInfo.CopyHelper =
01908     buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
01909   byrefInfo.DisposeHelper =
01910     buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
01911 
01912   T *copy = new (CGM.getContext()) T(byrefInfo);
01913   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
01914   return copy;
01915 }
01916 
01917 /// Build the copy and dispose helpers for the given __block variable
01918 /// emission.  Places the helpers in the global cache.  Returns null
01919 /// if no helpers are required.
01920 CodeGenModule::ByrefHelpers *
01921 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
01922                                    const AutoVarEmission &emission) {
01923   const VarDecl &var = *emission.Variable;
01924   QualType type = var.getType();
01925 
01926   unsigned byrefValueIndex = getByRefValueLLVMField(&var);
01927 
01928   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
01929     const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
01930     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
01931 
01932     CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
01933     return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01934   }
01935 
01936   // Otherwise, if we don't have a retainable type, there's nothing to do.
01937   // that the runtime does extra copies.
01938   if (!type->isObjCRetainableType()) return nullptr;
01939 
01940   Qualifiers qs = type.getQualifiers();
01941 
01942   // If we have lifetime, that dominates.
01943   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
01944     assert(getLangOpts().ObjCAutoRefCount);
01945 
01946     switch (lifetime) {
01947     case Qualifiers::OCL_None: llvm_unreachable("impossible");
01948 
01949     // These are just bits as far as the runtime is concerned.
01950     case Qualifiers::OCL_ExplicitNone:
01951     case Qualifiers::OCL_Autoreleasing:
01952       return nullptr;
01953 
01954     // Tell the runtime that this is ARC __weak, called by the
01955     // byref routines.
01956     case Qualifiers::OCL_Weak: {
01957       ARCWeakByrefHelpers byrefInfo(emission.Alignment);
01958       return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01959     }
01960 
01961     // ARC __strong __block variables need to be retained.
01962     case Qualifiers::OCL_Strong:
01963       // Block pointers need to be copied, and there's no direct
01964       // transfer possible.
01965       if (type->isBlockPointerType()) {
01966         ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
01967         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01968 
01969       // Otherwise, we transfer ownership of the retain from the stack
01970       // to the heap.
01971       } else {
01972         ARCStrongByrefHelpers byrefInfo(emission.Alignment);
01973         return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01974       }
01975     }
01976     llvm_unreachable("fell out of lifetime switch!");
01977   }
01978 
01979   BlockFieldFlags flags;
01980   if (type->isBlockPointerType()) {
01981     flags |= BLOCK_FIELD_IS_BLOCK;
01982   } else if (CGM.getContext().isObjCNSObjectType(type) || 
01983              type->isObjCObjectPointerType()) {
01984     flags |= BLOCK_FIELD_IS_OBJECT;
01985   } else {
01986     return nullptr;
01987   }
01988 
01989   if (type.isObjCGCWeak())
01990     flags |= BLOCK_FIELD_IS_WEAK;
01991 
01992   ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
01993   return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
01994 }
01995 
01996 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
01997   assert(ByRefValueInfo.count(VD) && "Did not find value!");
01998   
01999   return ByRefValueInfo.find(VD)->second.second;
02000 }
02001 
02002 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
02003                                                      const VarDecl *V) {
02004   llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
02005   Loc = Builder.CreateLoad(Loc);
02006   Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
02007                                 V->getNameAsString());
02008   return Loc;
02009 }
02010 
02011 /// BuildByRefType - This routine changes a __block variable declared as T x
02012 ///   into:
02013 ///
02014 ///      struct {
02015 ///        void *__isa;
02016 ///        void *__forwarding;
02017 ///        int32_t __flags;
02018 ///        int32_t __size;
02019 ///        void *__copy_helper;       // only if needed
02020 ///        void *__destroy_helper;    // only if needed
02021 ///        void *__byref_variable_layout;// only if needed
02022 ///        char padding[X];           // only if needed
02023 ///        T x;
02024 ///      } x
02025 ///
02026 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
02027   std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
02028   if (Info.first)
02029     return Info.first;
02030   
02031   QualType Ty = D->getType();
02032 
02033   SmallVector<llvm::Type *, 8> types;
02034   
02035   llvm::StructType *ByRefType =
02036     llvm::StructType::create(getLLVMContext(),
02037                              "struct.__block_byref_" + D->getNameAsString());
02038   
02039   // void *__isa;
02040   types.push_back(Int8PtrTy);
02041   
02042   // void *__forwarding;
02043   types.push_back(llvm::PointerType::getUnqual(ByRefType));
02044   
02045   // int32_t __flags;
02046   types.push_back(Int32Ty);
02047     
02048   // int32_t __size;
02049   types.push_back(Int32Ty);
02050   // Note that this must match *exactly* the logic in buildByrefHelpers.
02051   bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
02052   if (HasCopyAndDispose) {
02053     /// void *__copy_helper;
02054     types.push_back(Int8PtrTy);
02055     
02056     /// void *__destroy_helper;
02057     types.push_back(Int8PtrTy);
02058   }
02059   bool HasByrefExtendedLayout = false;
02060   Qualifiers::ObjCLifetime Lifetime;
02061   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
02062       HasByrefExtendedLayout)
02063     /// void *__byref_variable_layout;
02064     types.push_back(Int8PtrTy);
02065 
02066   bool Packed = false;
02067   CharUnits Align = getContext().getDeclAlign(D);
02068   if (Align >
02069       getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
02070     // We have to insert padding.
02071     
02072     // The struct above has 2 32-bit integers.
02073     unsigned CurrentOffsetInBytes = 4 * 2;
02074     
02075     // And either 2, 3, 4 or 5 pointers.
02076     unsigned noPointers = 2;
02077     if (HasCopyAndDispose)
02078       noPointers += 2;
02079     if (HasByrefExtendedLayout)
02080       noPointers += 1;
02081     
02082     CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
02083     
02084     // Align the offset.
02085     unsigned AlignedOffsetInBytes = 
02086       llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
02087     
02088     unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
02089     if (NumPaddingBytes > 0) {
02090       llvm::Type *Ty = Int8Ty;
02091       // FIXME: We need a sema error for alignment larger than the minimum of
02092       // the maximal stack alignment and the alignment of malloc on the system.
02093       if (NumPaddingBytes > 1)
02094         Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
02095     
02096       types.push_back(Ty);
02097 
02098       // We want a packed struct.
02099       Packed = true;
02100     }
02101   }
02102 
02103   // T x;
02104   types.push_back(ConvertTypeForMem(Ty));
02105   
02106   ByRefType->setBody(types, Packed);
02107   
02108   Info.first = ByRefType;
02109   
02110   Info.second = types.size() - 1;
02111   
02112   return Info.first;
02113 }
02114 
02115 /// Initialize the structural components of a __block variable, i.e.
02116 /// everything but the actual object.
02117 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
02118   // Find the address of the local.
02119   llvm::Value *addr = emission.Address;
02120 
02121   // That's an alloca of the byref structure type.
02122   llvm::StructType *byrefType = cast<llvm::StructType>(
02123                  cast<llvm::PointerType>(addr->getType())->getElementType());
02124 
02125   // Build the byref helpers if necessary.  This is null if we don't need any.
02126   CodeGenModule::ByrefHelpers *helpers =
02127     buildByrefHelpers(*byrefType, emission);
02128 
02129   const VarDecl &D = *emission.Variable;
02130   QualType type = D.getType();
02131 
02132   bool HasByrefExtendedLayout;
02133   Qualifiers::ObjCLifetime ByrefLifetime;
02134   bool ByRefHasLifetime =
02135     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
02136   
02137   llvm::Value *V;
02138 
02139   // Initialize the 'isa', which is just 0 or 1.
02140   int isa = 0;
02141   if (type.isObjCGCWeak())
02142     isa = 1;
02143   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
02144   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
02145 
02146   // Store the address of the variable into its own forwarding pointer.
02147   Builder.CreateStore(addr,
02148                       Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
02149 
02150   // Blocks ABI:
02151   //   c) the flags field is set to either 0 if no helper functions are
02152   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
02153   BlockFlags flags;
02154   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
02155   if (ByRefHasLifetime) {
02156     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
02157       else switch (ByrefLifetime) {
02158         case Qualifiers::OCL_Strong:
02159           flags |= BLOCK_BYREF_LAYOUT_STRONG;
02160           break;
02161         case Qualifiers::OCL_Weak:
02162           flags |= BLOCK_BYREF_LAYOUT_WEAK;
02163           break;
02164         case Qualifiers::OCL_ExplicitNone:
02165           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
02166           break;
02167         case Qualifiers::OCL_None:
02168           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
02169             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
02170           break;
02171         default:
02172           break;
02173       }
02174     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
02175       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
02176       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
02177         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
02178       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
02179         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
02180         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
02181           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
02182         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
02183           printf(" BLOCK_BYREF_LAYOUT_STRONG");
02184         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
02185           printf(" BLOCK_BYREF_LAYOUT_WEAK");
02186         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
02187           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
02188         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
02189           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
02190       }
02191       printf("\n");
02192     }
02193   }
02194   
02195   Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
02196                       Builder.CreateStructGEP(addr, 2, "byref.flags"));
02197 
02198   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
02199   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
02200   Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
02201 
02202   if (helpers) {
02203     llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
02204     Builder.CreateStore(helpers->CopyHelper, copy_helper);
02205 
02206     llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
02207     Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
02208   }
02209   if (ByRefHasLifetime && HasByrefExtendedLayout) {
02210     llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
02211     llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
02212                                                          "byref.layout");
02213     // cast destination to pointer to source type.
02214     llvm::Type *DesTy = ByrefLayoutInfo->getType();
02215     DesTy = DesTy->getPointerTo();
02216     llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
02217     Builder.CreateStore(ByrefLayoutInfo, BC);
02218   }
02219 }
02220 
02221 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
02222   llvm::Value *F = CGM.getBlockObjectDispose();
02223   llvm::Value *args[] = {
02224     Builder.CreateBitCast(V, Int8PtrTy),
02225     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
02226   };
02227   EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
02228 }
02229 
02230 namespace {
02231   struct CallBlockRelease : EHScopeStack::Cleanup {
02232     llvm::Value *Addr;
02233     CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
02234 
02235     void Emit(CodeGenFunction &CGF, Flags flags) override {
02236       // Should we be passing FIELD_IS_WEAK here?
02237       CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
02238     }
02239   };
02240 }
02241 
02242 /// Enter a cleanup to destroy a __block variable.  Note that this
02243 /// cleanup should be a no-op if the variable hasn't left the stack
02244 /// yet; if a cleanup is required for the variable itself, that needs
02245 /// to be done externally.
02246 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
02247   // We don't enter this cleanup if we're in pure-GC mode.
02248   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
02249     return;
02250 
02251   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
02252 }
02253 
02254 /// Adjust the declaration of something from the blocks API.
02255 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
02256                                          llvm::Constant *C) {
02257   if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
02258 
02259   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
02260   if (GV->isDeclaration() && GV->hasExternalLinkage())
02261     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
02262 }
02263 
02264 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
02265   if (BlockObjectDispose)
02266     return BlockObjectDispose;
02267 
02268   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
02269   llvm::FunctionType *fty
02270     = llvm::FunctionType::get(VoidTy, args, false);
02271   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
02272   configureBlocksRuntimeObject(*this, BlockObjectDispose);
02273   return BlockObjectDispose;
02274 }
02275 
02276 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
02277   if (BlockObjectAssign)
02278     return BlockObjectAssign;
02279 
02280   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
02281   llvm::FunctionType *fty
02282     = llvm::FunctionType::get(VoidTy, args, false);
02283   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
02284   configureBlocksRuntimeObject(*this, BlockObjectAssign);
02285   return BlockObjectAssign;
02286 }
02287 
02288 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
02289   if (NSConcreteGlobalBlock)
02290     return NSConcreteGlobalBlock;
02291 
02292   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
02293                                                 Int8PtrTy->getPointerTo(),
02294                                                 nullptr);
02295   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
02296   return NSConcreteGlobalBlock;
02297 }
02298 
02299 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
02300   if (NSConcreteStackBlock)
02301     return NSConcreteStackBlock;
02302 
02303   NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
02304                                                Int8PtrTy->getPointerTo(),
02305                                                nullptr);
02306   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
02307   return NSConcreteStackBlock;  
02308 }