1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
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 "ConstantBuilder.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Module.h"
28 using namespace clang;
29 using namespace CodeGen;
31 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
32 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
33 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
34 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
35 DominatingIP(nullptr) {
37 // Skip asm prefix, if any. 'name' is usually taken directly from
38 // the mangled name of the enclosing function.
39 if (!name.empty() && name[0] == '\01')
40 name = name.substr(1);
43 // Anchor the vtable to this translation unit.
44 BlockByrefHelpers::~BlockByrefHelpers() {}
46 /// Build the given block as a global block.
47 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
48 const CGBlockInfo &blockInfo,
49 llvm::Constant *blockFn);
51 /// Build the helper function to copy a block.
52 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
57 /// Build the helper function to dispose of a block.
58 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
63 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
64 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
65 /// meta-data and contains stationary information about the block literal.
66 /// Its definition will have 4 (or optinally 6) words.
68 /// struct Block_descriptor {
69 /// unsigned long reserved;
70 /// unsigned long size; // size of Block_literal metadata in bytes.
71 /// void *copy_func_helper_decl; // optional copy helper.
72 /// void *destroy_func_decl; // optioanl destructor helper.
73 /// void *block_method_encoding_address; // @encode for block literal signature.
74 /// void *block_layout_info; // encoding of captured block variables.
77 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
78 const CGBlockInfo &blockInfo) {
79 ASTContext &C = CGM.getContext();
81 llvm::IntegerType *ulong =
82 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
83 llvm::PointerType *i8p = nullptr;
84 if (CGM.getLangOpts().OpenCL)
86 llvm::Type::getInt8PtrTy(
87 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
91 ConstantInitBuilder builder(CGM);
92 auto elements = builder.beginStruct();
95 elements.addInt(ulong, 0);
98 // FIXME: What is the right way to say this doesn't fit? We should give
99 // a user diagnostic in that case. Better fix would be to change the
101 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
103 // Optional copy/dispose helpers.
104 if (blockInfo.NeedsCopyDispose) {
105 // copy_func_helper_decl
106 elements.add(buildCopyHelper(CGM, blockInfo));
109 elements.add(buildDisposeHelper(CGM, blockInfo));
112 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
113 std::string typeAtEncoding =
114 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
115 elements.add(llvm::ConstantExpr::getBitCast(
116 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
119 if (C.getLangOpts().ObjC1) {
120 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
121 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
123 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
126 elements.addNullPointer(i8p);
128 unsigned AddrSpace = 0;
129 if (C.getLangOpts().OpenCL)
130 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
132 llvm::GlobalVariable *global =
133 elements.finishAndCreateGlobal("__block_descriptor_tmp",
134 CGM.getPointerAlign(),
136 llvm::GlobalValue::InternalLinkage,
139 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
143 Purely notional variadic template describing the layout of a block.
145 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
146 struct Block_literal {
147 /// Initialized to one of:
148 /// extern void *_NSConcreteStackBlock[];
149 /// extern void *_NSConcreteGlobalBlock[];
151 /// In theory, we could start one off malloc'ed by setting
152 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
154 /// extern void *_NSConcreteMallocBlock[];
155 struct objc_class *isa;
157 /// These are the flags (with corresponding bit number) that the
158 /// compiler is actually supposed to know about.
159 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
160 /// descriptor provides copy and dispose helper functions
161 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
162 /// object with a nontrivial destructor or copy constructor
163 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
165 /// 29. BLOCK_USE_STRET - indicates that the block function
166 /// uses stret, which objc_msgSend needs to know about
167 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
168 /// @encoded signature string
169 /// And we're not supposed to manipulate these:
170 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
171 /// to malloc'ed memory
172 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
173 /// to GC-allocated memory
174 /// Additionally, the bottom 16 bits are a reference count which
175 /// should be zero on the stack.
178 /// Reserved; should be zero-initialized.
181 /// Function pointer generated from block literal.
182 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
184 /// Block description metadata generated from block literal.
185 struct Block_descriptor *block_descriptor;
187 /// Captured values follow.
188 _CapturesTypes captures...;
193 /// A chunk of data that we actually have to capture in the block.
194 struct BlockLayoutChunk {
197 Qualifiers::ObjCLifetime Lifetime;
198 const BlockDecl::Capture *Capture; // null for 'this'
202 BlockLayoutChunk(CharUnits align, CharUnits size,
203 Qualifiers::ObjCLifetime lifetime,
204 const BlockDecl::Capture *capture,
205 llvm::Type *type, QualType fieldType)
206 : Alignment(align), Size(size), Lifetime(lifetime),
207 Capture(capture), Type(type), FieldType(fieldType) {}
209 /// Tell the block info that this chunk has the given field index.
210 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
212 info.CXXThisIndex = index;
213 info.CXXThisOffset = offset;
215 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
216 info.Captures.insert({Capture->getVariable(), C});
221 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
222 /// all __weak together. Preserve descending alignment in all situations.
223 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
224 if (left.Alignment != right.Alignment)
225 return left.Alignment > right.Alignment;
227 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
228 if (chunk.Capture && chunk.Capture->isByRef())
230 if (chunk.Lifetime == Qualifiers::OCL_Strong)
232 if (chunk.Lifetime == Qualifiers::OCL_Weak)
237 return getPrefOrder(left) < getPrefOrder(right);
239 } // end anonymous namespace
241 /// Determines if the given type is safe for constant capture in C++.
242 static bool isSafeForCXXConstantCapture(QualType type) {
243 const RecordType *recordType =
244 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
246 // Only records can be unsafe.
247 if (!recordType) return true;
249 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
251 // Maintain semantics for classes with non-trivial dtors or copy ctors.
252 if (!record->hasTrivialDestructor()) return false;
253 if (record->hasNonTrivialCopyConstructor()) return false;
255 // Otherwise, we just have to make sure there aren't any mutable
256 // fields that might have changed since initialization.
257 return !record->hasMutableFields();
260 /// It is illegal to modify a const object after initialization.
261 /// Therefore, if a const object has a constant initializer, we don't
262 /// actually need to keep storage for it in the block; we'll just
263 /// rematerialize it at the start of the block function. This is
264 /// acceptable because we make no promises about address stability of
265 /// captured variables.
266 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
267 CodeGenFunction *CGF,
268 const VarDecl *var) {
269 // Return if this is a function paramter. We shouldn't try to
270 // rematerialize default arguments of function parameters.
271 if (isa<ParmVarDecl>(var))
274 QualType type = var->getType();
276 // We can only do this if the variable is const.
277 if (!type.isConstQualified()) return nullptr;
279 // Furthermore, in C++ we have to worry about mutable fields:
280 // C++ [dcl.type.cv]p4:
281 // Except that any class member declared mutable can be
282 // modified, any attempt to modify a const object during its
283 // lifetime results in undefined behavior.
284 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
287 // If the variable doesn't have any initializer (shouldn't this be
288 // invalid?), it's not clear what we should do. Maybe capture as
290 const Expr *init = var->getInit();
291 if (!init) return nullptr;
293 return CGM.EmitConstantInit(*var, CGF);
296 /// Get the low bit of a nonzero character count. This is the
297 /// alignment of the nth byte if the 0th byte is universally aligned.
298 static CharUnits getLowBit(CharUnits v) {
299 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
302 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
303 SmallVectorImpl<llvm::Type*> &elementTypes) {
304 // The header is basically 'struct { void *; int; int; void *; void *; }'.
305 // Assert that that struct is packed.
306 assert(CGM.getIntSize() <= CGM.getPointerSize());
307 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
308 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
310 info.BlockAlign = CGM.getPointerAlign();
311 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
313 assert(elementTypes.empty());
314 elementTypes.push_back(CGM.VoidPtrTy);
315 elementTypes.push_back(CGM.IntTy);
316 elementTypes.push_back(CGM.IntTy);
317 elementTypes.push_back(CGM.VoidPtrTy);
318 elementTypes.push_back(CGM.getBlockDescriptorType());
321 /// Compute the layout of the given block. Attempts to lay the block
322 /// out with minimal space requirements.
323 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
325 ASTContext &C = CGM.getContext();
326 const BlockDecl *block = info.getBlockDecl();
328 SmallVector<llvm::Type*, 8> elementTypes;
329 initializeForBlockHeader(CGM, info, elementTypes);
331 if (!block->hasCaptures()) {
333 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
334 info.CanBeGlobal = true;
337 else if (C.getLangOpts().ObjC1 &&
338 CGM.getLangOpts().getGC() == LangOptions::NonGC)
339 info.HasCapturedVariableLayout = true;
341 // Collect the layout chunks.
342 SmallVector<BlockLayoutChunk, 16> layout;
343 layout.reserve(block->capturesCXXThis() +
344 (block->capture_end() - block->capture_begin()));
346 CharUnits maxFieldAlign;
349 if (block->capturesCXXThis()) {
350 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
351 "Can't capture 'this' outside a method");
352 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
354 // Theoretically, this could be in a different address space, so
355 // don't assume standard pointer size/align.
356 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
357 std::pair<CharUnits,CharUnits> tinfo
358 = CGM.getContext().getTypeInfoInChars(thisType);
359 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
361 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
362 Qualifiers::OCL_None,
363 nullptr, llvmType, thisType));
366 // Next, all the block captures.
367 for (const auto &CI : block->captures()) {
368 const VarDecl *variable = CI.getVariable();
371 // We have to copy/dispose of the __block reference.
372 info.NeedsCopyDispose = true;
374 // Just use void* instead of a pointer to the byref type.
375 CharUnits align = CGM.getPointerAlign();
376 maxFieldAlign = std::max(maxFieldAlign, align);
378 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
379 Qualifiers::OCL_None, &CI,
380 CGM.VoidPtrTy, variable->getType()));
384 // Otherwise, build a layout chunk with the size and alignment of
386 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
387 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
391 // If we have a lifetime qualifier, honor it for capture purposes.
392 // That includes *not* copying it if it's __unsafe_unretained.
393 Qualifiers::ObjCLifetime lifetime =
394 variable->getType().getObjCLifetime();
397 case Qualifiers::OCL_None: llvm_unreachable("impossible");
398 case Qualifiers::OCL_ExplicitNone:
399 case Qualifiers::OCL_Autoreleasing:
402 case Qualifiers::OCL_Strong:
403 case Qualifiers::OCL_Weak:
404 info.NeedsCopyDispose = true;
407 // Block pointers require copy/dispose. So do Objective-C pointers.
408 } else if (variable->getType()->isObjCRetainableType()) {
409 // But honor the inert __unsafe_unretained qualifier, which doesn't
410 // actually make it into the type system.
411 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
412 lifetime = Qualifiers::OCL_ExplicitNone;
414 info.NeedsCopyDispose = true;
415 // used for mrr below.
416 lifetime = Qualifiers::OCL_Strong;
419 // So do types that require non-trivial copy construction.
420 } else if (CI.hasCopyExpr()) {
421 info.NeedsCopyDispose = true;
422 info.HasCXXObject = true;
424 // And so do types with destructors.
425 } else if (CGM.getLangOpts().CPlusPlus) {
426 if (const CXXRecordDecl *record =
427 variable->getType()->getAsCXXRecordDecl()) {
428 if (!record->hasTrivialDestructor()) {
429 info.HasCXXObject = true;
430 info.NeedsCopyDispose = true;
435 QualType VT = variable->getType();
437 // If the variable is captured by an enclosing block or lambda expression,
438 // use the type of the capture field.
439 if (CGF->BlockInfo && CI.isNested())
440 VT = CGF->BlockInfo->getCapture(variable).fieldType();
441 else if (auto *FD = CGF->LambdaCaptureFields.lookup(variable))
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);
453 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
456 // If that was everything, we're done here.
457 if (layout.empty()) {
459 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460 info.CanBeGlobal = true;
464 // Sort the layout by alignment. We have to use a stable sort here
465 // to get reproducible results. There should probably be an
466 // llvm::array_pod_stable_sort.
467 std::stable_sort(layout.begin(), layout.end());
469 // Needed for blocks layout info.
470 info.BlockHeaderForcedGapOffset = info.BlockSize;
471 info.BlockHeaderForcedGapSize = CharUnits::Zero();
473 CharUnits &blockSize = info.BlockSize;
474 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
476 // Assuming that the first byte in the header is maximally aligned,
477 // get the alignment of the first byte following the header.
478 CharUnits endAlign = getLowBit(blockSize);
480 // If the end of the header isn't satisfactorily aligned for the
481 // maximum thing, look for things that are okay with the header-end
482 // alignment, and keep appending them until we get something that's
483 // aligned right. This algorithm is only guaranteed optimal if
484 // that condition is satisfied at some point; otherwise we can get
486 // header // next byte has alignment 4
487 // something_with_size_5; // next byte has alignment 1
488 // something_with_alignment_8;
489 // which has 7 bytes of padding, as opposed to the naive solution
490 // which might have less (?).
491 if (endAlign < maxFieldAlign) {
492 SmallVectorImpl<BlockLayoutChunk>::iterator
493 li = layout.begin() + 1, le = layout.end();
495 // Look for something that the header end is already
496 // satisfactorily aligned for.
497 for (; li != le && endAlign < li->Alignment; ++li)
500 // If we found something that's naturally aligned for the end of
501 // the header, keep adding things...
503 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
504 for (; li != le; ++li) {
505 assert(endAlign >= li->Alignment);
507 li->setIndex(info, elementTypes.size(), blockSize);
508 elementTypes.push_back(li->Type);
509 blockSize += li->Size;
510 endAlign = getLowBit(blockSize);
512 // ...until we get to the alignment of the maximum field.
513 if (endAlign >= maxFieldAlign) {
517 // Don't re-append everything we just appended.
518 layout.erase(first, li);
522 assert(endAlign == getLowBit(blockSize));
524 // At this point, we just have to add padding if the end align still
525 // isn't aligned right.
526 if (endAlign < maxFieldAlign) {
527 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
528 CharUnits padding = newBlockSize - blockSize;
530 // If we haven't yet added any fields, remember that there was an
531 // initial gap; this need to go into the block layout bit map.
532 if (blockSize == info.BlockHeaderForcedGapOffset) {
533 info.BlockHeaderForcedGapSize = padding;
536 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
537 padding.getQuantity()));
538 blockSize = newBlockSize;
539 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
542 assert(endAlign >= maxFieldAlign);
543 assert(endAlign == getLowBit(blockSize));
544 // Slam everything else on now. This works because they have
545 // strictly decreasing alignment and we expect that size is always a
546 // multiple of alignment.
547 for (SmallVectorImpl<BlockLayoutChunk>::iterator
548 li = layout.begin(), le = layout.end(); li != le; ++li) {
549 if (endAlign < li->Alignment) {
550 // size may not be multiple of alignment. This can only happen with
551 // an over-aligned variable. We will be adding a padding field to
552 // make the size be multiple of alignment.
553 CharUnits padding = li->Alignment - endAlign;
554 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
555 padding.getQuantity()));
556 blockSize += padding;
557 endAlign = getLowBit(blockSize);
559 assert(endAlign >= li->Alignment);
560 li->setIndex(info, elementTypes.size(), blockSize);
561 elementTypes.push_back(li->Type);
562 blockSize += li->Size;
563 endAlign = getLowBit(blockSize);
567 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
570 /// Enter the scope of a block. This should be run at the entrance to
571 /// a full-expression so that the block's cleanups are pushed at the
572 /// right place in the stack.
573 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
574 assert(CGF.HaveInsertPoint());
576 // Allocate the block info and place it at the head of the list.
577 CGBlockInfo &blockInfo =
578 *new CGBlockInfo(block, CGF.CurFn->getName());
579 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
580 CGF.FirstBlockInfo = &blockInfo;
582 // Compute information about the layout, etc., of this block,
583 // pushing cleanups as necessary.
584 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
586 // Nothing else to do if it can be global.
587 if (blockInfo.CanBeGlobal) return;
589 // Make the allocation for the block.
590 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
591 blockInfo.BlockAlign, "block");
593 // If there are cleanups to emit, enter them (but inactive).
594 if (!blockInfo.NeedsCopyDispose) return;
596 // Walk through the captures (in order) and find the ones not
597 // captured by constant.
598 for (const auto &CI : block->captures()) {
599 // Ignore __block captures; there's nothing special in the
600 // on-stack block that we need to do for them.
601 if (CI.isByRef()) continue;
603 // Ignore variables that are constant-captured.
604 const VarDecl *variable = CI.getVariable();
605 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
606 if (capture.isConstant()) continue;
608 // Ignore objects that aren't destructed.
609 QualType::DestructionKind dtorKind =
610 variable->getType().isDestructedType();
611 if (dtorKind == QualType::DK_none) continue;
613 CodeGenFunction::Destroyer *destroyer;
615 // Block captures count as local values and have imprecise semantics.
616 // They also can't be arrays, so need to worry about that.
617 if (dtorKind == QualType::DK_objc_strong_lifetime) {
618 destroyer = CodeGenFunction::destroyARCStrongImprecise;
620 destroyer = CGF.getDestroyer(dtorKind);
623 // GEP down to the address.
624 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
626 capture.getOffset());
628 // We can use that GEP as the dominating IP.
629 if (!blockInfo.DominatingIP)
630 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
632 CleanupKind cleanupKind = InactiveNormalCleanup;
633 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
634 if (useArrayEHCleanup)
635 cleanupKind = InactiveNormalAndEHCleanup;
637 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
638 destroyer, useArrayEHCleanup);
640 // Remember where that cleanup was.
641 capture.setCleanup(CGF.EHStack.stable_begin());
645 /// Enter a full-expression with a non-trivial number of objects to
646 /// clean up. This is in this file because, at the moment, the only
647 /// kind of cleanup object is a BlockDecl*.
648 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
649 assert(E->getNumObjects() != 0);
650 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
651 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
652 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
653 enterBlockScope(*this, *i);
657 /// Find the layout for the given block in a linked list and remove it.
658 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
659 const BlockDecl *block) {
661 assert(head && *head);
662 CGBlockInfo *cur = *head;
664 // If this is the block we're looking for, splice it out of the list.
665 if (cur->getBlockDecl() == block) {
666 *head = cur->NextBlockInfo;
670 head = &cur->NextBlockInfo;
674 /// Destroy a chain of block layouts.
675 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
676 assert(head && "destroying an empty chain");
678 CGBlockInfo *cur = head;
679 head = cur->NextBlockInfo;
681 } while (head != nullptr);
684 /// Emit a block literal expression in the current function.
685 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
686 // If the block has no captures, we won't have a pre-computed
688 if (!blockExpr->getBlockDecl()->hasCaptures()) {
689 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
691 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
692 computeBlockInfo(CGM, this, blockInfo);
693 blockInfo.BlockExpression = blockExpr;
694 return EmitBlockLiteral(blockInfo);
697 // Find the block info for this block and take ownership of it.
698 std::unique_ptr<CGBlockInfo> blockInfo;
699 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
700 blockExpr->getBlockDecl()));
702 blockInfo->BlockExpression = blockExpr;
703 return EmitBlockLiteral(*blockInfo);
706 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
707 // Using the computed layout, generate the actual block function.
708 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
709 llvm::Constant *blockFn
710 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
713 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
715 // If there is nothing to capture, we can emit this as a global block.
716 if (blockInfo.CanBeGlobal)
717 return buildGlobalBlock(CGM, blockInfo, blockFn);
719 // Otherwise, we have to emit this as a local block.
721 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
722 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
724 // Build the block descriptor.
725 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
727 Address blockAddr = blockInfo.LocalAddress;
728 assert(blockAddr.isValid() && "block has no address!");
730 // Compute the initial on-stack block flags.
731 BlockFlags flags = BLOCK_HAS_SIGNATURE;
732 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
733 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
734 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
735 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
738 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
739 return Builder.CreateStructGEP(blockAddr, index, offset, name);
742 [&](llvm::Value *value, unsigned index, CharUnits offset,
744 Builder.CreateStore(value, projectField(index, offset, name));
747 // Initialize the block header.
749 // We assume all the header fields are densely packed.
752 auto addHeaderField =
753 [&](llvm::Value *value, CharUnits size, const Twine &name) {
754 storeField(value, index, offset, name);
759 addHeaderField(isa, getPointerSize(), "block.isa");
760 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
761 getIntSize(), "block.flags");
762 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
763 getIntSize(), "block.reserved");
764 addHeaderField(blockFn, getPointerSize(), "block.invoke");
765 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
768 // Finally, capture all the values into the block.
769 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
772 if (blockDecl->capturesCXXThis()) {
773 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
774 "block.captured-this.addr");
775 Builder.CreateStore(LoadCXXThis(), addr);
778 // Next, captured variables.
779 for (const auto &CI : blockDecl->captures()) {
780 const VarDecl *variable = CI.getVariable();
781 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
783 // Ignore constant captures.
784 if (capture.isConstant()) continue;
786 QualType type = capture.fieldType();
788 // This will be a [[type]]*, except that a byref entry will just be
791 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
793 // Compute the address of the thing we're going to move into the
795 Address src = Address::invalid();
797 if (blockDecl->isConversionFromLambda()) {
798 // The lambda capture in a lambda's conversion-to-block-pointer is
799 // special; we'll simply emit it directly.
800 src = Address::invalid();
801 } else if (CI.isByRef()) {
802 if (BlockInfo && CI.isNested()) {
803 // We need to use the capture from the enclosing block.
804 const CGBlockInfo::Capture &enclosingCapture =
805 BlockInfo->getCapture(variable);
807 // This is a [[type]]*, except that a byref entry wil just be an i8**.
808 src = Builder.CreateStructGEP(LoadBlockStruct(),
809 enclosingCapture.getIndex(),
810 enclosingCapture.getOffset(),
811 "block.capture.addr");
813 auto I = LocalDeclMap.find(variable);
814 assert(I != LocalDeclMap.end());
818 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
819 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
820 type.getNonReferenceType(), VK_LValue,
822 src = EmitDeclRefLValue(&declRef).getAddress();
825 // For byrefs, we just write the pointer to the byref struct into
826 // the block field. There's no need to chase the forwarding
827 // pointer at this point, since we're building something that will
828 // live a shorter life than the stack byref anyway.
830 // Get a void* that points to the byref struct.
831 llvm::Value *byrefPointer;
833 byrefPointer = Builder.CreateLoad(src, "byref.capture");
835 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
837 // Write that void* into the capture field.
838 Builder.CreateStore(byrefPointer, blockField);
840 // If we have a copy constructor, evaluate that into the block field.
841 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
842 if (blockDecl->isConversionFromLambda()) {
843 // If we have a lambda conversion, emit the expression
844 // directly into the block instead.
846 AggValueSlot::forAddr(blockField, Qualifiers(),
847 AggValueSlot::IsDestructed,
848 AggValueSlot::DoesNotNeedGCBarriers,
849 AggValueSlot::IsNotAliased);
850 EmitAggExpr(copyExpr, Slot);
852 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
855 // If it's a reference variable, copy the reference into the block field.
856 } else if (type->isReferenceType()) {
857 Builder.CreateStore(src.getPointer(), blockField);
859 // If this is an ARC __strong block-pointer variable, don't do a
862 // TODO: this can be generalized into the normal initialization logic:
863 // we should never need to do a block-copy when initializing a local
864 // variable, because the local variable's lifetime should be strictly
865 // contained within the stack block's.
866 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
867 type->isBlockPointerType()) {
868 // Load the block and do a simple retain.
869 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
870 value = EmitARCRetainNonBlock(value);
872 // Do a primitive store to the block field.
873 Builder.CreateStore(value, blockField);
875 // Otherwise, fake up a POD copy into the block field.
877 // Fake up a new variable so that EmitScalarInit doesn't think
878 // we're referring to the variable in its own initializer.
879 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
880 SourceLocation(), /*name*/ nullptr,
883 // We use one of these or the other depending on whether the
884 // reference is nested.
885 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
886 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
887 type, VK_LValue, SourceLocation());
889 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
890 &declRef, VK_RValue);
891 // FIXME: Pass a specific location for the expr init so that the store is
892 // attributed to a reasonable location - otherwise it may be attributed to
893 // locations of subexpressions in the initialization.
894 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
895 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
896 /*captured by init*/ false);
899 // Activate the cleanup if layout pushed one.
901 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
902 if (cleanup.isValid())
903 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
907 // Cast to the converted block-pointer type, which happens (somewhat
908 // unfortunately) to be a pointer to function type.
909 llvm::Value *result =
910 Builder.CreateBitCast(blockAddr.getPointer(),
911 ConvertType(blockInfo.getBlockExpr()->getType()));
917 llvm::Type *CodeGenModule::getBlockDescriptorType() {
918 if (BlockDescriptorType)
919 return BlockDescriptorType;
921 llvm::Type *UnsignedLongTy =
922 getTypes().ConvertType(getContext().UnsignedLongTy);
924 // struct __block_descriptor {
925 // unsigned long reserved;
926 // unsigned long block_size;
928 // // later, the following will be added
931 // void (*copyHelper)();
932 // void (*copyHelper)();
933 // } helpers; // !!! optional
935 // const char *signature; // the block signature
936 // const char *layout; // reserved
938 BlockDescriptorType =
939 llvm::StructType::create("struct.__block_descriptor",
940 UnsignedLongTy, UnsignedLongTy, nullptr);
942 // Now form a pointer to that.
943 unsigned AddrSpace = 0;
944 if (getLangOpts().OpenCL)
945 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
946 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
947 return BlockDescriptorType;
950 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
951 if (GenericBlockLiteralType)
952 return GenericBlockLiteralType;
954 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
956 // struct __block_literal_generic {
960 // void (*__invoke)(void *);
961 // struct __block_descriptor *__descriptor;
963 GenericBlockLiteralType =
964 llvm::StructType::create("struct.__block_literal_generic",
965 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
966 BlockDescPtrTy, nullptr);
968 return GenericBlockLiteralType;
971 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
972 ReturnValueSlot ReturnValue) {
973 const BlockPointerType *BPT =
974 E->getCallee()->getType()->getAs<BlockPointerType>();
976 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
978 // Get a pointer to the generic block literal.
979 llvm::Type *BlockLiteralTy =
980 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
982 // Bitcast the callee to a block literal.
983 BlockPtr = Builder.CreateBitCast(BlockPtr, BlockLiteralTy, "block.literal");
985 // Get the function pointer from the literal.
986 llvm::Value *FuncPtr =
987 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
989 BlockPtr = Builder.CreateBitCast(BlockPtr, VoidPtrTy);
991 // Add the block literal.
993 Args.add(RValue::get(BlockPtr), getContext().VoidPtrTy);
995 QualType FnType = BPT->getPointeeType();
997 // And the rest of the arguments.
998 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1000 // Load the function.
1001 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1003 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1004 const CGFunctionInfo &FnInfo =
1005 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1007 // Cast the function pointer to the right type.
1008 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1010 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1011 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
1013 // Prepare the callee.
1014 CGCallee Callee(CGCalleeInfo(), Func);
1016 // And call the block.
1017 return EmitCall(FnInfo, Callee, ReturnValue, Args);
1020 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1022 assert(BlockInfo && "evaluating block ref without block information?");
1023 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1025 // Handle constant captures.
1026 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1029 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1030 capture.getOffset(), "block.capture.addr");
1033 // addr should be a void** right now. Load, then cast the result
1036 auto &byrefInfo = getBlockByrefInfo(variable);
1037 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1039 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1040 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1042 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1043 variable->getName());
1046 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
1047 addr = EmitLoadOfReference(addr, refType);
1052 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1053 llvm::Constant *Addr) {
1054 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1056 assert(Ok && "Trying to replace an already-existing global block!");
1060 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1062 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1065 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1066 blockInfo.BlockExpression = BE;
1068 // Compute information about the layout, etc., of this block.
1069 computeBlockInfo(*this, nullptr, blockInfo);
1071 // Using that metadata, generate the actual block function.
1072 llvm::Constant *blockFn;
1074 CodeGenFunction::DeclMapTy LocalDeclMap;
1075 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1080 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1082 return buildGlobalBlock(*this, blockInfo, blockFn);
1085 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1086 const CGBlockInfo &blockInfo,
1087 llvm::Constant *blockFn) {
1088 assert(blockInfo.CanBeGlobal);
1089 // Callers should detect this case on their own: calling this function
1090 // generally requires computing layout information, which is a waste of time
1091 // if we've already emitted this block.
1092 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1093 "Refusing to re-emit a global block.");
1095 // Generate the constants for the block literal initializer.
1096 ConstantInitBuilder builder(CGM);
1097 auto fields = builder.beginStruct();
1100 fields.add(CGM.getNSConcreteGlobalBlock());
1103 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1104 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1106 fields.addInt(CGM.IntTy, flags.getBitMask());
1109 fields.addInt(CGM.IntTy, 0);
1112 fields.add(blockFn);
1115 fields.add(buildBlockDescriptor(CGM, blockInfo));
1117 llvm::Constant *literal =
1118 fields.finishAndCreateGlobal("__block_literal_global",
1119 blockInfo.BlockAlign,
1122 // Return a constant of the appropriately-casted type.
1123 llvm::Type *RequiredType =
1124 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1125 llvm::Constant *Result =
1126 llvm::ConstantExpr::getBitCast(literal, RequiredType);
1127 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1131 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1134 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1136 llvm::Value *localAddr = nullptr;
1137 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1138 // Allocate a stack slot to let the debug info survive the RA.
1139 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1140 Builder.CreateStore(arg, alloc);
1141 localAddr = Builder.CreateLoad(alloc);
1144 if (CGDebugInfo *DI = getDebugInfo()) {
1145 if (CGM.getCodeGenOpts().getDebugInfo() >=
1146 codegenoptions::LimitedDebugInfo) {
1147 DI->setLocation(D->getLocation());
1148 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1149 localAddr, Builder);
1153 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1154 ApplyDebugLocation Scope(*this, StartLoc);
1156 // Instead of messing around with LocalDeclMap, just set the value
1157 // directly as BlockPointer.
1158 BlockPointer = Builder.CreateBitCast(arg,
1159 BlockInfo->StructureType->getPointerTo(),
1163 Address CodeGenFunction::LoadBlockStruct() {
1164 assert(BlockInfo && "not in a block invocation function!");
1165 assert(BlockPointer && "no block pointer set!");
1166 return Address(BlockPointer, BlockInfo->BlockAlign);
1170 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1171 const CGBlockInfo &blockInfo,
1172 const DeclMapTy &ldm,
1173 bool IsLambdaConversionToBlock) {
1174 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1178 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1180 BlockInfo = &blockInfo;
1182 // Arrange for local static and local extern declarations to appear
1183 // to be local to this function as well, in case they're directly
1184 // referenced in a block.
1185 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1186 const auto *var = dyn_cast<VarDecl>(i->first);
1187 if (var && !var->hasLocalStorage())
1188 setAddrOfLocalVar(var, i->second);
1191 // Begin building the function declaration.
1193 // Build the argument list.
1194 FunctionArgList args;
1196 // The first argument is the block pointer. Just take it as a void*
1197 // and cast it later.
1198 QualType selfTy = getContext().VoidPtrTy;
1199 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1201 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1202 SourceLocation(), II, selfTy);
1203 args.push_back(&selfDecl);
1205 // Now add the rest of the parameters.
1206 args.append(blockDecl->param_begin(), blockDecl->param_end());
1208 // Create the function declaration.
1209 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1210 const CGFunctionInfo &fnInfo =
1211 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1212 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1213 blockInfo.UsesStret = true;
1215 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1217 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1218 llvm::Function *fn = llvm::Function::Create(
1219 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1220 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1222 // Begin generating the function.
1223 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1224 blockDecl->getLocation(),
1225 blockInfo.getBlockExpr()->getBody()->getLocStart());
1227 // Okay. Undo some of what StartFunction did.
1229 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1230 // won't delete the dbg.declare intrinsics for captured variables.
1231 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1232 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1233 // Allocate a stack slot for it, so we can point the debugger to it
1234 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1237 // Set the DebugLocation to empty, so the store is recognized as a
1238 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1239 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1240 Builder.CreateStore(BlockPointer, Alloca);
1241 BlockPointerDbgLoc = Alloca.getPointer();
1244 // If we have a C++ 'this' reference, go ahead and force it into
1246 if (blockDecl->capturesCXXThis()) {
1248 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1249 blockInfo.CXXThisOffset, "block.captured-this");
1250 CXXThisValue = Builder.CreateLoad(addr, "this");
1253 // Also force all the constant captures.
1254 for (const auto &CI : blockDecl->captures()) {
1255 const VarDecl *variable = CI.getVariable();
1256 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1257 if (!capture.isConstant()) continue;
1259 CharUnits align = getContext().getDeclAlign(variable);
1261 CreateMemTemp(variable->getType(), align, "block.captured-const");
1263 Builder.CreateStore(capture.getConstant(), alloca);
1265 setAddrOfLocalVar(variable, alloca);
1268 // Save a spot to insert the debug information for all the DeclRefExprs.
1269 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1270 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1273 if (IsLambdaConversionToBlock)
1274 EmitLambdaBlockInvokeBody();
1276 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1277 incrementProfileCounter(blockDecl->getBody());
1278 EmitStmt(blockDecl->getBody());
1281 // Remember where we were...
1282 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1284 // Go back to the entry.
1286 Builder.SetInsertPoint(entry, entry_ptr);
1288 // Emit debug information for all the DeclRefExprs.
1289 // FIXME: also for 'this'
1290 if (CGDebugInfo *DI = getDebugInfo()) {
1291 for (const auto &CI : blockDecl->captures()) {
1292 const VarDecl *variable = CI.getVariable();
1293 DI->EmitLocation(Builder, variable->getLocation());
1295 if (CGM.getCodeGenOpts().getDebugInfo() >=
1296 codegenoptions::LimitedDebugInfo) {
1297 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1298 if (capture.isConstant()) {
1299 auto addr = LocalDeclMap.find(variable)->second;
1300 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1305 DI->EmitDeclareOfBlockDeclRefVariable(
1306 variable, BlockPointerDbgLoc, Builder, blockInfo,
1307 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1310 // Recover location if it was changed in the above loop.
1311 DI->EmitLocation(Builder,
1312 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1315 // And resume where we left off.
1316 if (resume == nullptr)
1317 Builder.ClearInsertionPoint();
1319 Builder.SetInsertPoint(resume);
1321 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1327 notes.push_back(HelperInfo());
1328 HelperInfo ¬e = notes.back();
1329 note.index = capture.getIndex();
1330 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1331 note.cxxbar_import = ci->getCopyExpr();
1333 if (ci->isByRef()) {
1334 note.flag = BLOCK_FIELD_IS_BYREF;
1335 if (type.isObjCGCWeak())
1336 note.flag |= BLOCK_FIELD_IS_WEAK;
1337 } else if (type->isBlockPointerType()) {
1338 note.flag = BLOCK_FIELD_IS_BLOCK;
1340 note.flag = BLOCK_FIELD_IS_OBJECT;
1344 /// Generate the copy-helper function for a block closure object:
1345 /// static void block_copy_helper(block_t *dst, block_t *src);
1346 /// The runtime will have previously initialized 'dst' by doing a
1347 /// bit-copy of 'src'.
1349 /// Note that this copies an entire block closure object to the heap;
1350 /// it should not be confused with a 'byref copy helper', which moves
1351 /// the contents of an individual __block variable to the heap.
1353 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1354 ASTContext &C = getContext();
1356 FunctionArgList args;
1357 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1359 args.push_back(&dstDecl);
1360 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1362 args.push_back(&srcDecl);
1364 const CGFunctionInfo &FI =
1365 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1367 // FIXME: it would be nice if these were mergeable with things with
1368 // identical semantics.
1369 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1371 llvm::Function *Fn =
1372 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1373 "__copy_helper_block_", &CGM.getModule());
1376 = &CGM.getContext().Idents.get("__copy_helper_block_");
1378 FunctionDecl *FD = FunctionDecl::Create(C,
1379 C.getTranslationUnitDecl(),
1381 SourceLocation(), II, C.VoidTy,
1386 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1388 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1389 StartFunction(FD, C.VoidTy, Fn, FI, args);
1390 // Create a scope with an artificial location for the body of this function.
1391 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1392 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1394 Address src = GetAddrOfLocalVar(&srcDecl);
1395 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1396 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1398 Address dst = GetAddrOfLocalVar(&dstDecl);
1399 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1400 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1402 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1404 for (const auto &CI : blockDecl->captures()) {
1405 const VarDecl *variable = CI.getVariable();
1406 QualType type = variable->getType();
1408 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1409 if (capture.isConstant()) continue;
1411 const Expr *copyExpr = CI.getCopyExpr();
1412 BlockFieldFlags flags;
1414 bool useARCWeakCopy = false;
1415 bool useARCStrongCopy = false;
1418 assert(!CI.isByRef());
1419 // don't bother computing flags
1421 } else if (CI.isByRef()) {
1422 flags = BLOCK_FIELD_IS_BYREF;
1423 if (type.isObjCGCWeak())
1424 flags |= BLOCK_FIELD_IS_WEAK;
1426 } else if (type->isObjCRetainableType()) {
1427 flags = BLOCK_FIELD_IS_OBJECT;
1428 bool isBlockPointer = type->isBlockPointerType();
1430 flags = BLOCK_FIELD_IS_BLOCK;
1432 // Special rules for ARC captures:
1433 Qualifiers qs = type.getQualifiers();
1435 // We need to register __weak direct captures with the runtime.
1436 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1437 useARCWeakCopy = true;
1439 // We need to retain the copied value for __strong direct captures.
1440 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1441 // If it's a block pointer, we have to copy the block and
1442 // assign that to the destination pointer, so we might as
1443 // well use _Block_object_assign. Otherwise we can avoid that.
1444 if (!isBlockPointer)
1445 useARCStrongCopy = true;
1447 // Non-ARC captures of retainable pointers are strong and
1448 // therefore require a call to _Block_object_assign.
1449 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1452 // Otherwise the memcpy is fine.
1457 // For all other types, the memcpy is fine.
1462 unsigned index = capture.getIndex();
1463 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1464 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1466 // If there's an explicit copy expression, we do that.
1468 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1469 } else if (useARCWeakCopy) {
1470 EmitARCCopyWeak(dstField, srcField);
1472 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1473 if (useARCStrongCopy) {
1474 // At -O0, store null into the destination field (so that the
1475 // storeStrong doesn't over-release) and then call storeStrong.
1476 // This is a workaround to not having an initStrong call.
1477 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1478 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1479 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1480 Builder.CreateStore(null, dstField);
1481 EmitARCStoreStrongCall(dstField, srcValue, true);
1483 // With optimization enabled, take advantage of the fact that
1484 // the blocks runtime guarantees a memcpy of the block data, and
1485 // just emit a retain of the src field.
1487 EmitARCRetainNonBlock(srcValue);
1489 // We don't need this anymore, so kill it. It's not quite
1490 // worth the annoyance to avoid creating it in the first place.
1491 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1494 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1495 llvm::Value *dstAddr =
1496 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1497 llvm::Value *args[] = {
1498 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1501 bool copyCanThrow = false;
1502 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1503 const Expr *copyExpr =
1504 CGM.getContext().getBlockVarCopyInits(variable);
1506 copyCanThrow = true; // FIXME: reuse the noexcept logic
1511 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1513 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1521 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1524 /// Generate the destroy-helper function for a block closure object:
1525 /// static void block_destroy_helper(block_t *theBlock);
1527 /// Note that this destroys a heap-allocated block closure object;
1528 /// it should not be confused with a 'byref destroy helper', which
1529 /// destroys the heap-allocated contents of an individual __block
1532 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1533 ASTContext &C = getContext();
1535 FunctionArgList args;
1536 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1538 args.push_back(&srcDecl);
1540 const CGFunctionInfo &FI =
1541 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1543 // FIXME: We'd like to put these into a mergable by content, with
1544 // internal linkage.
1545 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1547 llvm::Function *Fn =
1548 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1549 "__destroy_helper_block_", &CGM.getModule());
1552 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1554 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1556 SourceLocation(), II, C.VoidTy,
1560 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1562 // Create a scope with an artificial location for the body of this function.
1563 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1564 StartFunction(FD, C.VoidTy, Fn, FI, args);
1565 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1567 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1569 Address src = GetAddrOfLocalVar(&srcDecl);
1570 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1571 src = Builder.CreateBitCast(src, structPtrTy, "block");
1573 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1575 CodeGenFunction::RunCleanupsScope cleanups(*this);
1577 for (const auto &CI : blockDecl->captures()) {
1578 const VarDecl *variable = CI.getVariable();
1579 QualType type = variable->getType();
1581 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1582 if (capture.isConstant()) continue;
1584 BlockFieldFlags flags;
1585 const CXXDestructorDecl *dtor = nullptr;
1587 bool useARCWeakDestroy = false;
1588 bool useARCStrongDestroy = false;
1591 flags = BLOCK_FIELD_IS_BYREF;
1592 if (type.isObjCGCWeak())
1593 flags |= BLOCK_FIELD_IS_WEAK;
1594 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1595 if (record->hasTrivialDestructor())
1597 dtor = record->getDestructor();
1598 } else if (type->isObjCRetainableType()) {
1599 flags = BLOCK_FIELD_IS_OBJECT;
1600 if (type->isBlockPointerType())
1601 flags = BLOCK_FIELD_IS_BLOCK;
1603 // Special rules for ARC captures.
1604 Qualifiers qs = type.getQualifiers();
1606 // Use objc_storeStrong for __strong direct captures; the
1607 // dynamic tools really like it when we do this.
1608 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1609 useARCStrongDestroy = true;
1611 // Support __weak direct captures.
1612 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1613 useARCWeakDestroy = true;
1615 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1616 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1619 // Otherwise, we have nothing to do.
1628 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1630 // If there's an explicit copy expression, we do that.
1632 PushDestructorCleanup(dtor, srcField);
1634 // If this is a __weak capture, emit the release directly.
1635 } else if (useARCWeakDestroy) {
1636 EmitARCDestroyWeak(srcField);
1638 // Destroy strong objects with a call if requested.
1639 } else if (useARCStrongDestroy) {
1640 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1642 // Otherwise we call _Block_object_dispose. It wouldn't be too
1643 // hard to just emit this as a cleanup if we wanted to make sure
1644 // that things were done in reverse.
1646 llvm::Value *value = Builder.CreateLoad(srcField);
1647 value = Builder.CreateBitCast(value, VoidPtrTy);
1648 BuildBlockRelease(value, flags);
1652 cleanups.ForceCleanup();
1656 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1661 /// Emits the copy/dispose helper functions for a __block object of id type.
1662 class ObjectByrefHelpers final : public BlockByrefHelpers {
1663 BlockFieldFlags Flags;
1666 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1667 : BlockByrefHelpers(alignment), Flags(flags) {}
1669 void emitCopy(CodeGenFunction &CGF, Address destField,
1670 Address srcField) override {
1671 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1673 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1674 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1676 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1678 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1679 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1681 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1682 CGF.EmitNounwindRuntimeCall(fn, args);
1685 void emitDispose(CodeGenFunction &CGF, Address field) override {
1686 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1687 llvm::Value *value = CGF.Builder.CreateLoad(field);
1689 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1692 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1693 id.AddInteger(Flags.getBitMask());
1697 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1698 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1700 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1702 void emitCopy(CodeGenFunction &CGF, Address destField,
1703 Address srcField) override {
1704 CGF.EmitARCMoveWeak(destField, srcField);
1707 void emitDispose(CodeGenFunction &CGF, Address field) override {
1708 CGF.EmitARCDestroyWeak(field);
1711 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1712 // 0 is distinguishable from all pointers and byref flags
1717 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1718 /// that's not of block-pointer type.
1719 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1721 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1723 void emitCopy(CodeGenFunction &CGF, Address destField,
1724 Address srcField) override {
1725 // Do a "move" by copying the value and then zeroing out the old
1728 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1731 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1733 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1734 CGF.Builder.CreateStore(null, destField);
1735 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1736 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1739 CGF.Builder.CreateStore(value, destField);
1740 CGF.Builder.CreateStore(null, srcField);
1743 void emitDispose(CodeGenFunction &CGF, Address field) override {
1744 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1747 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1748 // 1 is distinguishable from all pointers and byref flags
1753 /// Emits the copy/dispose helpers for an ARC __block __strong
1754 /// variable that's of block-pointer type.
1755 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1757 ARCStrongBlockByrefHelpers(CharUnits alignment)
1758 : BlockByrefHelpers(alignment) {}
1760 void emitCopy(CodeGenFunction &CGF, Address destField,
1761 Address srcField) override {
1762 // Do the copy with objc_retainBlock; that's all that
1763 // _Block_object_assign would do anyway, and we'd have to pass the
1764 // right arguments to make sure it doesn't get no-op'ed.
1765 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1766 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1767 CGF.Builder.CreateStore(copy, destField);
1770 void emitDispose(CodeGenFunction &CGF, Address field) override {
1771 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1774 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1775 // 2 is distinguishable from all pointers and byref flags
1780 /// Emits the copy/dispose helpers for a __block variable with a
1781 /// nontrivial copy constructor or destructor.
1782 class CXXByrefHelpers final : public BlockByrefHelpers {
1784 const Expr *CopyExpr;
1787 CXXByrefHelpers(CharUnits alignment, QualType type,
1788 const Expr *copyExpr)
1789 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1791 bool needsCopy() const override { return CopyExpr != nullptr; }
1792 void emitCopy(CodeGenFunction &CGF, Address destField,
1793 Address srcField) override {
1794 if (!CopyExpr) return;
1795 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1798 void emitDispose(CodeGenFunction &CGF, Address field) override {
1799 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1800 CGF.PushDestructorCleanup(VarType, field);
1801 CGF.PopCleanupBlocks(cleanupDepth);
1804 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1805 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1808 } // end anonymous namespace
1810 static llvm::Constant *
1811 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1812 BlockByrefHelpers &generator) {
1813 ASTContext &Context = CGF.getContext();
1815 QualType R = Context.VoidTy;
1817 FunctionArgList args;
1818 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1820 args.push_back(&dst);
1822 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1824 args.push_back(&src);
1826 const CGFunctionInfo &FI =
1827 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1829 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1831 // FIXME: We'd like to put these into a mergable by content, with
1832 // internal linkage.
1833 llvm::Function *Fn =
1834 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1835 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1838 = &Context.Idents.get("__Block_byref_object_copy_");
1840 FunctionDecl *FD = FunctionDecl::Create(Context,
1841 Context.getTranslationUnitDecl(),
1843 SourceLocation(), II, R, nullptr,
1847 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1849 CGF.StartFunction(FD, R, Fn, FI, args);
1851 if (generator.needsCopy()) {
1852 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1855 Address destField = CGF.GetAddrOfLocalVar(&dst);
1856 destField = Address(CGF.Builder.CreateLoad(destField),
1857 byrefInfo.ByrefAlignment);
1858 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1859 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1863 Address srcField = CGF.GetAddrOfLocalVar(&src);
1864 srcField = Address(CGF.Builder.CreateLoad(srcField),
1865 byrefInfo.ByrefAlignment);
1866 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1867 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1870 generator.emitCopy(CGF, destField, srcField);
1873 CGF.FinishFunction();
1875 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1878 /// Build the copy helper for a __block variable.
1879 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1880 const BlockByrefInfo &byrefInfo,
1881 BlockByrefHelpers &generator) {
1882 CodeGenFunction CGF(CGM);
1883 return generateByrefCopyHelper(CGF, byrefInfo, generator);
1886 /// Generate code for a __block variable's dispose helper.
1887 static llvm::Constant *
1888 generateByrefDisposeHelper(CodeGenFunction &CGF,
1889 const BlockByrefInfo &byrefInfo,
1890 BlockByrefHelpers &generator) {
1891 ASTContext &Context = CGF.getContext();
1892 QualType R = Context.VoidTy;
1894 FunctionArgList args;
1895 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1897 args.push_back(&src);
1899 const CGFunctionInfo &FI =
1900 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1902 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1904 // FIXME: We'd like to put these into a mergable by content, with
1905 // internal linkage.
1906 llvm::Function *Fn =
1907 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1908 "__Block_byref_object_dispose_",
1909 &CGF.CGM.getModule());
1912 = &Context.Idents.get("__Block_byref_object_dispose_");
1914 FunctionDecl *FD = FunctionDecl::Create(Context,
1915 Context.getTranslationUnitDecl(),
1917 SourceLocation(), II, R, nullptr,
1921 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1923 CGF.StartFunction(FD, R, Fn, FI, args);
1925 if (generator.needsDispose()) {
1926 Address addr = CGF.GetAddrOfLocalVar(&src);
1927 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1928 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1929 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1930 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1932 generator.emitDispose(CGF, addr);
1935 CGF.FinishFunction();
1937 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1940 /// Build the dispose helper for a __block variable.
1941 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1942 const BlockByrefInfo &byrefInfo,
1943 BlockByrefHelpers &generator) {
1944 CodeGenFunction CGF(CGM);
1945 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1948 /// Lazily build the copy and dispose helpers for a __block variable
1949 /// with the given information.
1951 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1953 llvm::FoldingSetNodeID id;
1954 generator.Profile(id);
1957 BlockByrefHelpers *node
1958 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1959 if (node) return static_cast<T*>(node);
1961 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1962 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1964 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
1965 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1969 /// Build the copy and dispose helpers for the given __block variable
1970 /// emission. Places the helpers in the global cache. Returns null
1971 /// if no helpers are required.
1973 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1974 const AutoVarEmission &emission) {
1975 const VarDecl &var = *emission.Variable;
1976 QualType type = var.getType();
1978 auto &byrefInfo = getBlockByrefInfo(&var);
1980 // The alignment we care about for the purposes of uniquing byref
1981 // helpers is the alignment of the actual byref value field.
1982 CharUnits valueAlignment =
1983 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1985 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1986 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1987 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1989 return ::buildByrefHelpers(
1990 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1993 // Otherwise, if we don't have a retainable type, there's nothing to do.
1994 // that the runtime does extra copies.
1995 if (!type->isObjCRetainableType()) return nullptr;
1997 Qualifiers qs = type.getQualifiers();
1999 // If we have lifetime, that dominates.
2000 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2002 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2004 // These are just bits as far as the runtime is concerned.
2005 case Qualifiers::OCL_ExplicitNone:
2006 case Qualifiers::OCL_Autoreleasing:
2009 // Tell the runtime that this is ARC __weak, called by the
2011 case Qualifiers::OCL_Weak:
2012 return ::buildByrefHelpers(CGM, byrefInfo,
2013 ARCWeakByrefHelpers(valueAlignment));
2015 // ARC __strong __block variables need to be retained.
2016 case Qualifiers::OCL_Strong:
2017 // Block pointers need to be copied, and there's no direct
2018 // transfer possible.
2019 if (type->isBlockPointerType()) {
2020 return ::buildByrefHelpers(CGM, byrefInfo,
2021 ARCStrongBlockByrefHelpers(valueAlignment));
2023 // Otherwise, we transfer ownership of the retain from the stack
2026 return ::buildByrefHelpers(CGM, byrefInfo,
2027 ARCStrongByrefHelpers(valueAlignment));
2030 llvm_unreachable("fell out of lifetime switch!");
2033 BlockFieldFlags flags;
2034 if (type->isBlockPointerType()) {
2035 flags |= BLOCK_FIELD_IS_BLOCK;
2036 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2037 type->isObjCObjectPointerType()) {
2038 flags |= BLOCK_FIELD_IS_OBJECT;
2043 if (type.isObjCGCWeak())
2044 flags |= BLOCK_FIELD_IS_WEAK;
2046 return ::buildByrefHelpers(CGM, byrefInfo,
2047 ObjectByrefHelpers(valueAlignment, flags));
2050 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2052 bool followForward) {
2053 auto &info = getBlockByrefInfo(var);
2054 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2057 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2058 const BlockByrefInfo &info,
2060 const llvm::Twine &name) {
2061 // Chase the forwarding address if requested.
2062 if (followForward) {
2063 Address forwardingAddr =
2064 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2065 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2068 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2069 info.FieldOffset, name);
2072 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2077 /// void *__forwarding;
2078 /// int32_t __flags;
2080 /// void *__copy_helper; // only if needed
2081 /// void *__destroy_helper; // only if needed
2082 /// void *__byref_variable_layout;// only if needed
2083 /// char padding[X]; // only if needed
2087 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2088 auto it = BlockByrefInfos.find(D);
2089 if (it != BlockByrefInfos.end())
2092 llvm::StructType *byrefType =
2093 llvm::StructType::create(getLLVMContext(),
2094 "struct.__block_byref_" + D->getNameAsString());
2096 QualType Ty = D->getType();
2099 SmallVector<llvm::Type *, 8> types;
2102 types.push_back(Int8PtrTy);
2103 size += getPointerSize();
2105 // void *__forwarding;
2106 types.push_back(llvm::PointerType::getUnqual(byrefType));
2107 size += getPointerSize();
2110 types.push_back(Int32Ty);
2111 size += CharUnits::fromQuantity(4);
2114 types.push_back(Int32Ty);
2115 size += CharUnits::fromQuantity(4);
2117 // Note that this must match *exactly* the logic in buildByrefHelpers.
2118 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2119 if (hasCopyAndDispose) {
2120 /// void *__copy_helper;
2121 types.push_back(Int8PtrTy);
2122 size += getPointerSize();
2124 /// void *__destroy_helper;
2125 types.push_back(Int8PtrTy);
2126 size += getPointerSize();
2129 bool HasByrefExtendedLayout = false;
2130 Qualifiers::ObjCLifetime Lifetime;
2131 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2132 HasByrefExtendedLayout) {
2133 /// void *__byref_variable_layout;
2134 types.push_back(Int8PtrTy);
2135 size += CharUnits::fromQuantity(PointerSizeInBytes);
2139 llvm::Type *varTy = ConvertTypeForMem(Ty);
2141 bool packed = false;
2142 CharUnits varAlign = getContext().getDeclAlign(D);
2143 CharUnits varOffset = size.alignTo(varAlign);
2145 // We may have to insert padding.
2146 if (varOffset != size) {
2147 llvm::Type *paddingTy =
2148 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2150 types.push_back(paddingTy);
2153 // Conversely, we might have to prevent LLVM from inserting padding.
2154 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2155 > varAlign.getQuantity()) {
2158 types.push_back(varTy);
2160 byrefType->setBody(types, packed);
2162 BlockByrefInfo info;
2163 info.Type = byrefType;
2164 info.FieldIndex = types.size() - 1;
2165 info.FieldOffset = varOffset;
2166 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2168 auto pair = BlockByrefInfos.insert({D, info});
2169 assert(pair.second && "info was inserted recursively?");
2170 return pair.first->second;
2173 /// Initialize the structural components of a __block variable, i.e.
2174 /// everything but the actual object.
2175 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2176 // Find the address of the local.
2177 Address addr = emission.Addr;
2179 // That's an alloca of the byref structure type.
2180 llvm::StructType *byrefType = cast<llvm::StructType>(
2181 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2183 unsigned nextHeaderIndex = 0;
2184 CharUnits nextHeaderOffset;
2185 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2186 const Twine &name) {
2187 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2188 nextHeaderOffset, name);
2189 Builder.CreateStore(value, fieldAddr);
2192 nextHeaderOffset += fieldSize;
2195 // Build the byref helpers if necessary. This is null if we don't need any.
2196 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2198 const VarDecl &D = *emission.Variable;
2199 QualType type = D.getType();
2201 bool HasByrefExtendedLayout;
2202 Qualifiers::ObjCLifetime ByrefLifetime;
2203 bool ByRefHasLifetime =
2204 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2208 // Initialize the 'isa', which is just 0 or 1.
2210 if (type.isObjCGCWeak())
2212 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2213 storeHeaderField(V, getPointerSize(), "byref.isa");
2215 // Store the address of the variable into its own forwarding pointer.
2216 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2219 // c) the flags field is set to either 0 if no helper functions are
2220 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2222 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2223 if (ByRefHasLifetime) {
2224 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2225 else switch (ByrefLifetime) {
2226 case Qualifiers::OCL_Strong:
2227 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2229 case Qualifiers::OCL_Weak:
2230 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2232 case Qualifiers::OCL_ExplicitNone:
2233 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2235 case Qualifiers::OCL_None:
2236 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2237 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2242 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2243 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2244 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2245 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2246 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2247 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2248 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2249 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2250 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2251 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2252 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2253 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2254 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2255 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2256 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2257 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2262 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2263 getIntSize(), "byref.flags");
2265 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2266 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2267 storeHeaderField(V, getIntSize(), "byref.size");
2270 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2271 "byref.copyHelper");
2272 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2273 "byref.disposeHelper");
2276 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2277 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2278 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2282 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2283 llvm::Value *F = CGM.getBlockObjectDispose();
2284 llvm::Value *args[] = {
2285 Builder.CreateBitCast(V, Int8PtrTy),
2286 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2288 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2292 /// Release a __block variable.
2293 struct CallBlockRelease final : EHScopeStack::Cleanup {
2295 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2297 void Emit(CodeGenFunction &CGF, Flags flags) override {
2298 // Should we be passing FIELD_IS_WEAK here?
2299 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2302 } // end anonymous namespace
2304 /// Enter a cleanup to destroy a __block variable. Note that this
2305 /// cleanup should be a no-op if the variable hasn't left the stack
2306 /// yet; if a cleanup is required for the variable itself, that needs
2307 /// to be done externally.
2308 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2309 // We don't enter this cleanup if we're in pure-GC mode.
2310 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2313 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2314 emission.Addr.getPointer());
2317 /// Adjust the declaration of something from the blocks API.
2318 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2319 llvm::Constant *C) {
2320 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2322 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2323 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2324 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2325 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2327 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2328 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2329 "expected Function or GlobalVariable");
2331 const NamedDecl *ND = nullptr;
2332 for (const auto &Result : DC->lookup(&II))
2333 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2334 (ND = dyn_cast<VarDecl>(Result)))
2337 // TODO: support static blocks runtime
2338 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2339 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2340 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2342 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2343 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2347 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2350 if (GV->isDeclaration() && GV->hasExternalLinkage())
2351 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2354 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2355 if (BlockObjectDispose)
2356 return BlockObjectDispose;
2358 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2359 llvm::FunctionType *fty
2360 = llvm::FunctionType::get(VoidTy, args, false);
2361 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2362 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2363 return BlockObjectDispose;
2366 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2367 if (BlockObjectAssign)
2368 return BlockObjectAssign;
2370 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2371 llvm::FunctionType *fty
2372 = llvm::FunctionType::get(VoidTy, args, false);
2373 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2374 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2375 return BlockObjectAssign;
2378 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2379 if (NSConcreteGlobalBlock)
2380 return NSConcreteGlobalBlock;
2382 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2383 Int8PtrTy->getPointerTo(),
2385 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2386 return NSConcreteGlobalBlock;
2389 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2390 if (NSConcreteStackBlock)
2391 return NSConcreteStackBlock;
2393 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2394 Int8PtrTy->getPointerTo(),
2396 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2397 return NSConcreteStackBlock;