clang API Documentation

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