1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit blocks.
12 //===----------------------------------------------------------------------===//
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/CallSite.h"
27 using namespace clang;
28 using namespace CodeGen;
30 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
32 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33 StructureType(0), Block(block),
36 // Skip asm prefix, if any. 'name' is usually taken directly from
37 // the mangled name of the enclosing function.
38 if (!name.empty() && name[0] == '\01')
39 name = name.substr(1);
42 // Anchor the vtable to this translation unit.
43 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
45 /// Build the given block as a global block.
46 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo,
48 llvm::Constant *blockFn);
50 /// Build the helper function to copy a block.
51 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo) {
53 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
56 /// Build the helper function to dipose of a block.
57 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
62 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
64 /// meta-data and contains stationary information about the block literal.
65 /// Its definition will have 4 (or optinally 6) words.
66 /// struct Block_descriptor {
67 /// unsigned long reserved;
68 /// unsigned long size; // size of Block_literal metadata in bytes.
69 /// void *copy_func_helper_decl; // optional copy helper.
70 /// void *destroy_func_decl; // optioanl destructor helper.
71 /// void *block_method_encoding_address;//@encode for block literal signature.
72 /// void *block_layout_info; // encoding of captured block variables.
74 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
75 const CGBlockInfo &blockInfo) {
76 ASTContext &C = CGM.getContext();
78 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
79 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
81 SmallVector<llvm::Constant*, 6> elements;
84 elements.push_back(llvm::ConstantInt::get(ulong, 0));
87 // FIXME: What is the right way to say this doesn't fit? We should give
88 // a user diagnostic in that case. Better fix would be to change the
90 elements.push_back(llvm::ConstantInt::get(ulong,
91 blockInfo.BlockSize.getQuantity()));
93 // Optional copy/dispose helpers.
94 if (blockInfo.NeedsCopyDispose) {
95 // copy_func_helper_decl
96 elements.push_back(buildCopyHelper(CGM, blockInfo));
99 elements.push_back(buildDisposeHelper(CGM, blockInfo));
102 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
103 std::string typeAtEncoding =
104 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
105 elements.push_back(llvm::ConstantExpr::getBitCast(
106 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
109 if (C.getLangOpts().ObjC1) {
110 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
111 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
113 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
116 elements.push_back(llvm::Constant::getNullValue(i8p));
118 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
120 llvm::GlobalVariable *global =
121 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
122 llvm::GlobalValue::InternalLinkage,
123 init, "__block_descriptor_tmp");
125 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
129 Purely notional variadic template describing the layout of a block.
131 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
132 struct Block_literal {
133 /// Initialized to one of:
134 /// extern void *_NSConcreteStackBlock[];
135 /// extern void *_NSConcreteGlobalBlock[];
137 /// In theory, we could start one off malloc'ed by setting
138 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
140 /// extern void *_NSConcreteMallocBlock[];
141 struct objc_class *isa;
143 /// These are the flags (with corresponding bit number) that the
144 /// compiler is actually supposed to know about.
145 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
146 /// descriptor provides copy and dispose helper functions
147 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
148 /// object with a nontrivial destructor or copy constructor
149 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
151 /// 29. BLOCK_USE_STRET - indicates that the block function
152 /// uses stret, which objc_msgSend needs to know about
153 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
154 /// @encoded signature string
155 /// And we're not supposed to manipulate these:
156 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
157 /// to malloc'ed memory
158 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
159 /// to GC-allocated memory
160 /// Additionally, the bottom 16 bits are a reference count which
161 /// should be zero on the stack.
164 /// Reserved; should be zero-initialized.
167 /// Function pointer generated from block literal.
168 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
170 /// Block description metadata generated from block literal.
171 struct Block_descriptor *block_descriptor;
173 /// Captured values follow.
174 _CapturesTypes captures...;
178 /// The number of fields in a block header.
179 const unsigned BlockHeaderSize = 5;
182 /// A chunk of data that we actually have to capture in the block.
183 struct BlockLayoutChunk {
186 Qualifiers::ObjCLifetime Lifetime;
187 const BlockDecl::Capture *Capture; // null for 'this'
190 BlockLayoutChunk(CharUnits align, CharUnits size,
191 Qualifiers::ObjCLifetime lifetime,
192 const BlockDecl::Capture *capture,
194 : Alignment(align), Size(size), Lifetime(lifetime),
195 Capture(capture), Type(type) {}
197 /// Tell the block info that this chunk has the given field index.
198 void setIndex(CGBlockInfo &info, unsigned index) {
200 info.CXXThisIndex = index;
202 info.Captures[Capture->getVariable()]
203 = CGBlockInfo::Capture::makeIndex(index);
207 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
208 /// all __weak together. Preserve descending alignment in all situations.
209 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
210 CharUnits LeftValue, RightValue;
211 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
212 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
214 if (left.Lifetime == Qualifiers::OCL_Strong &&
215 left.Alignment >= right.Alignment)
216 LeftValue = CharUnits::fromQuantity(64);
217 else if (LeftByref && left.Alignment >= right.Alignment)
218 LeftValue = CharUnits::fromQuantity(32);
219 else if (left.Lifetime == Qualifiers::OCL_Weak &&
220 left.Alignment >= right.Alignment)
221 LeftValue = CharUnits::fromQuantity(16);
223 LeftValue = left.Alignment;
224 if (right.Lifetime == Qualifiers::OCL_Strong &&
225 right.Alignment >= left.Alignment)
226 RightValue = CharUnits::fromQuantity(64);
227 else if (RightByref && right.Alignment >= left.Alignment)
228 RightValue = CharUnits::fromQuantity(32);
229 else if (right.Lifetime == Qualifiers::OCL_Weak &&
230 right.Alignment >= left.Alignment)
231 RightValue = CharUnits::fromQuantity(16);
233 RightValue = right.Alignment;
235 return LeftValue > RightValue;
239 /// Determines if the given type is safe for constant capture in C++.
240 static bool isSafeForCXXConstantCapture(QualType type) {
241 const RecordType *recordType =
242 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
244 // Only records can be unsafe.
245 if (!recordType) return true;
247 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
249 // Maintain semantics for classes with non-trivial dtors or copy ctors.
250 if (!record->hasTrivialDestructor()) return false;
251 if (record->hasNonTrivialCopyConstructor()) return false;
253 // Otherwise, we just have to make sure there aren't any mutable
254 // fields that might have changed since initialization.
255 return !record->hasMutableFields();
258 /// It is illegal to modify a const object after initialization.
259 /// Therefore, if a const object has a constant initializer, we don't
260 /// actually need to keep storage for it in the block; we'll just
261 /// rematerialize it at the start of the block function. This is
262 /// acceptable because we make no promises about address stability of
263 /// captured variables.
264 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
265 CodeGenFunction *CGF,
266 const VarDecl *var) {
267 QualType type = var->getType();
269 // We can only do this if the variable is const.
270 if (!type.isConstQualified()) return 0;
272 // Furthermore, in C++ we have to worry about mutable fields:
273 // C++ [dcl.type.cv]p4:
274 // Except that any class member declared mutable can be
275 // modified, any attempt to modify a const object during its
276 // lifetime results in undefined behavior.
277 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
280 // If the variable doesn't have any initializer (shouldn't this be
281 // invalid?), it's not clear what we should do. Maybe capture as
283 const Expr *init = var->getInit();
286 return CGM.EmitConstantInit(*var, CGF);
289 /// Get the low bit of a nonzero character count. This is the
290 /// alignment of the nth byte if the 0th byte is universally aligned.
291 static CharUnits getLowBit(CharUnits v) {
292 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
295 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
296 SmallVectorImpl<llvm::Type*> &elementTypes) {
297 ASTContext &C = CGM.getContext();
299 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
300 CharUnits ptrSize, ptrAlign, intSize, intAlign;
301 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
302 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
304 // Are there crazy embedded platforms where this isn't true?
305 assert(intSize <= ptrSize && "layout assumptions horribly violated");
307 CharUnits headerSize = ptrSize;
308 if (2 * intSize < ptrAlign) headerSize += ptrSize;
309 else headerSize += 2 * intSize;
310 headerSize += 2 * ptrSize;
312 info.BlockAlign = ptrAlign;
313 info.BlockSize = headerSize;
315 assert(elementTypes.empty());
316 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
317 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
318 elementTypes.push_back(i8p);
319 elementTypes.push_back(intTy);
320 elementTypes.push_back(intTy);
321 elementTypes.push_back(i8p);
322 elementTypes.push_back(CGM.getBlockDescriptorType());
324 assert(elementTypes.size() == BlockHeaderSize);
327 /// Compute the layout of the given block. Attempts to lay the block
328 /// out with minimal space requirements.
329 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
331 ASTContext &C = CGM.getContext();
332 const BlockDecl *block = info.getBlockDecl();
334 SmallVector<llvm::Type*, 8> elementTypes;
335 initializeForBlockHeader(CGM, info, elementTypes);
337 if (!block->hasCaptures()) {
339 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
340 info.CanBeGlobal = true;
343 else if (C.getLangOpts().ObjC1 &&
344 CGM.getLangOpts().getGC() == LangOptions::NonGC)
345 info.HasCapturedVariableLayout = true;
347 // Collect the layout chunks.
348 SmallVector<BlockLayoutChunk, 16> layout;
349 layout.reserve(block->capturesCXXThis() +
350 (block->capture_end() - block->capture_begin()));
352 CharUnits maxFieldAlign;
355 if (block->capturesCXXThis()) {
356 const DeclContext *DC = block->getDeclContext();
357 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
360 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
361 thisType = C.getPointerType(C.getRecordType(RD));
363 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
365 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
366 std::pair<CharUnits,CharUnits> tinfo
367 = CGM.getContext().getTypeInfoInChars(thisType);
368 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
370 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
371 Qualifiers::OCL_None,
375 // Next, all the block captures.
376 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
377 ce = block->capture_end(); ci != ce; ++ci) {
378 const VarDecl *variable = ci->getVariable();
381 // We have to copy/dispose of the __block reference.
382 info.NeedsCopyDispose = true;
384 // Just use void* instead of a pointer to the byref type.
385 QualType byRefPtrTy = C.VoidPtrTy;
387 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
388 std::pair<CharUnits,CharUnits> tinfo
389 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
390 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
392 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
393 Qualifiers::OCL_None,
398 // Otherwise, build a layout chunk with the size and alignment of
400 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
401 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
405 // If we have a lifetime qualifier, honor it for capture purposes.
406 // That includes *not* copying it if it's __unsafe_unretained.
407 Qualifiers::ObjCLifetime lifetime =
408 variable->getType().getObjCLifetime();
411 case Qualifiers::OCL_None: llvm_unreachable("impossible");
412 case Qualifiers::OCL_ExplicitNone:
413 case Qualifiers::OCL_Autoreleasing:
416 case Qualifiers::OCL_Strong:
417 case Qualifiers::OCL_Weak:
418 info.NeedsCopyDispose = true;
421 // Block pointers require copy/dispose. So do Objective-C pointers.
422 } else if (variable->getType()->isObjCRetainableType()) {
423 info.NeedsCopyDispose = true;
424 // used for mrr below.
425 lifetime = Qualifiers::OCL_Strong;
427 // So do types that require non-trivial copy construction.
428 } else if (ci->hasCopyExpr()) {
429 info.NeedsCopyDispose = true;
430 info.HasCXXObject = true;
432 // And so do types with destructors.
433 } else if (CGM.getLangOpts().CPlusPlus) {
434 if (const CXXRecordDecl *record =
435 variable->getType()->getAsCXXRecordDecl()) {
436 if (!record->hasTrivialDestructor()) {
437 info.HasCXXObject = true;
438 info.NeedsCopyDispose = true;
443 QualType VT = variable->getType();
444 CharUnits size = C.getTypeSizeInChars(VT);
445 CharUnits align = C.getDeclAlign(variable);
447 maxFieldAlign = std::max(maxFieldAlign, align);
449 llvm::Type *llvmType =
450 CGM.getTypes().ConvertTypeForMem(VT);
452 layout.push_back(BlockLayoutChunk(align, size, lifetime, &*ci, llvmType));
455 // If that was everything, we're done here.
456 if (layout.empty()) {
458 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
459 info.CanBeGlobal = true;
463 // Sort the layout by alignment. We have to use a stable sort here
464 // to get reproducible results. There should probably be an
465 // llvm::array_pod_stable_sort.
466 std::stable_sort(layout.begin(), layout.end());
468 // Needed for blocks layout info.
469 info.BlockHeaderForcedGapOffset = info.BlockSize;
470 info.BlockHeaderForcedGapSize = CharUnits::Zero();
472 CharUnits &blockSize = info.BlockSize;
473 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
475 // Assuming that the first byte in the header is maximally aligned,
476 // get the alignment of the first byte following the header.
477 CharUnits endAlign = getLowBit(blockSize);
479 // If the end of the header isn't satisfactorily aligned for the
480 // maximum thing, look for things that are okay with the header-end
481 // alignment, and keep appending them until we get something that's
482 // aligned right. This algorithm is only guaranteed optimal if
483 // that condition is satisfied at some point; otherwise we can get
485 // header // next byte has alignment 4
486 // something_with_size_5; // next byte has alignment 1
487 // something_with_alignment_8;
488 // which has 7 bytes of padding, as opposed to the naive solution
489 // which might have less (?).
490 if (endAlign < maxFieldAlign) {
491 SmallVectorImpl<BlockLayoutChunk>::iterator
492 li = layout.begin() + 1, le = layout.end();
494 // Look for something that the header end is already
495 // satisfactorily aligned for.
496 for (; li != le && endAlign < li->Alignment; ++li)
499 // If we found something that's naturally aligned for the end of
500 // the header, keep adding things...
502 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
503 for (; li != le; ++li) {
504 assert(endAlign >= li->Alignment);
506 li->setIndex(info, elementTypes.size());
507 elementTypes.push_back(li->Type);
508 blockSize += li->Size;
509 endAlign = getLowBit(blockSize);
511 // ...until we get to the alignment of the maximum field.
512 if (endAlign >= maxFieldAlign) {
514 // No user field was appended. So, a gap was added.
515 // Save total gap size for use in block layout bit map.
516 info.BlockHeaderForcedGapSize = li->Size;
521 // Don't re-append everything we just appended.
522 layout.erase(first, li);
526 assert(endAlign == getLowBit(blockSize));
528 // At this point, we just have to add padding if the end align still
529 // isn't aligned right.
530 if (endAlign < maxFieldAlign) {
531 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
532 CharUnits padding = newBlockSize - blockSize;
534 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
535 padding.getQuantity()));
536 blockSize = newBlockSize;
537 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
540 assert(endAlign >= maxFieldAlign);
541 assert(endAlign == getLowBit(blockSize));
542 // Slam everything else on now. This works because they have
543 // strictly decreasing alignment and we expect that size is always a
544 // multiple of alignment.
545 for (SmallVectorImpl<BlockLayoutChunk>::iterator
546 li = layout.begin(), le = layout.end(); li != le; ++li) {
547 assert(endAlign >= li->Alignment);
548 li->setIndex(info, elementTypes.size());
549 elementTypes.push_back(li->Type);
550 blockSize += li->Size;
551 endAlign = getLowBit(blockSize);
555 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
558 /// Enter the scope of a block. This should be run at the entrance to
559 /// a full-expression so that the block's cleanups are pushed at the
560 /// right place in the stack.
561 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
562 assert(CGF.HaveInsertPoint());
564 // Allocate the block info and place it at the head of the list.
565 CGBlockInfo &blockInfo =
566 *new CGBlockInfo(block, CGF.CurFn->getName());
567 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
568 CGF.FirstBlockInfo = &blockInfo;
570 // Compute information about the layout, etc., of this block,
571 // pushing cleanups as necessary.
572 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
574 // Nothing else to do if it can be global.
575 if (blockInfo.CanBeGlobal) return;
577 // Make the allocation for the block.
579 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
580 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
582 // If there are cleanups to emit, enter them (but inactive).
583 if (!blockInfo.NeedsCopyDispose) return;
585 // Walk through the captures (in order) and find the ones not
586 // captured by constant.
587 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
588 ce = block->capture_end(); ci != ce; ++ci) {
589 // Ignore __block captures; there's nothing special in the
590 // on-stack block that we need to do for them.
591 if (ci->isByRef()) continue;
593 // Ignore variables that are constant-captured.
594 const VarDecl *variable = ci->getVariable();
595 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
596 if (capture.isConstant()) continue;
598 // Ignore objects that aren't destructed.
599 QualType::DestructionKind dtorKind =
600 variable->getType().isDestructedType();
601 if (dtorKind == QualType::DK_none) continue;
603 CodeGenFunction::Destroyer *destroyer;
605 // Block captures count as local values and have imprecise semantics.
606 // They also can't be arrays, so need to worry about that.
607 if (dtorKind == QualType::DK_objc_strong_lifetime) {
608 destroyer = CodeGenFunction::destroyARCStrongImprecise;
610 destroyer = CGF.getDestroyer(dtorKind);
613 // GEP down to the address.
614 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
617 // We can use that GEP as the dominating IP.
618 if (!blockInfo.DominatingIP)
619 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
621 CleanupKind cleanupKind = InactiveNormalCleanup;
622 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623 if (useArrayEHCleanup)
624 cleanupKind = InactiveNormalAndEHCleanup;
626 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
627 destroyer, useArrayEHCleanup);
629 // Remember where that cleanup was.
630 capture.setCleanup(CGF.EHStack.stable_begin());
634 /// Enter a full-expression with a non-trivial number of objects to
635 /// clean up. This is in this file because, at the moment, the only
636 /// kind of cleanup object is a BlockDecl*.
637 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
638 assert(E->getNumObjects() != 0);
639 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
640 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
641 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642 enterBlockScope(*this, *i);
646 /// Find the layout for the given block in a linked list and remove it.
647 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
648 const BlockDecl *block) {
650 assert(head && *head);
651 CGBlockInfo *cur = *head;
653 // If this is the block we're looking for, splice it out of the list.
654 if (cur->getBlockDecl() == block) {
655 *head = cur->NextBlockInfo;
659 head = &cur->NextBlockInfo;
663 /// Destroy a chain of block layouts.
664 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
665 assert(head && "destroying an empty chain");
667 CGBlockInfo *cur = head;
668 head = cur->NextBlockInfo;
673 /// Emit a block literal expression in the current function.
674 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
675 // If the block has no captures, we won't have a pre-computed
677 if (!blockExpr->getBlockDecl()->hasCaptures()) {
678 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
679 computeBlockInfo(CGM, this, blockInfo);
680 blockInfo.BlockExpression = blockExpr;
681 return EmitBlockLiteral(blockInfo);
684 // Find the block info for this block and take ownership of it.
685 OwningPtr<CGBlockInfo> blockInfo;
686 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687 blockExpr->getBlockDecl()));
689 blockInfo->BlockExpression = blockExpr;
690 return EmitBlockLiteral(*blockInfo);
693 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
694 // Using the computed layout, generate the actual block function.
695 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
696 llvm::Constant *blockFn
697 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
700 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
702 // If there is nothing to capture, we can emit this as a global block.
703 if (blockInfo.CanBeGlobal)
704 return buildGlobalBlock(CGM, blockInfo, blockFn);
706 // Otherwise, we have to emit this as a local block.
708 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
709 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
711 // Build the block descriptor.
712 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
714 llvm::AllocaInst *blockAddr = blockInfo.Address;
715 assert(blockAddr && "block has no address!");
717 // Compute the initial on-stack block flags.
718 BlockFlags flags = BLOCK_HAS_SIGNATURE;
719 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
720 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
722 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
724 // Initialize the block literal.
725 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
726 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
727 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
728 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
729 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
730 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
732 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
733 "block.descriptor"));
735 // Finally, capture all the values into the block.
736 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
739 if (blockDecl->capturesCXXThis()) {
740 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
741 blockInfo.CXXThisIndex,
742 "block.captured-this.addr");
743 Builder.CreateStore(LoadCXXThis(), addr);
746 // Next, captured variables.
747 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
748 ce = blockDecl->capture_end(); ci != ce; ++ci) {
749 const VarDecl *variable = ci->getVariable();
750 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
752 // Ignore constant captures.
753 if (capture.isConstant()) continue;
755 QualType type = variable->getType();
756 CharUnits align = getContext().getDeclAlign(variable);
758 // This will be a [[type]]*, except that a byref entry will just be
760 llvm::Value *blockField =
761 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
764 // Compute the address of the thing we're going to move into the
767 if (BlockInfo && ci->isNested()) {
768 // We need to use the capture from the enclosing block.
769 const CGBlockInfo::Capture &enclosingCapture =
770 BlockInfo->getCapture(variable);
772 // This is a [[type]]*, except that a byref entry wil just be an i8**.
773 src = Builder.CreateStructGEP(LoadBlockStruct(),
774 enclosingCapture.getIndex(),
775 "block.capture.addr");
776 } else if (blockDecl->isConversionFromLambda()) {
777 // The lambda capture in a lambda's conversion-to-block-pointer is
778 // special; we'll simply emit it directly.
781 // Just look it up in the locals map, which will give us back a
782 // [[type]]*. If that doesn't work, do the more elaborate DRE
784 src = LocalDeclMap.lookup(variable);
786 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
787 /*refersToEnclosing*/ ci->isNested(), type,
788 VK_LValue, SourceLocation());
789 src = EmitDeclRefLValue(&declRef).getAddress();
793 // For byrefs, we just write the pointer to the byref struct into
794 // the block field. There's no need to chase the forwarding
795 // pointer at this point, since we're building something that will
796 // live a shorter life than the stack byref anyway.
798 // Get a void* that points to the byref struct.
800 src = Builder.CreateAlignedLoad(src, align.getQuantity(),
803 src = Builder.CreateBitCast(src, VoidPtrTy);
805 // Write that void* into the capture field.
806 Builder.CreateAlignedStore(src, blockField, align.getQuantity());
808 // If we have a copy constructor, evaluate that into the block field.
809 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
810 if (blockDecl->isConversionFromLambda()) {
811 // If we have a lambda conversion, emit the expression
812 // directly into the block instead.
814 AggValueSlot::forAddr(blockField, align, Qualifiers(),
815 AggValueSlot::IsDestructed,
816 AggValueSlot::DoesNotNeedGCBarriers,
817 AggValueSlot::IsNotAliased);
818 EmitAggExpr(copyExpr, Slot);
820 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
823 // If it's a reference variable, copy the reference into the block field.
824 } else if (type->isReferenceType()) {
826 Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
827 Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
829 // If this is an ARC __strong block-pointer variable, don't do a
832 // TODO: this can be generalized into the normal initialization logic:
833 // we should never need to do a block-copy when initializing a local
834 // variable, because the local variable's lifetime should be strictly
835 // contained within the stack block's.
836 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
837 type->isBlockPointerType()) {
838 // Load the block and do a simple retain.
839 LValue srcLV = MakeAddrLValue(src, type, align);
840 llvm::Value *value = EmitLoadOfScalar(srcLV);
841 value = EmitARCRetainNonBlock(value);
843 // Do a primitive store to the block field.
844 LValue destLV = MakeAddrLValue(blockField, type, align);
845 EmitStoreOfScalar(value, destLV, /*init*/ true);
847 // Otherwise, fake up a POD copy into the block field.
849 // Fake up a new variable so that EmitScalarInit doesn't think
850 // we're referring to the variable in its own initializer.
851 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
854 // We use one of these or the other depending on whether the
855 // reference is nested.
856 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
857 /*refersToEnclosing*/ ci->isNested(), type,
858 VK_LValue, SourceLocation());
860 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
861 &declRef, VK_RValue);
862 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
863 MakeAddrLValue(blockField, type, align),
864 /*captured by init*/ false);
867 // Activate the cleanup if layout pushed one.
868 if (!ci->isByRef()) {
869 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
870 if (cleanup.isValid())
871 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
875 // Cast to the converted block-pointer type, which happens (somewhat
876 // unfortunately) to be a pointer to function type.
877 llvm::Value *result =
878 Builder.CreateBitCast(blockAddr,
879 ConvertType(blockInfo.getBlockExpr()->getType()));
885 llvm::Type *CodeGenModule::getBlockDescriptorType() {
886 if (BlockDescriptorType)
887 return BlockDescriptorType;
889 llvm::Type *UnsignedLongTy =
890 getTypes().ConvertType(getContext().UnsignedLongTy);
892 // struct __block_descriptor {
893 // unsigned long reserved;
894 // unsigned long block_size;
896 // // later, the following will be added
899 // void (*copyHelper)();
900 // void (*copyHelper)();
901 // } helpers; // !!! optional
903 // const char *signature; // the block signature
904 // const char *layout; // reserved
906 BlockDescriptorType =
907 llvm::StructType::create("struct.__block_descriptor",
908 UnsignedLongTy, UnsignedLongTy, NULL);
910 // Now form a pointer to that.
911 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
912 return BlockDescriptorType;
915 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
916 if (GenericBlockLiteralType)
917 return GenericBlockLiteralType;
919 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
921 // struct __block_literal_generic {
925 // void (*__invoke)(void *);
926 // struct __block_descriptor *__descriptor;
928 GenericBlockLiteralType =
929 llvm::StructType::create("struct.__block_literal_generic",
930 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
931 BlockDescPtrTy, NULL);
933 return GenericBlockLiteralType;
937 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
938 ReturnValueSlot ReturnValue) {
939 const BlockPointerType *BPT =
940 E->getCallee()->getType()->getAs<BlockPointerType>();
942 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
944 // Get a pointer to the generic block literal.
945 llvm::Type *BlockLiteralTy =
946 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
948 // Bitcast the callee to a block literal.
949 llvm::Value *BlockLiteral =
950 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
952 // Get the function pointer from the literal.
953 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
955 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
957 // Add the block literal.
959 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
961 QualType FnType = BPT->getPointeeType();
963 // And the rest of the arguments.
964 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
965 E->arg_begin(), E->arg_end());
967 // Load the function.
968 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
970 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
971 const CGFunctionInfo &FnInfo =
972 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
974 // Cast the function pointer to the right type.
975 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
977 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
978 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
980 // And call the block.
981 return EmitCall(FnInfo, Func, ReturnValue, Args);
984 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
986 assert(BlockInfo && "evaluating block ref without block information?");
987 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
989 // Handle constant captures.
990 if (capture.isConstant()) return LocalDeclMap[variable];
993 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
994 "block.capture.addr");
997 // addr should be a void** right now. Load, then cast the result
1000 addr = Builder.CreateLoad(addr);
1001 llvm::PointerType *byrefPointerType
1002 = llvm::PointerType::get(BuildByRefType(variable), 0);
1003 addr = Builder.CreateBitCast(addr, byrefPointerType,
1006 // Follow the forwarding pointer.
1007 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
1008 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
1010 // Cast back to byref* and GEP over to the actual object.
1011 addr = Builder.CreateBitCast(addr, byrefPointerType);
1012 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
1013 variable->getNameAsString());
1016 if (variable->getType()->isReferenceType())
1017 addr = Builder.CreateLoad(addr, "ref.tmp");
1023 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1025 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1026 blockInfo.BlockExpression = blockExpr;
1028 // Compute information about the layout, etc., of this block.
1029 computeBlockInfo(*this, 0, blockInfo);
1031 // Using that metadata, generate the actual block function.
1032 llvm::Constant *blockFn;
1034 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
1035 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1040 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1042 return buildGlobalBlock(*this, blockInfo, blockFn);
1045 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1046 const CGBlockInfo &blockInfo,
1047 llvm::Constant *blockFn) {
1048 assert(blockInfo.CanBeGlobal);
1050 // Generate the constants for the block literal initializer.
1051 llvm::Constant *fields[BlockHeaderSize];
1054 fields[0] = CGM.getNSConcreteGlobalBlock();
1057 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1058 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1060 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1063 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1066 fields[3] = blockFn;
1069 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1071 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1073 llvm::GlobalVariable *literal =
1074 new llvm::GlobalVariable(CGM.getModule(),
1077 llvm::GlobalVariable::InternalLinkage,
1079 "__block_literal_global");
1080 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1082 // Return a constant of the appropriately-casted type.
1083 llvm::Type *requiredType =
1084 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1085 return llvm::ConstantExpr::getBitCast(literal, requiredType);
1089 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1090 const CGBlockInfo &blockInfo,
1091 const DeclMapTy &ldm,
1092 bool IsLambdaConversionToBlock) {
1093 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1095 // Check if we should generate debug info for this block function.
1096 maybeInitializeDebugInfo();
1099 BlockInfo = &blockInfo;
1101 // Arrange for local static and local extern declarations to appear
1102 // to be local to this function as well, in case they're directly
1103 // referenced in a block.
1104 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1105 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1106 if (var && !var->hasLocalStorage())
1107 LocalDeclMap[var] = i->second;
1110 // Begin building the function declaration.
1112 // Build the argument list.
1113 FunctionArgList args;
1115 // The first argument is the block pointer. Just take it as a void*
1116 // and cast it later.
1117 QualType selfTy = getContext().VoidPtrTy;
1118 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1120 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1121 SourceLocation(), II, selfTy);
1122 args.push_back(&selfDecl);
1124 // Now add the rest of the parameters.
1125 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1126 e = blockDecl->param_end(); i != e; ++i)
1129 // Create the function declaration.
1130 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1131 const CGFunctionInfo &fnInfo =
1132 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1133 fnType->getExtInfo(),
1134 fnType->isVariadic());
1135 if (CGM.ReturnTypeUsesSRet(fnInfo))
1136 blockInfo.UsesStret = true;
1138 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1141 CGM.getBlockMangledName(GD, name, blockDecl);
1142 llvm::Function *fn =
1143 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1144 name.getString(), &CGM.getModule());
1145 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1147 // Begin generating the function.
1148 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
1149 blockInfo.getBlockExpr()->getBody()->getLocStart());
1151 // Okay. Undo some of what StartFunction did.
1153 // Pull the 'self' reference out of the local decl map.
1154 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1155 LocalDeclMap.erase(&selfDecl);
1156 BlockPointer = Builder.CreateBitCast(blockAddr,
1157 blockInfo.StructureType->getPointerTo(),
1159 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1160 // won't delete the dbg.declare intrinsics for captured variables.
1161 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1162 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1163 // Allocate a stack slot for it, so we can point the debugger to it
1164 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1166 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1167 Alloca->setAlignment(Align);
1168 // Set the DebugLocation to empty, so the store is recognized as a
1169 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1170 Builder.DisableDebugLocations();
1171 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1172 Builder.EnableDebugLocations();
1173 BlockPointerDbgLoc = Alloca;
1176 // If we have a C++ 'this' reference, go ahead and force it into
1178 if (blockDecl->capturesCXXThis()) {
1179 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1180 blockInfo.CXXThisIndex,
1181 "block.captured-this");
1182 CXXThisValue = Builder.CreateLoad(addr, "this");
1185 // Also force all the constant captures.
1186 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1187 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1188 const VarDecl *variable = ci->getVariable();
1189 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1190 if (!capture.isConstant()) continue;
1192 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1194 llvm::AllocaInst *alloca =
1195 CreateMemTemp(variable->getType(), "block.captured-const");
1196 alloca->setAlignment(align);
1198 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
1200 LocalDeclMap[variable] = alloca;
1203 // Save a spot to insert the debug information for all the DeclRefExprs.
1204 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1205 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1208 if (IsLambdaConversionToBlock)
1209 EmitLambdaBlockInvokeBody();
1211 EmitStmt(blockDecl->getBody());
1213 // Remember where we were...
1214 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1216 // Go back to the entry.
1218 Builder.SetInsertPoint(entry, entry_ptr);
1220 // Emit debug information for all the DeclRefExprs.
1221 // FIXME: also for 'this'
1222 if (CGDebugInfo *DI = getDebugInfo()) {
1223 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1224 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1225 const VarDecl *variable = ci->getVariable();
1226 DI->EmitLocation(Builder, variable->getLocation());
1228 if (CGM.getCodeGenOpts().getDebugInfo()
1229 >= CodeGenOptions::LimitedDebugInfo) {
1230 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1231 if (capture.isConstant()) {
1232 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1237 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
1238 Builder, blockInfo);
1241 // Recover location if it was changed in the above loop.
1242 DI->EmitLocation(Builder,
1243 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1246 // And resume where we left off.
1248 Builder.ClearInsertionPoint();
1250 Builder.SetInsertPoint(resume);
1252 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1258 notes.push_back(HelperInfo());
1259 HelperInfo ¬e = notes.back();
1260 note.index = capture.getIndex();
1261 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1262 note.cxxbar_import = ci->getCopyExpr();
1264 if (ci->isByRef()) {
1265 note.flag = BLOCK_FIELD_IS_BYREF;
1266 if (type.isObjCGCWeak())
1267 note.flag |= BLOCK_FIELD_IS_WEAK;
1268 } else if (type->isBlockPointerType()) {
1269 note.flag = BLOCK_FIELD_IS_BLOCK;
1271 note.flag = BLOCK_FIELD_IS_OBJECT;
1276 /// Generate the copy-helper function for a block closure object:
1277 /// static void block_copy_helper(block_t *dst, block_t *src);
1278 /// The runtime will have previously initialized 'dst' by doing a
1279 /// bit-copy of 'src'.
1281 /// Note that this copies an entire block closure object to the heap;
1282 /// it should not be confused with a 'byref copy helper', which moves
1283 /// the contents of an individual __block variable to the heap.
1285 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1286 ASTContext &C = getContext();
1288 FunctionArgList args;
1289 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1290 args.push_back(&dstDecl);
1291 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1292 args.push_back(&srcDecl);
1294 const CGFunctionInfo &FI =
1295 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1296 FunctionType::ExtInfo(),
1297 /*variadic*/ false);
1299 // FIXME: it would be nice if these were mergeable with things with
1300 // identical semantics.
1301 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1303 llvm::Function *Fn =
1304 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1305 "__copy_helper_block_", &CGM.getModule());
1308 = &CGM.getContext().Idents.get("__copy_helper_block_");
1310 // Check if we should generate debug info for this block helper function.
1311 maybeInitializeDebugInfo();
1313 FunctionDecl *FD = FunctionDecl::Create(C,
1314 C.getTranslationUnitDecl(),
1316 SourceLocation(), II, C.VoidTy, 0,
1320 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1322 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1324 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1325 src = Builder.CreateLoad(src);
1326 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1328 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1329 dst = Builder.CreateLoad(dst);
1330 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1332 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1334 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1335 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1336 const VarDecl *variable = ci->getVariable();
1337 QualType type = variable->getType();
1339 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1340 if (capture.isConstant()) continue;
1342 const Expr *copyExpr = ci->getCopyExpr();
1343 BlockFieldFlags flags;
1345 bool useARCWeakCopy = false;
1346 bool useARCStrongCopy = false;
1349 assert(!ci->isByRef());
1350 // don't bother computing flags
1352 } else if (ci->isByRef()) {
1353 flags = BLOCK_FIELD_IS_BYREF;
1354 if (type.isObjCGCWeak())
1355 flags |= BLOCK_FIELD_IS_WEAK;
1357 } else if (type->isObjCRetainableType()) {
1358 flags = BLOCK_FIELD_IS_OBJECT;
1359 bool isBlockPointer = type->isBlockPointerType();
1361 flags = BLOCK_FIELD_IS_BLOCK;
1363 // Special rules for ARC captures:
1364 if (getLangOpts().ObjCAutoRefCount) {
1365 Qualifiers qs = type.getQualifiers();
1367 // We need to register __weak direct captures with the runtime.
1368 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1369 useARCWeakCopy = true;
1371 // We need to retain the copied value for __strong direct captures.
1372 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1373 // If it's a block pointer, we have to copy the block and
1374 // assign that to the destination pointer, so we might as
1375 // well use _Block_object_assign. Otherwise we can avoid that.
1376 if (!isBlockPointer)
1377 useARCStrongCopy = true;
1379 // Otherwise the memcpy is fine.
1384 // Non-ARC captures of retainable pointers are strong and
1385 // therefore require a call to _Block_object_assign.
1393 unsigned index = capture.getIndex();
1394 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1395 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
1397 // If there's an explicit copy expression, we do that.
1399 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1400 } else if (useARCWeakCopy) {
1401 EmitARCCopyWeak(dstField, srcField);
1403 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1404 if (useARCStrongCopy) {
1405 // At -O0, store null into the destination field (so that the
1406 // storeStrong doesn't over-release) and then call storeStrong.
1407 // This is a workaround to not having an initStrong call.
1408 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1409 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1410 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1411 Builder.CreateStore(null, dstField);
1412 EmitARCStoreStrongCall(dstField, srcValue, true);
1414 // With optimization enabled, take advantage of the fact that
1415 // the blocks runtime guarantees a memcpy of the block data, and
1416 // just emit a retain of the src field.
1418 EmitARCRetainNonBlock(srcValue);
1420 // We don't need this anymore, so kill it. It's not quite
1421 // worth the annoyance to avoid creating it in the first place.
1422 cast<llvm::Instruction>(dstField)->eraseFromParent();
1425 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1426 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1427 llvm::Value *args[] = {
1428 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1431 bool copyCanThrow = false;
1432 if (ci->isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1433 const Expr *copyExpr =
1434 CGM.getContext().getBlockVarCopyInits(variable);
1436 copyCanThrow = true; // FIXME: reuse the noexcept logic
1441 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1443 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1451 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1454 /// Generate the destroy-helper function for a block closure object:
1455 /// static void block_destroy_helper(block_t *theBlock);
1457 /// Note that this destroys a heap-allocated block closure object;
1458 /// it should not be confused with a 'byref destroy helper', which
1459 /// destroys the heap-allocated contents of an individual __block
1462 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1463 ASTContext &C = getContext();
1465 FunctionArgList args;
1466 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1467 args.push_back(&srcDecl);
1469 const CGFunctionInfo &FI =
1470 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1471 FunctionType::ExtInfo(),
1472 /*variadic*/ false);
1474 // FIXME: We'd like to put these into a mergable by content, with
1475 // internal linkage.
1476 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1478 llvm::Function *Fn =
1479 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1480 "__destroy_helper_block_", &CGM.getModule());
1482 // Check if we should generate debug info for this block destroy function.
1483 maybeInitializeDebugInfo();
1486 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1488 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1490 SourceLocation(), II, C.VoidTy, 0,
1493 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1495 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1497 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1498 src = Builder.CreateLoad(src);
1499 src = Builder.CreateBitCast(src, structPtrTy, "block");
1501 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1503 CodeGenFunction::RunCleanupsScope cleanups(*this);
1505 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1506 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1507 const VarDecl *variable = ci->getVariable();
1508 QualType type = variable->getType();
1510 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1511 if (capture.isConstant()) continue;
1513 BlockFieldFlags flags;
1514 const CXXDestructorDecl *dtor = 0;
1516 bool useARCWeakDestroy = false;
1517 bool useARCStrongDestroy = false;
1519 if (ci->isByRef()) {
1520 flags = BLOCK_FIELD_IS_BYREF;
1521 if (type.isObjCGCWeak())
1522 flags |= BLOCK_FIELD_IS_WEAK;
1523 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1524 if (record->hasTrivialDestructor())
1526 dtor = record->getDestructor();
1527 } else if (type->isObjCRetainableType()) {
1528 flags = BLOCK_FIELD_IS_OBJECT;
1529 if (type->isBlockPointerType())
1530 flags = BLOCK_FIELD_IS_BLOCK;
1532 // Special rules for ARC captures.
1533 if (getLangOpts().ObjCAutoRefCount) {
1534 Qualifiers qs = type.getQualifiers();
1536 // Don't generate special dispose logic for a captured object
1537 // unless it's __strong or __weak.
1538 if (!qs.hasStrongOrWeakObjCLifetime())
1541 // Support __weak direct captures.
1542 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1543 useARCWeakDestroy = true;
1545 // Tools really want us to use objc_storeStrong here.
1547 useARCStrongDestroy = true;
1553 unsigned index = capture.getIndex();
1554 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1556 // If there's an explicit copy expression, we do that.
1558 PushDestructorCleanup(dtor, srcField);
1560 // If this is a __weak capture, emit the release directly.
1561 } else if (useARCWeakDestroy) {
1562 EmitARCDestroyWeak(srcField);
1564 // Destroy strong objects with a call if requested.
1565 } else if (useARCStrongDestroy) {
1566 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1568 // Otherwise we call _Block_object_dispose. It wouldn't be too
1569 // hard to just emit this as a cleanup if we wanted to make sure
1570 // that things were done in reverse.
1572 llvm::Value *value = Builder.CreateLoad(srcField);
1573 value = Builder.CreateBitCast(value, VoidPtrTy);
1574 BuildBlockRelease(value, flags);
1578 cleanups.ForceCleanup();
1582 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1587 /// Emits the copy/dispose helper functions for a __block object of id type.
1588 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1589 BlockFieldFlags Flags;
1592 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1593 : ByrefHelpers(alignment), Flags(flags) {}
1595 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1596 llvm::Value *srcField) {
1597 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1599 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1600 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1602 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1604 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1605 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1607 llvm::Value *args[] = { destField, srcValue, flagsVal };
1608 CGF.EmitNounwindRuntimeCall(fn, args);
1611 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1612 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1613 llvm::Value *value = CGF.Builder.CreateLoad(field);
1615 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1618 void profileImpl(llvm::FoldingSetNodeID &id) const {
1619 id.AddInteger(Flags.getBitMask());
1623 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1624 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1626 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1628 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1629 llvm::Value *srcField) {
1630 CGF.EmitARCMoveWeak(destField, srcField);
1633 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1634 CGF.EmitARCDestroyWeak(field);
1637 void profileImpl(llvm::FoldingSetNodeID &id) const {
1638 // 0 is distinguishable from all pointers and byref flags
1643 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1644 /// that's not of block-pointer type.
1645 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1647 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1649 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1650 llvm::Value *srcField) {
1651 // Do a "move" by copying the value and then zeroing out the old
1654 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1655 value->setAlignment(Alignment.getQuantity());
1658 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1660 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1661 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1662 store->setAlignment(Alignment.getQuantity());
1663 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1664 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1667 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1668 store->setAlignment(Alignment.getQuantity());
1670 store = CGF.Builder.CreateStore(null, srcField);
1671 store->setAlignment(Alignment.getQuantity());
1674 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1675 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1678 void profileImpl(llvm::FoldingSetNodeID &id) const {
1679 // 1 is distinguishable from all pointers and byref flags
1684 /// Emits the copy/dispose helpers for an ARC __block __strong
1685 /// variable that's of block-pointer type.
1686 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1688 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1690 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1691 llvm::Value *srcField) {
1692 // Do the copy with objc_retainBlock; that's all that
1693 // _Block_object_assign would do anyway, and we'd have to pass the
1694 // right arguments to make sure it doesn't get no-op'ed.
1695 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1696 oldValue->setAlignment(Alignment.getQuantity());
1698 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1700 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1701 store->setAlignment(Alignment.getQuantity());
1704 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1705 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1708 void profileImpl(llvm::FoldingSetNodeID &id) const {
1709 // 2 is distinguishable from all pointers and byref flags
1714 /// Emits the copy/dispose helpers for a __block variable with a
1715 /// nontrivial copy constructor or destructor.
1716 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1718 const Expr *CopyExpr;
1721 CXXByrefHelpers(CharUnits alignment, QualType type,
1722 const Expr *copyExpr)
1723 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1725 bool needsCopy() const { return CopyExpr != 0; }
1726 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1727 llvm::Value *srcField) {
1728 if (!CopyExpr) return;
1729 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1732 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1733 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1734 CGF.PushDestructorCleanup(VarType, field);
1735 CGF.PopCleanupBlocks(cleanupDepth);
1738 void profileImpl(llvm::FoldingSetNodeID &id) const {
1739 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1742 } // end anonymous namespace
1744 static llvm::Constant *
1745 generateByrefCopyHelper(CodeGenFunction &CGF,
1746 llvm::StructType &byrefType,
1747 unsigned valueFieldIndex,
1748 CodeGenModule::ByrefHelpers &byrefInfo) {
1749 ASTContext &Context = CGF.getContext();
1751 QualType R = Context.VoidTy;
1753 FunctionArgList args;
1754 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
1755 args.push_back(&dst);
1757 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1758 args.push_back(&src);
1760 const CGFunctionInfo &FI =
1761 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1762 FunctionType::ExtInfo(),
1763 /*variadic*/ false);
1765 CodeGenTypes &Types = CGF.CGM.getTypes();
1766 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1768 // FIXME: We'd like to put these into a mergable by content, with
1769 // internal linkage.
1770 llvm::Function *Fn =
1771 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1772 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1775 = &Context.Idents.get("__Block_byref_object_copy_");
1777 FunctionDecl *FD = FunctionDecl::Create(Context,
1778 Context.getTranslationUnitDecl(),
1780 SourceLocation(), II, R, 0,
1784 // Initialize debug info if necessary.
1785 CGF.maybeInitializeDebugInfo();
1786 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1788 if (byrefInfo.needsCopy()) {
1789 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1792 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1793 destField = CGF.Builder.CreateLoad(destField);
1794 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1795 destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
1798 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1799 srcField = CGF.Builder.CreateLoad(srcField);
1800 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1801 srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
1803 byrefInfo.emitCopy(CGF, destField, srcField);
1806 CGF.FinishFunction();
1808 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1811 /// Build the copy helper for a __block variable.
1812 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1813 llvm::StructType &byrefType,
1814 unsigned byrefValueIndex,
1815 CodeGenModule::ByrefHelpers &info) {
1816 CodeGenFunction CGF(CGM);
1817 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
1820 /// Generate code for a __block variable's dispose helper.
1821 static llvm::Constant *
1822 generateByrefDisposeHelper(CodeGenFunction &CGF,
1823 llvm::StructType &byrefType,
1824 unsigned byrefValueIndex,
1825 CodeGenModule::ByrefHelpers &byrefInfo) {
1826 ASTContext &Context = CGF.getContext();
1827 QualType R = Context.VoidTy;
1829 FunctionArgList args;
1830 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1831 args.push_back(&src);
1833 const CGFunctionInfo &FI =
1834 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1835 FunctionType::ExtInfo(),
1836 /*variadic*/ false);
1838 CodeGenTypes &Types = CGF.CGM.getTypes();
1839 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1841 // FIXME: We'd like to put these into a mergable by content, with
1842 // internal linkage.
1843 llvm::Function *Fn =
1844 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1845 "__Block_byref_object_dispose_",
1846 &CGF.CGM.getModule());
1849 = &Context.Idents.get("__Block_byref_object_dispose_");
1851 FunctionDecl *FD = FunctionDecl::Create(Context,
1852 Context.getTranslationUnitDecl(),
1854 SourceLocation(), II, R, 0,
1857 // Initialize debug info if necessary.
1858 CGF.maybeInitializeDebugInfo();
1859 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1861 if (byrefInfo.needsDispose()) {
1862 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1863 V = CGF.Builder.CreateLoad(V);
1864 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1865 V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
1867 byrefInfo.emitDispose(CGF, V);
1870 CGF.FinishFunction();
1872 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1875 /// Build the dispose helper for a __block variable.
1876 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1877 llvm::StructType &byrefType,
1878 unsigned byrefValueIndex,
1879 CodeGenModule::ByrefHelpers &info) {
1880 CodeGenFunction CGF(CGM);
1881 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
1884 /// Lazily build the copy and dispose helpers for a __block variable
1885 /// with the given information.
1886 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1887 llvm::StructType &byrefTy,
1888 unsigned byrefValueIndex,
1890 // Increase the field's alignment to be at least pointer alignment,
1891 // since the layout of the byref struct will guarantee at least that.
1892 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1893 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1895 llvm::FoldingSetNodeID id;
1896 byrefInfo.Profile(id);
1899 CodeGenModule::ByrefHelpers *node
1900 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1901 if (node) return static_cast<T*>(node);
1903 byrefInfo.CopyHelper =
1904 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1905 byrefInfo.DisposeHelper =
1906 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
1908 T *copy = new (CGM.getContext()) T(byrefInfo);
1909 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1913 /// Build the copy and dispose helpers for the given __block variable
1914 /// emission. Places the helpers in the global cache. Returns null
1915 /// if no helpers are required.
1916 CodeGenModule::ByrefHelpers *
1917 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1918 const AutoVarEmission &emission) {
1919 const VarDecl &var = *emission.Variable;
1920 QualType type = var.getType();
1922 unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1924 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1925 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1926 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1928 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1929 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1932 // Otherwise, if we don't have a retainable type, there's nothing to do.
1933 // that the runtime does extra copies.
1934 if (!type->isObjCRetainableType()) return 0;
1936 Qualifiers qs = type.getQualifiers();
1938 // If we have lifetime, that dominates.
1939 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1940 assert(getLangOpts().ObjCAutoRefCount);
1943 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1945 // These are just bits as far as the runtime is concerned.
1946 case Qualifiers::OCL_ExplicitNone:
1947 case Qualifiers::OCL_Autoreleasing:
1950 // Tell the runtime that this is ARC __weak, called by the
1952 case Qualifiers::OCL_Weak: {
1953 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1954 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1957 // ARC __strong __block variables need to be retained.
1958 case Qualifiers::OCL_Strong:
1959 // Block pointers need to be copied, and there's no direct
1960 // transfer possible.
1961 if (type->isBlockPointerType()) {
1962 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1963 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1965 // Otherwise, we transfer ownership of the retain from the stack
1968 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1969 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1972 llvm_unreachable("fell out of lifetime switch!");
1975 BlockFieldFlags flags;
1976 if (type->isBlockPointerType()) {
1977 flags |= BLOCK_FIELD_IS_BLOCK;
1978 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1979 type->isObjCObjectPointerType()) {
1980 flags |= BLOCK_FIELD_IS_OBJECT;
1985 if (type.isObjCGCWeak())
1986 flags |= BLOCK_FIELD_IS_WEAK;
1988 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1989 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1992 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1993 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1995 return ByRefValueInfo.find(VD)->second.second;
1998 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
2000 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
2001 Loc = Builder.CreateLoad(Loc);
2002 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
2003 V->getNameAsString());
2007 /// BuildByRefType - This routine changes a __block variable declared as T x
2012 /// void *__forwarding;
2013 /// int32_t __flags;
2015 /// void *__copy_helper; // only if needed
2016 /// void *__destroy_helper; // only if needed
2017 /// void *__byref_variable_layout;// only if needed
2018 /// char padding[X]; // only if needed
2022 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2023 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
2027 QualType Ty = D->getType();
2029 SmallVector<llvm::Type *, 8> types;
2031 llvm::StructType *ByRefType =
2032 llvm::StructType::create(getLLVMContext(),
2033 "struct.__block_byref_" + D->getNameAsString());
2036 types.push_back(Int8PtrTy);
2038 // void *__forwarding;
2039 types.push_back(llvm::PointerType::getUnqual(ByRefType));
2042 types.push_back(Int32Ty);
2045 types.push_back(Int32Ty);
2046 // Note that this must match *exactly* the logic in buildByrefHelpers.
2047 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2048 if (HasCopyAndDispose) {
2049 /// void *__copy_helper;
2050 types.push_back(Int8PtrTy);
2052 /// void *__destroy_helper;
2053 types.push_back(Int8PtrTy);
2055 bool HasByrefExtendedLayout = false;
2056 Qualifiers::ObjCLifetime Lifetime;
2057 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2058 HasByrefExtendedLayout)
2059 /// void *__byref_variable_layout;
2060 types.push_back(Int8PtrTy);
2062 bool Packed = false;
2063 CharUnits Align = getContext().getDeclAlign(D);
2065 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
2066 // We have to insert padding.
2068 // The struct above has 2 32-bit integers.
2069 unsigned CurrentOffsetInBytes = 4 * 2;
2071 // And either 2, 3, 4 or 5 pointers.
2072 unsigned noPointers = 2;
2073 if (HasCopyAndDispose)
2075 if (HasByrefExtendedLayout)
2078 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
2080 // Align the offset.
2081 unsigned AlignedOffsetInBytes =
2082 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2084 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2085 if (NumPaddingBytes > 0) {
2086 llvm::Type *Ty = Int8Ty;
2087 // FIXME: We need a sema error for alignment larger than the minimum of
2088 // the maximal stack alignment and the alignment of malloc on the system.
2089 if (NumPaddingBytes > 1)
2090 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2092 types.push_back(Ty);
2094 // We want a packed struct.
2100 types.push_back(ConvertTypeForMem(Ty));
2102 ByRefType->setBody(types, Packed);
2104 Info.first = ByRefType;
2106 Info.second = types.size() - 1;
2111 /// Initialize the structural components of a __block variable, i.e.
2112 /// everything but the actual object.
2113 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2114 // Find the address of the local.
2115 llvm::Value *addr = emission.Address;
2117 // That's an alloca of the byref structure type.
2118 llvm::StructType *byrefType = cast<llvm::StructType>(
2119 cast<llvm::PointerType>(addr->getType())->getElementType());
2121 // Build the byref helpers if necessary. This is null if we don't need any.
2122 CodeGenModule::ByrefHelpers *helpers =
2123 buildByrefHelpers(*byrefType, emission);
2125 const VarDecl &D = *emission.Variable;
2126 QualType type = D.getType();
2128 bool HasByrefExtendedLayout;
2129 Qualifiers::ObjCLifetime ByrefLifetime;
2130 bool ByRefHasLifetime =
2131 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2135 // Initialize the 'isa', which is just 0 or 1.
2137 if (type.isObjCGCWeak())
2139 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2140 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2142 // Store the address of the variable into its own forwarding pointer.
2143 Builder.CreateStore(addr,
2144 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2147 // c) the flags field is set to either 0 if no helper functions are
2148 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2150 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2151 if (ByRefHasLifetime) {
2152 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2153 else switch (ByrefLifetime) {
2154 case Qualifiers::OCL_Strong:
2155 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2157 case Qualifiers::OCL_Weak:
2158 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2160 case Qualifiers::OCL_ExplicitNone:
2161 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2163 case Qualifiers::OCL_None:
2164 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2165 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2170 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2171 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2172 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2173 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2174 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2175 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2176 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2177 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2178 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2179 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2180 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2181 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2182 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2183 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2184 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2185 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2191 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2192 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2194 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2195 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2196 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2199 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
2200 Builder.CreateStore(helpers->CopyHelper, copy_helper);
2202 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
2203 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
2205 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2206 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2207 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2209 // cast destination to pointer to source type.
2210 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2211 DesTy = DesTy->getPointerTo();
2212 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2213 Builder.CreateStore(ByrefLayoutInfo, BC);
2217 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2218 llvm::Value *F = CGM.getBlockObjectDispose();
2219 llvm::Value *args[] = {
2220 Builder.CreateBitCast(V, Int8PtrTy),
2221 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2223 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2227 struct CallBlockRelease : EHScopeStack::Cleanup {
2229 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2231 void Emit(CodeGenFunction &CGF, Flags flags) {
2232 // Should we be passing FIELD_IS_WEAK here?
2233 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2238 /// Enter a cleanup to destroy a __block variable. Note that this
2239 /// cleanup should be a no-op if the variable hasn't left the stack
2240 /// yet; if a cleanup is required for the variable itself, that needs
2241 /// to be done externally.
2242 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2243 // We don't enter this cleanup if we're in pure-GC mode.
2244 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2247 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2250 /// Adjust the declaration of something from the blocks API.
2251 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2252 llvm::Constant *C) {
2253 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2255 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2256 if (GV->isDeclaration() &&
2257 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2258 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2261 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2262 if (BlockObjectDispose)
2263 return BlockObjectDispose;
2265 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2266 llvm::FunctionType *fty
2267 = llvm::FunctionType::get(VoidTy, args, false);
2268 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2269 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2270 return BlockObjectDispose;
2273 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2274 if (BlockObjectAssign)
2275 return BlockObjectAssign;
2277 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2278 llvm::FunctionType *fty
2279 = llvm::FunctionType::get(VoidTy, args, false);
2280 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2281 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2282 return BlockObjectAssign;
2285 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2286 if (NSConcreteGlobalBlock)
2287 return NSConcreteGlobalBlock;
2289 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2290 Int8PtrTy->getPointerTo(), 0);
2291 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2292 return NSConcreteGlobalBlock;
2295 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2296 if (NSConcreteStackBlock)
2297 return NSConcreteStackBlock;
2299 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2300 Int8PtrTy->getPointerTo(), 0);
2301 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2302 return NSConcreteStackBlock;