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