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 "clang/AST/DeclObjC.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.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 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
34 DominatingIP(nullptr) {
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 BlockByrefHelpers::~BlockByrefHelpers() {}
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 dispose 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.
67 /// struct Block_descriptor {
68 /// unsigned long reserved;
69 /// unsigned long size; // size of Block_literal metadata in bytes.
70 /// void *copy_func_helper_decl; // optional copy helper.
71 /// void *destroy_func_decl; // optioanl destructor helper.
72 /// void *block_method_encoding_address; // @encode for block literal signature.
73 /// void *block_layout_info; // encoding of captured block variables.
76 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
80 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
81 llvm::Type *i8p = nullptr;
82 if (CGM.getLangOpts().OpenCL)
84 llvm::Type::getInt8PtrTy(
85 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
87 i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
89 SmallVector<llvm::Constant*, 6> elements;
92 elements.push_back(llvm::ConstantInt::get(ulong, 0));
95 // FIXME: What is the right way to say this doesn't fit? We should give
96 // a user diagnostic in that case. Better fix would be to change the
98 elements.push_back(llvm::ConstantInt::get(ulong,
99 blockInfo.BlockSize.getQuantity()));
101 // Optional copy/dispose helpers.
102 if (blockInfo.NeedsCopyDispose) {
103 // copy_func_helper_decl
104 elements.push_back(buildCopyHelper(CGM, blockInfo));
107 elements.push_back(buildDisposeHelper(CGM, blockInfo));
110 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
111 std::string typeAtEncoding =
112 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113 elements.push_back(llvm::ConstantExpr::getBitCast(
114 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
117 if (C.getLangOpts().ObjC1) {
118 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
121 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
124 elements.push_back(llvm::Constant::getNullValue(i8p));
126 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
128 llvm::GlobalVariable *global =
129 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130 llvm::GlobalValue::InternalLinkage,
131 init, "__block_descriptor_tmp");
133 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
137 Purely notional variadic template describing the layout of a block.
139 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140 struct Block_literal {
141 /// Initialized to one of:
142 /// extern void *_NSConcreteStackBlock[];
143 /// extern void *_NSConcreteGlobalBlock[];
145 /// In theory, we could start one off malloc'ed by setting
146 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
148 /// extern void *_NSConcreteMallocBlock[];
149 struct objc_class *isa;
151 /// These are the flags (with corresponding bit number) that the
152 /// compiler is actually supposed to know about.
153 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154 /// descriptor provides copy and dispose helper functions
155 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156 /// object with a nontrivial destructor or copy constructor
157 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
159 /// 29. BLOCK_USE_STRET - indicates that the block function
160 /// uses stret, which objc_msgSend needs to know about
161 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162 /// @encoded signature string
163 /// And we're not supposed to manipulate these:
164 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165 /// to malloc'ed memory
166 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
167 /// to GC-allocated memory
168 /// Additionally, the bottom 16 bits are a reference count which
169 /// should be zero on the stack.
172 /// Reserved; should be zero-initialized.
175 /// Function pointer generated from block literal.
176 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
178 /// Block description metadata generated from block literal.
179 struct Block_descriptor *block_descriptor;
181 /// Captured values follow.
182 _CapturesTypes captures...;
186 /// The number of fields in a block header.
187 const unsigned BlockHeaderSize = 5;
190 /// A chunk of data that we actually have to capture in the block.
191 struct BlockLayoutChunk {
194 Qualifiers::ObjCLifetime Lifetime;
195 const BlockDecl::Capture *Capture; // null for 'this'
198 BlockLayoutChunk(CharUnits align, CharUnits size,
199 Qualifiers::ObjCLifetime lifetime,
200 const BlockDecl::Capture *capture,
202 : Alignment(align), Size(size), Lifetime(lifetime),
203 Capture(capture), Type(type) {}
205 /// Tell the block info that this chunk has the given field index.
206 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
208 info.CXXThisIndex = index;
209 info.CXXThisOffset = offset;
211 info.Captures.insert({Capture->getVariable(),
212 CGBlockInfo::Capture::makeIndex(index, offset)});
217 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
218 /// all __weak together. Preserve descending alignment in all situations.
219 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
220 if (left.Alignment != right.Alignment)
221 return left.Alignment > right.Alignment;
223 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
224 if (chunk.Capture && chunk.Capture->isByRef())
226 if (chunk.Lifetime == Qualifiers::OCL_Strong)
228 if (chunk.Lifetime == Qualifiers::OCL_Weak)
233 return getPrefOrder(left) < getPrefOrder(right);
235 } // end anonymous namespace
237 /// Determines if the given type is safe for constant capture in C++.
238 static bool isSafeForCXXConstantCapture(QualType type) {
239 const RecordType *recordType =
240 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
242 // Only records can be unsafe.
243 if (!recordType) return true;
245 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
247 // Maintain semantics for classes with non-trivial dtors or copy ctors.
248 if (!record->hasTrivialDestructor()) return false;
249 if (record->hasNonTrivialCopyConstructor()) return false;
251 // Otherwise, we just have to make sure there aren't any mutable
252 // fields that might have changed since initialization.
253 return !record->hasMutableFields();
256 /// It is illegal to modify a const object after initialization.
257 /// Therefore, if a const object has a constant initializer, we don't
258 /// actually need to keep storage for it in the block; we'll just
259 /// rematerialize it at the start of the block function. This is
260 /// acceptable because we make no promises about address stability of
261 /// captured variables.
262 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
263 CodeGenFunction *CGF,
264 const VarDecl *var) {
265 QualType type = var->getType();
267 // We can only do this if the variable is const.
268 if (!type.isConstQualified()) return nullptr;
270 // Furthermore, in C++ we have to worry about mutable fields:
271 // C++ [dcl.type.cv]p4:
272 // Except that any class member declared mutable can be
273 // modified, any attempt to modify a const object during its
274 // lifetime results in undefined behavior.
275 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
278 // If the variable doesn't have any initializer (shouldn't this be
279 // invalid?), it's not clear what we should do. Maybe capture as
281 const Expr *init = var->getInit();
282 if (!init) return nullptr;
284 return CGM.EmitConstantInit(*var, CGF);
287 /// Get the low bit of a nonzero character count. This is the
288 /// alignment of the nth byte if the 0th byte is universally aligned.
289 static CharUnits getLowBit(CharUnits v) {
290 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
293 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
294 SmallVectorImpl<llvm::Type*> &elementTypes) {
295 // The header is basically 'struct { void *; int; int; void *; void *; }'.
296 // Assert that that struct is packed.
297 assert(CGM.getIntSize() <= CGM.getPointerSize());
298 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
299 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
301 info.BlockAlign = CGM.getPointerAlign();
302 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
304 assert(elementTypes.empty());
305 elementTypes.push_back(CGM.VoidPtrTy);
306 elementTypes.push_back(CGM.IntTy);
307 elementTypes.push_back(CGM.IntTy);
308 elementTypes.push_back(CGM.VoidPtrTy);
309 elementTypes.push_back(CGM.getBlockDescriptorType());
311 assert(elementTypes.size() == BlockHeaderSize);
314 /// Compute the layout of the given block. Attempts to lay the block
315 /// out with minimal space requirements.
316 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
318 ASTContext &C = CGM.getContext();
319 const BlockDecl *block = info.getBlockDecl();
321 SmallVector<llvm::Type*, 8> elementTypes;
322 initializeForBlockHeader(CGM, info, elementTypes);
324 if (!block->hasCaptures()) {
326 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
327 info.CanBeGlobal = true;
330 else if (C.getLangOpts().ObjC1 &&
331 CGM.getLangOpts().getGC() == LangOptions::NonGC)
332 info.HasCapturedVariableLayout = true;
334 // Collect the layout chunks.
335 SmallVector<BlockLayoutChunk, 16> layout;
336 layout.reserve(block->capturesCXXThis() +
337 (block->capture_end() - block->capture_begin()));
339 CharUnits maxFieldAlign;
342 if (block->capturesCXXThis()) {
343 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
344 "Can't capture 'this' outside a method");
345 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
347 // Theoretically, this could be in a different address space, so
348 // don't assume standard pointer size/align.
349 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
350 std::pair<CharUnits,CharUnits> tinfo
351 = CGM.getContext().getTypeInfoInChars(thisType);
352 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
354 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
355 Qualifiers::OCL_None,
359 // Next, all the block captures.
360 for (const auto &CI : block->captures()) {
361 const VarDecl *variable = CI.getVariable();
364 // We have to copy/dispose of the __block reference.
365 info.NeedsCopyDispose = true;
367 // Just use void* instead of a pointer to the byref type.
368 CharUnits align = CGM.getPointerAlign();
369 maxFieldAlign = std::max(maxFieldAlign, align);
371 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
372 Qualifiers::OCL_None, &CI,
377 // Otherwise, build a layout chunk with the size and alignment of
379 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
380 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
384 // If we have a lifetime qualifier, honor it for capture purposes.
385 // That includes *not* copying it if it's __unsafe_unretained.
386 Qualifiers::ObjCLifetime lifetime =
387 variable->getType().getObjCLifetime();
390 case Qualifiers::OCL_None: llvm_unreachable("impossible");
391 case Qualifiers::OCL_ExplicitNone:
392 case Qualifiers::OCL_Autoreleasing:
395 case Qualifiers::OCL_Strong:
396 case Qualifiers::OCL_Weak:
397 info.NeedsCopyDispose = true;
400 // Block pointers require copy/dispose. So do Objective-C pointers.
401 } else if (variable->getType()->isObjCRetainableType()) {
402 // But honor the inert __unsafe_unretained qualifier, which doesn't
403 // actually make it into the type system.
404 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
405 lifetime = Qualifiers::OCL_ExplicitNone;
407 info.NeedsCopyDispose = true;
408 // used for mrr below.
409 lifetime = Qualifiers::OCL_Strong;
412 // So do types that require non-trivial copy construction.
413 } else if (CI.hasCopyExpr()) {
414 info.NeedsCopyDispose = true;
415 info.HasCXXObject = true;
417 // And so do types with destructors.
418 } else if (CGM.getLangOpts().CPlusPlus) {
419 if (const CXXRecordDecl *record =
420 variable->getType()->getAsCXXRecordDecl()) {
421 if (!record->hasTrivialDestructor()) {
422 info.HasCXXObject = true;
423 info.NeedsCopyDispose = true;
428 QualType VT = variable->getType();
429 CharUnits size = C.getTypeSizeInChars(VT);
430 CharUnits align = C.getDeclAlign(variable);
432 maxFieldAlign = std::max(maxFieldAlign, align);
434 llvm::Type *llvmType =
435 CGM.getTypes().ConvertTypeForMem(VT);
437 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
440 // If that was everything, we're done here.
441 if (layout.empty()) {
443 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
444 info.CanBeGlobal = true;
448 // Sort the layout by alignment. We have to use a stable sort here
449 // to get reproducible results. There should probably be an
450 // llvm::array_pod_stable_sort.
451 std::stable_sort(layout.begin(), layout.end());
453 // Needed for blocks layout info.
454 info.BlockHeaderForcedGapOffset = info.BlockSize;
455 info.BlockHeaderForcedGapSize = CharUnits::Zero();
457 CharUnits &blockSize = info.BlockSize;
458 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
460 // Assuming that the first byte in the header is maximally aligned,
461 // get the alignment of the first byte following the header.
462 CharUnits endAlign = getLowBit(blockSize);
464 // If the end of the header isn't satisfactorily aligned for the
465 // maximum thing, look for things that are okay with the header-end
466 // alignment, and keep appending them until we get something that's
467 // aligned right. This algorithm is only guaranteed optimal if
468 // that condition is satisfied at some point; otherwise we can get
470 // header // next byte has alignment 4
471 // something_with_size_5; // next byte has alignment 1
472 // something_with_alignment_8;
473 // which has 7 bytes of padding, as opposed to the naive solution
474 // which might have less (?).
475 if (endAlign < maxFieldAlign) {
476 SmallVectorImpl<BlockLayoutChunk>::iterator
477 li = layout.begin() + 1, le = layout.end();
479 // Look for something that the header end is already
480 // satisfactorily aligned for.
481 for (; li != le && endAlign < li->Alignment; ++li)
484 // If we found something that's naturally aligned for the end of
485 // the header, keep adding things...
487 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
488 for (; li != le; ++li) {
489 assert(endAlign >= li->Alignment);
491 li->setIndex(info, elementTypes.size(), blockSize);
492 elementTypes.push_back(li->Type);
493 blockSize += li->Size;
494 endAlign = getLowBit(blockSize);
496 // ...until we get to the alignment of the maximum field.
497 if (endAlign >= maxFieldAlign) {
501 // Don't re-append everything we just appended.
502 layout.erase(first, li);
506 assert(endAlign == getLowBit(blockSize));
508 // At this point, we just have to add padding if the end align still
509 // isn't aligned right.
510 if (endAlign < maxFieldAlign) {
511 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
512 CharUnits padding = newBlockSize - blockSize;
514 // If we haven't yet added any fields, remember that there was an
515 // initial gap; this need to go into the block layout bit map.
516 if (blockSize == info.BlockHeaderForcedGapOffset) {
517 info.BlockHeaderForcedGapSize = padding;
520 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
521 padding.getQuantity()));
522 blockSize = newBlockSize;
523 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
526 assert(endAlign >= maxFieldAlign);
527 assert(endAlign == getLowBit(blockSize));
528 // Slam everything else on now. This works because they have
529 // strictly decreasing alignment and we expect that size is always a
530 // multiple of alignment.
531 for (SmallVectorImpl<BlockLayoutChunk>::iterator
532 li = layout.begin(), le = layout.end(); li != le; ++li) {
533 if (endAlign < li->Alignment) {
534 // size may not be multiple of alignment. This can only happen with
535 // an over-aligned variable. We will be adding a padding field to
536 // make the size be multiple of alignment.
537 CharUnits padding = li->Alignment - endAlign;
538 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
539 padding.getQuantity()));
540 blockSize += padding;
541 endAlign = getLowBit(blockSize);
543 assert(endAlign >= li->Alignment);
544 li->setIndex(info, elementTypes.size(), blockSize);
545 elementTypes.push_back(li->Type);
546 blockSize += li->Size;
547 endAlign = getLowBit(blockSize);
551 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
554 /// Enter the scope of a block. This should be run at the entrance to
555 /// a full-expression so that the block's cleanups are pushed at the
556 /// right place in the stack.
557 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
558 assert(CGF.HaveInsertPoint());
560 // Allocate the block info and place it at the head of the list.
561 CGBlockInfo &blockInfo =
562 *new CGBlockInfo(block, CGF.CurFn->getName());
563 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
564 CGF.FirstBlockInfo = &blockInfo;
566 // Compute information about the layout, etc., of this block,
567 // pushing cleanups as necessary.
568 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
570 // Nothing else to do if it can be global.
571 if (blockInfo.CanBeGlobal) return;
573 // Make the allocation for the block.
574 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
575 blockInfo.BlockAlign, "block");
577 // If there are cleanups to emit, enter them (but inactive).
578 if (!blockInfo.NeedsCopyDispose) return;
580 // Walk through the captures (in order) and find the ones not
581 // captured by constant.
582 for (const auto &CI : block->captures()) {
583 // Ignore __block captures; there's nothing special in the
584 // on-stack block that we need to do for them.
585 if (CI.isByRef()) continue;
587 // Ignore variables that are constant-captured.
588 const VarDecl *variable = CI.getVariable();
589 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
590 if (capture.isConstant()) continue;
592 // Ignore objects that aren't destructed.
593 QualType::DestructionKind dtorKind =
594 variable->getType().isDestructedType();
595 if (dtorKind == QualType::DK_none) continue;
597 CodeGenFunction::Destroyer *destroyer;
599 // Block captures count as local values and have imprecise semantics.
600 // They also can't be arrays, so need to worry about that.
601 if (dtorKind == QualType::DK_objc_strong_lifetime) {
602 destroyer = CodeGenFunction::destroyARCStrongImprecise;
604 destroyer = CGF.getDestroyer(dtorKind);
607 // GEP down to the address.
608 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
610 capture.getOffset());
612 // We can use that GEP as the dominating IP.
613 if (!blockInfo.DominatingIP)
614 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
616 CleanupKind cleanupKind = InactiveNormalCleanup;
617 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
618 if (useArrayEHCleanup)
619 cleanupKind = InactiveNormalAndEHCleanup;
621 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
622 destroyer, useArrayEHCleanup);
624 // Remember where that cleanup was.
625 capture.setCleanup(CGF.EHStack.stable_begin());
629 /// Enter a full-expression with a non-trivial number of objects to
630 /// clean up. This is in this file because, at the moment, the only
631 /// kind of cleanup object is a BlockDecl*.
632 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
633 assert(E->getNumObjects() != 0);
634 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
635 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
636 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
637 enterBlockScope(*this, *i);
641 /// Find the layout for the given block in a linked list and remove it.
642 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
643 const BlockDecl *block) {
645 assert(head && *head);
646 CGBlockInfo *cur = *head;
648 // If this is the block we're looking for, splice it out of the list.
649 if (cur->getBlockDecl() == block) {
650 *head = cur->NextBlockInfo;
654 head = &cur->NextBlockInfo;
658 /// Destroy a chain of block layouts.
659 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
660 assert(head && "destroying an empty chain");
662 CGBlockInfo *cur = head;
663 head = cur->NextBlockInfo;
665 } while (head != nullptr);
668 /// Emit a block literal expression in the current function.
669 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
670 // If the block has no captures, we won't have a pre-computed
672 if (!blockExpr->getBlockDecl()->hasCaptures()) {
673 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
674 computeBlockInfo(CGM, this, blockInfo);
675 blockInfo.BlockExpression = blockExpr;
676 return EmitBlockLiteral(blockInfo);
679 // Find the block info for this block and take ownership of it.
680 std::unique_ptr<CGBlockInfo> blockInfo;
681 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
682 blockExpr->getBlockDecl()));
684 blockInfo->BlockExpression = blockExpr;
685 return EmitBlockLiteral(*blockInfo);
688 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
689 // Using the computed layout, generate the actual block function.
690 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
691 llvm::Constant *blockFn
692 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
695 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
697 // If there is nothing to capture, we can emit this as a global block.
698 if (blockInfo.CanBeGlobal)
699 return buildGlobalBlock(CGM, blockInfo, blockFn);
701 // Otherwise, we have to emit this as a local block.
703 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
704 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
706 // Build the block descriptor.
707 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
709 Address blockAddr = blockInfo.LocalAddress;
710 assert(blockAddr.isValid() && "block has no address!");
712 // Compute the initial on-stack block flags.
713 BlockFlags flags = BLOCK_HAS_SIGNATURE;
714 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
715 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
716 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
717 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
720 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
721 return Builder.CreateStructGEP(blockAddr, index, offset, name);
724 [&](llvm::Value *value, unsigned index, CharUnits offset,
726 Builder.CreateStore(value, projectField(index, offset, name));
729 // Initialize the block header.
731 // We assume all the header fields are densely packed.
734 auto addHeaderField =
735 [&](llvm::Value *value, CharUnits size, const Twine &name) {
736 storeField(value, index, offset, name);
741 addHeaderField(isa, getPointerSize(), "block.isa");
742 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
743 getIntSize(), "block.flags");
744 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
745 getIntSize(), "block.reserved");
746 addHeaderField(blockFn, getPointerSize(), "block.invoke");
747 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
750 // Finally, capture all the values into the block.
751 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
754 if (blockDecl->capturesCXXThis()) {
755 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
756 "block.captured-this.addr");
757 Builder.CreateStore(LoadCXXThis(), addr);
760 // Next, captured variables.
761 for (const auto &CI : blockDecl->captures()) {
762 const VarDecl *variable = CI.getVariable();
763 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
765 // Ignore constant captures.
766 if (capture.isConstant()) continue;
768 QualType type = variable->getType();
770 // This will be a [[type]]*, except that a byref entry will just be
773 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
775 // Compute the address of the thing we're going to move into the
777 Address src = Address::invalid();
778 if (BlockInfo && CI.isNested()) {
779 // We need to use the capture from the enclosing block.
780 const CGBlockInfo::Capture &enclosingCapture =
781 BlockInfo->getCapture(variable);
783 // This is a [[type]]*, except that a byref entry wil just be an i8**.
784 src = Builder.CreateStructGEP(LoadBlockStruct(),
785 enclosingCapture.getIndex(),
786 enclosingCapture.getOffset(),
787 "block.capture.addr");
788 } else if (blockDecl->isConversionFromLambda()) {
789 // The lambda capture in a lambda's conversion-to-block-pointer is
790 // special; we'll simply emit it directly.
791 src = Address::invalid();
793 // Just look it up in the locals map, which will give us back a
794 // [[type]]*. If that doesn't work, do the more elaborate DRE
796 auto it = LocalDeclMap.find(variable);
797 if (it != LocalDeclMap.end()) {
801 const_cast<VarDecl *>(variable),
802 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
803 VK_LValue, SourceLocation());
804 src = EmitDeclRefLValue(&declRef).getAddress();
808 // For byrefs, we just write the pointer to the byref struct into
809 // the block field. There's no need to chase the forwarding
810 // pointer at this point, since we're building something that will
811 // live a shorter life than the stack byref anyway.
813 // Get a void* that points to the byref struct.
814 llvm::Value *byrefPointer;
816 byrefPointer = Builder.CreateLoad(src, "byref.capture");
818 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
820 // Write that void* into the capture field.
821 Builder.CreateStore(byrefPointer, blockField);
823 // If we have a copy constructor, evaluate that into the block field.
824 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
825 if (blockDecl->isConversionFromLambda()) {
826 // If we have a lambda conversion, emit the expression
827 // directly into the block instead.
829 AggValueSlot::forAddr(blockField, Qualifiers(),
830 AggValueSlot::IsDestructed,
831 AggValueSlot::DoesNotNeedGCBarriers,
832 AggValueSlot::IsNotAliased);
833 EmitAggExpr(copyExpr, Slot);
835 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
838 // If it's a reference variable, copy the reference into the block field.
839 } else if (type->isReferenceType()) {
840 llvm::Value *ref = Builder.CreateLoad(src, "ref.val");
841 Builder.CreateStore(ref, blockField);
843 // If this is an ARC __strong block-pointer variable, don't do a
846 // TODO: this can be generalized into the normal initialization logic:
847 // we should never need to do a block-copy when initializing a local
848 // variable, because the local variable's lifetime should be strictly
849 // contained within the stack block's.
850 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
851 type->isBlockPointerType()) {
852 // Load the block and do a simple retain.
853 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
854 value = EmitARCRetainNonBlock(value);
856 // Do a primitive store to the block field.
857 Builder.CreateStore(value, blockField);
859 // Otherwise, fake up a POD copy into the block field.
861 // Fake up a new variable so that EmitScalarInit doesn't think
862 // we're referring to the variable in its own initializer.
863 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
864 SourceLocation(), /*name*/ nullptr,
867 // We use one of these or the other depending on whether the
868 // reference is nested.
869 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
870 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
871 type, VK_LValue, SourceLocation());
873 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
874 &declRef, VK_RValue);
875 // FIXME: Pass a specific location for the expr init so that the store is
876 // attributed to a reasonable location - otherwise it may be attributed to
877 // locations of subexpressions in the initialization.
878 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
879 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
880 /*captured by init*/ false);
883 // Activate the cleanup if layout pushed one.
885 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
886 if (cleanup.isValid())
887 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
891 // Cast to the converted block-pointer type, which happens (somewhat
892 // unfortunately) to be a pointer to function type.
893 llvm::Value *result =
894 Builder.CreateBitCast(blockAddr.getPointer(),
895 ConvertType(blockInfo.getBlockExpr()->getType()));
901 llvm::Type *CodeGenModule::getBlockDescriptorType() {
902 if (BlockDescriptorType)
903 return BlockDescriptorType;
905 llvm::Type *UnsignedLongTy =
906 getTypes().ConvertType(getContext().UnsignedLongTy);
908 // struct __block_descriptor {
909 // unsigned long reserved;
910 // unsigned long block_size;
912 // // later, the following will be added
915 // void (*copyHelper)();
916 // void (*copyHelper)();
917 // } helpers; // !!! optional
919 // const char *signature; // the block signature
920 // const char *layout; // reserved
922 BlockDescriptorType =
923 llvm::StructType::create("struct.__block_descriptor",
924 UnsignedLongTy, UnsignedLongTy, nullptr);
926 // Now form a pointer to that.
927 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
928 return BlockDescriptorType;
931 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
932 if (GenericBlockLiteralType)
933 return GenericBlockLiteralType;
935 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
937 // struct __block_literal_generic {
941 // void (*__invoke)(void *);
942 // struct __block_descriptor *__descriptor;
944 GenericBlockLiteralType =
945 llvm::StructType::create("struct.__block_literal_generic",
946 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
947 BlockDescPtrTy, nullptr);
949 return GenericBlockLiteralType;
952 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
953 ReturnValueSlot ReturnValue) {
954 const BlockPointerType *BPT =
955 E->getCallee()->getType()->getAs<BlockPointerType>();
957 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
959 // Get a pointer to the generic block literal.
960 llvm::Type *BlockLiteralTy =
961 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
963 // Bitcast the callee to a block literal.
964 llvm::Value *BlockLiteral =
965 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
967 // Get the function pointer from the literal.
968 llvm::Value *FuncPtr =
969 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
971 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
973 // Add the block literal.
975 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
977 QualType FnType = BPT->getPointeeType();
979 // And the rest of the arguments.
980 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
982 // Load the function.
983 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
985 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
986 const CGFunctionInfo &FnInfo =
987 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
989 // Cast the function pointer to the right type.
990 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
992 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
993 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
995 // And call the block.
996 return EmitCall(FnInfo, Func, ReturnValue, Args);
999 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1001 assert(BlockInfo && "evaluating block ref without block information?");
1002 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1004 // Handle constant captures.
1005 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1008 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1009 capture.getOffset(), "block.capture.addr");
1012 // addr should be a void** right now. Load, then cast the result
1015 auto &byrefInfo = getBlockByrefInfo(variable);
1016 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1018 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1019 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1021 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1022 variable->getName());
1025 if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1026 addr = EmitLoadOfReference(addr, refType);
1033 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1035 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1036 blockInfo.BlockExpression = blockExpr;
1038 // Compute information about the layout, etc., of this block.
1039 computeBlockInfo(*this, nullptr, blockInfo);
1041 // Using that metadata, generate the actual block function.
1042 llvm::Constant *blockFn;
1044 CodeGenFunction::DeclMapTy LocalDeclMap;
1045 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1050 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1052 return buildGlobalBlock(*this, blockInfo, blockFn);
1055 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1056 const CGBlockInfo &blockInfo,
1057 llvm::Constant *blockFn) {
1058 assert(blockInfo.CanBeGlobal);
1060 // Generate the constants for the block literal initializer.
1061 llvm::Constant *fields[BlockHeaderSize];
1064 fields[0] = CGM.getNSConcreteGlobalBlock();
1067 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1068 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1070 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1073 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1076 fields[3] = blockFn;
1079 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1081 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1083 llvm::GlobalVariable *literal =
1084 new llvm::GlobalVariable(CGM.getModule(),
1087 llvm::GlobalVariable::InternalLinkage,
1089 "__block_literal_global");
1090 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1092 // Return a constant of the appropriately-casted type.
1093 llvm::Type *requiredType =
1094 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1095 return llvm::ConstantExpr::getBitCast(literal, requiredType);
1098 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1101 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1103 llvm::Value *localAddr = nullptr;
1104 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1105 // Allocate a stack slot to let the debug info survive the RA.
1106 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1107 Builder.CreateStore(arg, alloc);
1108 localAddr = Builder.CreateLoad(alloc);
1111 if (CGDebugInfo *DI = getDebugInfo()) {
1112 if (CGM.getCodeGenOpts().getDebugInfo()
1113 >= CodeGenOptions::LimitedDebugInfo) {
1114 DI->setLocation(D->getLocation());
1115 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1116 localAddr, Builder);
1120 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1121 ApplyDebugLocation Scope(*this, StartLoc);
1123 // Instead of messing around with LocalDeclMap, just set the value
1124 // directly as BlockPointer.
1125 BlockPointer = Builder.CreateBitCast(arg,
1126 BlockInfo->StructureType->getPointerTo(),
1130 Address CodeGenFunction::LoadBlockStruct() {
1131 assert(BlockInfo && "not in a block invocation function!");
1132 assert(BlockPointer && "no block pointer set!");
1133 return Address(BlockPointer, BlockInfo->BlockAlign);
1137 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1138 const CGBlockInfo &blockInfo,
1139 const DeclMapTy &ldm,
1140 bool IsLambdaConversionToBlock) {
1141 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1145 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1147 BlockInfo = &blockInfo;
1149 // Arrange for local static and local extern declarations to appear
1150 // to be local to this function as well, in case they're directly
1151 // referenced in a block.
1152 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1153 const auto *var = dyn_cast<VarDecl>(i->first);
1154 if (var && !var->hasLocalStorage())
1155 setAddrOfLocalVar(var, i->second);
1158 // Begin building the function declaration.
1160 // Build the argument list.
1161 FunctionArgList args;
1163 // The first argument is the block pointer. Just take it as a void*
1164 // and cast it later.
1165 QualType selfTy = getContext().VoidPtrTy;
1166 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1168 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1169 SourceLocation(), II, selfTy);
1170 args.push_back(&selfDecl);
1172 // Now add the rest of the parameters.
1173 args.append(blockDecl->param_begin(), blockDecl->param_end());
1175 // Create the function declaration.
1176 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1177 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1178 fnType->getReturnType(), args, fnType->getExtInfo(),
1179 fnType->isVariadic());
1180 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1181 blockInfo.UsesStret = true;
1183 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1185 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1186 llvm::Function *fn = llvm::Function::Create(
1187 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1188 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1190 // Begin generating the function.
1191 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1192 blockDecl->getLocation(),
1193 blockInfo.getBlockExpr()->getBody()->getLocStart());
1195 // Okay. Undo some of what StartFunction did.
1197 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1198 // won't delete the dbg.declare intrinsics for captured variables.
1199 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1200 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1201 // Allocate a stack slot for it, so we can point the debugger to it
1202 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1205 // Set the DebugLocation to empty, so the store is recognized as a
1206 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1207 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1208 Builder.CreateStore(BlockPointer, Alloca);
1209 BlockPointerDbgLoc = Alloca.getPointer();
1212 // If we have a C++ 'this' reference, go ahead and force it into
1214 if (blockDecl->capturesCXXThis()) {
1216 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1217 blockInfo.CXXThisOffset, "block.captured-this");
1218 CXXThisValue = Builder.CreateLoad(addr, "this");
1221 // Also force all the constant captures.
1222 for (const auto &CI : blockDecl->captures()) {
1223 const VarDecl *variable = CI.getVariable();
1224 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1225 if (!capture.isConstant()) continue;
1227 CharUnits align = getContext().getDeclAlign(variable);
1229 CreateMemTemp(variable->getType(), align, "block.captured-const");
1231 Builder.CreateStore(capture.getConstant(), alloca);
1233 setAddrOfLocalVar(variable, alloca);
1236 // Save a spot to insert the debug information for all the DeclRefExprs.
1237 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1238 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1241 if (IsLambdaConversionToBlock)
1242 EmitLambdaBlockInvokeBody();
1244 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1245 incrementProfileCounter(blockDecl->getBody());
1246 EmitStmt(blockDecl->getBody());
1249 // Remember where we were...
1250 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1252 // Go back to the entry.
1254 Builder.SetInsertPoint(entry, entry_ptr);
1256 // Emit debug information for all the DeclRefExprs.
1257 // FIXME: also for 'this'
1258 if (CGDebugInfo *DI = getDebugInfo()) {
1259 for (const auto &CI : blockDecl->captures()) {
1260 const VarDecl *variable = CI.getVariable();
1261 DI->EmitLocation(Builder, variable->getLocation());
1263 if (CGM.getCodeGenOpts().getDebugInfo()
1264 >= CodeGenOptions::LimitedDebugInfo) {
1265 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1266 if (capture.isConstant()) {
1267 auto addr = LocalDeclMap.find(variable)->second;
1268 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1273 DI->EmitDeclareOfBlockDeclRefVariable(
1274 variable, BlockPointerDbgLoc, Builder, blockInfo,
1275 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1278 // Recover location if it was changed in the above loop.
1279 DI->EmitLocation(Builder,
1280 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1283 // And resume where we left off.
1284 if (resume == nullptr)
1285 Builder.ClearInsertionPoint();
1287 Builder.SetInsertPoint(resume);
1289 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1295 notes.push_back(HelperInfo());
1296 HelperInfo ¬e = notes.back();
1297 note.index = capture.getIndex();
1298 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1299 note.cxxbar_import = ci->getCopyExpr();
1301 if (ci->isByRef()) {
1302 note.flag = BLOCK_FIELD_IS_BYREF;
1303 if (type.isObjCGCWeak())
1304 note.flag |= BLOCK_FIELD_IS_WEAK;
1305 } else if (type->isBlockPointerType()) {
1306 note.flag = BLOCK_FIELD_IS_BLOCK;
1308 note.flag = BLOCK_FIELD_IS_OBJECT;
1312 /// Generate the copy-helper function for a block closure object:
1313 /// static void block_copy_helper(block_t *dst, block_t *src);
1314 /// The runtime will have previously initialized 'dst' by doing a
1315 /// bit-copy of 'src'.
1317 /// Note that this copies an entire block closure object to the heap;
1318 /// it should not be confused with a 'byref copy helper', which moves
1319 /// the contents of an individual __block variable to the heap.
1321 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1322 ASTContext &C = getContext();
1324 FunctionArgList args;
1325 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1327 args.push_back(&dstDecl);
1328 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1330 args.push_back(&srcDecl);
1332 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1333 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1335 // FIXME: it would be nice if these were mergeable with things with
1336 // identical semantics.
1337 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1339 llvm::Function *Fn =
1340 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1341 "__copy_helper_block_", &CGM.getModule());
1344 = &CGM.getContext().Idents.get("__copy_helper_block_");
1346 FunctionDecl *FD = FunctionDecl::Create(C,
1347 C.getTranslationUnitDecl(),
1349 SourceLocation(), II, C.VoidTy,
1354 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1356 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1357 StartFunction(FD, C.VoidTy, Fn, FI, args);
1358 // Create a scope with an artificial location for the body of this function.
1359 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1360 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1362 Address src = GetAddrOfLocalVar(&srcDecl);
1363 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1364 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1366 Address dst = GetAddrOfLocalVar(&dstDecl);
1367 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1368 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1370 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1372 for (const auto &CI : blockDecl->captures()) {
1373 const VarDecl *variable = CI.getVariable();
1374 QualType type = variable->getType();
1376 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1377 if (capture.isConstant()) continue;
1379 const Expr *copyExpr = CI.getCopyExpr();
1380 BlockFieldFlags flags;
1382 bool useARCWeakCopy = false;
1383 bool useARCStrongCopy = false;
1386 assert(!CI.isByRef());
1387 // don't bother computing flags
1389 } else if (CI.isByRef()) {
1390 flags = BLOCK_FIELD_IS_BYREF;
1391 if (type.isObjCGCWeak())
1392 flags |= BLOCK_FIELD_IS_WEAK;
1394 } else if (type->isObjCRetainableType()) {
1395 flags = BLOCK_FIELD_IS_OBJECT;
1396 bool isBlockPointer = type->isBlockPointerType();
1398 flags = BLOCK_FIELD_IS_BLOCK;
1400 // Special rules for ARC captures:
1401 Qualifiers qs = type.getQualifiers();
1403 // We need to register __weak direct captures with the runtime.
1404 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1405 useARCWeakCopy = true;
1407 // We need to retain the copied value for __strong direct captures.
1408 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1409 // If it's a block pointer, we have to copy the block and
1410 // assign that to the destination pointer, so we might as
1411 // well use _Block_object_assign. Otherwise we can avoid that.
1412 if (!isBlockPointer)
1413 useARCStrongCopy = true;
1415 // Non-ARC captures of retainable pointers are strong and
1416 // therefore require a call to _Block_object_assign.
1417 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1420 // Otherwise the memcpy is fine.
1425 // For all other types, the memcpy is fine.
1430 unsigned index = capture.getIndex();
1431 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1432 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1434 // If there's an explicit copy expression, we do that.
1436 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1437 } else if (useARCWeakCopy) {
1438 EmitARCCopyWeak(dstField, srcField);
1440 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1441 if (useARCStrongCopy) {
1442 // At -O0, store null into the destination field (so that the
1443 // storeStrong doesn't over-release) and then call storeStrong.
1444 // This is a workaround to not having an initStrong call.
1445 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1446 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1447 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1448 Builder.CreateStore(null, dstField);
1449 EmitARCStoreStrongCall(dstField, srcValue, true);
1451 // With optimization enabled, take advantage of the fact that
1452 // the blocks runtime guarantees a memcpy of the block data, and
1453 // just emit a retain of the src field.
1455 EmitARCRetainNonBlock(srcValue);
1457 // We don't need this anymore, so kill it. It's not quite
1458 // worth the annoyance to avoid creating it in the first place.
1459 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1462 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1463 llvm::Value *dstAddr =
1464 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1465 llvm::Value *args[] = {
1466 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1469 bool copyCanThrow = false;
1470 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1471 const Expr *copyExpr =
1472 CGM.getContext().getBlockVarCopyInits(variable);
1474 copyCanThrow = true; // FIXME: reuse the noexcept logic
1479 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1481 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1489 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1492 /// Generate the destroy-helper function for a block closure object:
1493 /// static void block_destroy_helper(block_t *theBlock);
1495 /// Note that this destroys a heap-allocated block closure object;
1496 /// it should not be confused with a 'byref destroy helper', which
1497 /// destroys the heap-allocated contents of an individual __block
1500 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1501 ASTContext &C = getContext();
1503 FunctionArgList args;
1504 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1506 args.push_back(&srcDecl);
1508 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1509 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1511 // FIXME: We'd like to put these into a mergable by content, with
1512 // internal linkage.
1513 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1515 llvm::Function *Fn =
1516 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1517 "__destroy_helper_block_", &CGM.getModule());
1520 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1522 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1524 SourceLocation(), II, C.VoidTy,
1528 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1530 // Create a scope with an artificial location for the body of this function.
1531 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1532 StartFunction(FD, C.VoidTy, Fn, FI, args);
1533 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1535 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1537 Address src = GetAddrOfLocalVar(&srcDecl);
1538 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1539 src = Builder.CreateBitCast(src, structPtrTy, "block");
1541 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1543 CodeGenFunction::RunCleanupsScope cleanups(*this);
1545 for (const auto &CI : blockDecl->captures()) {
1546 const VarDecl *variable = CI.getVariable();
1547 QualType type = variable->getType();
1549 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1550 if (capture.isConstant()) continue;
1552 BlockFieldFlags flags;
1553 const CXXDestructorDecl *dtor = nullptr;
1555 bool useARCWeakDestroy = false;
1556 bool useARCStrongDestroy = false;
1559 flags = BLOCK_FIELD_IS_BYREF;
1560 if (type.isObjCGCWeak())
1561 flags |= BLOCK_FIELD_IS_WEAK;
1562 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1563 if (record->hasTrivialDestructor())
1565 dtor = record->getDestructor();
1566 } else if (type->isObjCRetainableType()) {
1567 flags = BLOCK_FIELD_IS_OBJECT;
1568 if (type->isBlockPointerType())
1569 flags = BLOCK_FIELD_IS_BLOCK;
1571 // Special rules for ARC captures.
1572 Qualifiers qs = type.getQualifiers();
1574 // Use objc_storeStrong for __strong direct captures; the
1575 // dynamic tools really like it when we do this.
1576 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1577 useARCStrongDestroy = true;
1579 // Support __weak direct captures.
1580 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1581 useARCWeakDestroy = true;
1583 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1584 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1587 // Otherwise, we have nothing to do.
1596 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1598 // If there's an explicit copy expression, we do that.
1600 PushDestructorCleanup(dtor, srcField);
1602 // If this is a __weak capture, emit the release directly.
1603 } else if (useARCWeakDestroy) {
1604 EmitARCDestroyWeak(srcField);
1606 // Destroy strong objects with a call if requested.
1607 } else if (useARCStrongDestroy) {
1608 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1610 // Otherwise we call _Block_object_dispose. It wouldn't be too
1611 // hard to just emit this as a cleanup if we wanted to make sure
1612 // that things were done in reverse.
1614 llvm::Value *value = Builder.CreateLoad(srcField);
1615 value = Builder.CreateBitCast(value, VoidPtrTy);
1616 BuildBlockRelease(value, flags);
1620 cleanups.ForceCleanup();
1624 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1629 /// Emits the copy/dispose helper functions for a __block object of id type.
1630 class ObjectByrefHelpers final : public BlockByrefHelpers {
1631 BlockFieldFlags Flags;
1634 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1635 : BlockByrefHelpers(alignment), Flags(flags) {}
1637 void emitCopy(CodeGenFunction &CGF, Address destField,
1638 Address srcField) override {
1639 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1641 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1642 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1644 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1646 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1647 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1649 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1650 CGF.EmitNounwindRuntimeCall(fn, args);
1653 void emitDispose(CodeGenFunction &CGF, Address field) override {
1654 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1655 llvm::Value *value = CGF.Builder.CreateLoad(field);
1657 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1660 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1661 id.AddInteger(Flags.getBitMask());
1665 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1666 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1668 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1670 void emitCopy(CodeGenFunction &CGF, Address destField,
1671 Address srcField) override {
1672 CGF.EmitARCMoveWeak(destField, srcField);
1675 void emitDispose(CodeGenFunction &CGF, Address field) override {
1676 CGF.EmitARCDestroyWeak(field);
1679 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1680 // 0 is distinguishable from all pointers and byref flags
1685 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1686 /// that's not of block-pointer type.
1687 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1689 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1691 void emitCopy(CodeGenFunction &CGF, Address destField,
1692 Address srcField) override {
1693 // Do a "move" by copying the value and then zeroing out the old
1696 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1699 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1701 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1702 CGF.Builder.CreateStore(null, destField);
1703 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1704 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1707 CGF.Builder.CreateStore(value, destField);
1708 CGF.Builder.CreateStore(null, srcField);
1711 void emitDispose(CodeGenFunction &CGF, Address field) override {
1712 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1715 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1716 // 1 is distinguishable from all pointers and byref flags
1721 /// Emits the copy/dispose helpers for an ARC __block __strong
1722 /// variable that's of block-pointer type.
1723 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1725 ARCStrongBlockByrefHelpers(CharUnits alignment)
1726 : BlockByrefHelpers(alignment) {}
1728 void emitCopy(CodeGenFunction &CGF, Address destField,
1729 Address srcField) override {
1730 // Do the copy with objc_retainBlock; that's all that
1731 // _Block_object_assign would do anyway, and we'd have to pass the
1732 // right arguments to make sure it doesn't get no-op'ed.
1733 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1734 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1735 CGF.Builder.CreateStore(copy, destField);
1738 void emitDispose(CodeGenFunction &CGF, Address field) override {
1739 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1742 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1743 // 2 is distinguishable from all pointers and byref flags
1748 /// Emits the copy/dispose helpers for a __block variable with a
1749 /// nontrivial copy constructor or destructor.
1750 class CXXByrefHelpers final : public BlockByrefHelpers {
1752 const Expr *CopyExpr;
1755 CXXByrefHelpers(CharUnits alignment, QualType type,
1756 const Expr *copyExpr)
1757 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1759 bool needsCopy() const override { return CopyExpr != nullptr; }
1760 void emitCopy(CodeGenFunction &CGF, Address destField,
1761 Address srcField) override {
1762 if (!CopyExpr) return;
1763 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1766 void emitDispose(CodeGenFunction &CGF, Address field) override {
1767 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1768 CGF.PushDestructorCleanup(VarType, field);
1769 CGF.PopCleanupBlocks(cleanupDepth);
1772 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1773 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1776 } // end anonymous namespace
1778 static llvm::Constant *
1779 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1780 BlockByrefHelpers &generator) {
1781 ASTContext &Context = CGF.getContext();
1783 QualType R = Context.VoidTy;
1785 FunctionArgList args;
1786 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1788 args.push_back(&dst);
1790 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1792 args.push_back(&src);
1794 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1795 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1797 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1799 // FIXME: We'd like to put these into a mergable by content, with
1800 // internal linkage.
1801 llvm::Function *Fn =
1802 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1803 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1806 = &Context.Idents.get("__Block_byref_object_copy_");
1808 FunctionDecl *FD = FunctionDecl::Create(Context,
1809 Context.getTranslationUnitDecl(),
1811 SourceLocation(), II, R, nullptr,
1815 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1817 CGF.StartFunction(FD, R, Fn, FI, args);
1819 if (generator.needsCopy()) {
1820 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1823 Address destField = CGF.GetAddrOfLocalVar(&dst);
1824 destField = Address(CGF.Builder.CreateLoad(destField),
1825 byrefInfo.ByrefAlignment);
1826 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1827 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1831 Address srcField = CGF.GetAddrOfLocalVar(&src);
1832 srcField = Address(CGF.Builder.CreateLoad(srcField),
1833 byrefInfo.ByrefAlignment);
1834 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1835 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1838 generator.emitCopy(CGF, destField, srcField);
1841 CGF.FinishFunction();
1843 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1846 /// Build the copy helper for a __block variable.
1847 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1848 const BlockByrefInfo &byrefInfo,
1849 BlockByrefHelpers &generator) {
1850 CodeGenFunction CGF(CGM);
1851 return generateByrefCopyHelper(CGF, byrefInfo, generator);
1854 /// Generate code for a __block variable's dispose helper.
1855 static llvm::Constant *
1856 generateByrefDisposeHelper(CodeGenFunction &CGF,
1857 const BlockByrefInfo &byrefInfo,
1858 BlockByrefHelpers &generator) {
1859 ASTContext &Context = CGF.getContext();
1860 QualType R = Context.VoidTy;
1862 FunctionArgList args;
1863 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1865 args.push_back(&src);
1867 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1868 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1870 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1872 // FIXME: We'd like to put these into a mergable by content, with
1873 // internal linkage.
1874 llvm::Function *Fn =
1875 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1876 "__Block_byref_object_dispose_",
1877 &CGF.CGM.getModule());
1880 = &Context.Idents.get("__Block_byref_object_dispose_");
1882 FunctionDecl *FD = FunctionDecl::Create(Context,
1883 Context.getTranslationUnitDecl(),
1885 SourceLocation(), II, R, nullptr,
1889 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1891 CGF.StartFunction(FD, R, Fn, FI, args);
1893 if (generator.needsDispose()) {
1894 Address addr = CGF.GetAddrOfLocalVar(&src);
1895 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1896 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1897 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1898 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1900 generator.emitDispose(CGF, addr);
1903 CGF.FinishFunction();
1905 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1908 /// Build the dispose helper for a __block variable.
1909 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1910 const BlockByrefInfo &byrefInfo,
1911 BlockByrefHelpers &generator) {
1912 CodeGenFunction CGF(CGM);
1913 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1916 /// Lazily build the copy and dispose helpers for a __block variable
1917 /// with the given information.
1919 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1921 llvm::FoldingSetNodeID id;
1922 generator.Profile(id);
1925 BlockByrefHelpers *node
1926 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1927 if (node) return static_cast<T*>(node);
1929 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1930 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1932 T *copy = new (CGM.getContext()) T(std::move(generator));
1933 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1937 /// Build the copy and dispose helpers for the given __block variable
1938 /// emission. Places the helpers in the global cache. Returns null
1939 /// if no helpers are required.
1941 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1942 const AutoVarEmission &emission) {
1943 const VarDecl &var = *emission.Variable;
1944 QualType type = var.getType();
1946 auto &byrefInfo = getBlockByrefInfo(&var);
1948 // The alignment we care about for the purposes of uniquing byref
1949 // helpers is the alignment of the actual byref value field.
1950 CharUnits valueAlignment =
1951 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1953 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1954 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1955 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1957 return ::buildByrefHelpers(
1958 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1961 // Otherwise, if we don't have a retainable type, there's nothing to do.
1962 // that the runtime does extra copies.
1963 if (!type->isObjCRetainableType()) return nullptr;
1965 Qualifiers qs = type.getQualifiers();
1967 // If we have lifetime, that dominates.
1968 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1970 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1972 // These are just bits as far as the runtime is concerned.
1973 case Qualifiers::OCL_ExplicitNone:
1974 case Qualifiers::OCL_Autoreleasing:
1977 // Tell the runtime that this is ARC __weak, called by the
1979 case Qualifiers::OCL_Weak:
1980 return ::buildByrefHelpers(CGM, byrefInfo,
1981 ARCWeakByrefHelpers(valueAlignment));
1983 // ARC __strong __block variables need to be retained.
1984 case Qualifiers::OCL_Strong:
1985 // Block pointers need to be copied, and there's no direct
1986 // transfer possible.
1987 if (type->isBlockPointerType()) {
1988 return ::buildByrefHelpers(CGM, byrefInfo,
1989 ARCStrongBlockByrefHelpers(valueAlignment));
1991 // Otherwise, we transfer ownership of the retain from the stack
1994 return ::buildByrefHelpers(CGM, byrefInfo,
1995 ARCStrongByrefHelpers(valueAlignment));
1998 llvm_unreachable("fell out of lifetime switch!");
2001 BlockFieldFlags flags;
2002 if (type->isBlockPointerType()) {
2003 flags |= BLOCK_FIELD_IS_BLOCK;
2004 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2005 type->isObjCObjectPointerType()) {
2006 flags |= BLOCK_FIELD_IS_OBJECT;
2011 if (type.isObjCGCWeak())
2012 flags |= BLOCK_FIELD_IS_WEAK;
2014 return ::buildByrefHelpers(CGM, byrefInfo,
2015 ObjectByrefHelpers(valueAlignment, flags));
2018 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2020 bool followForward) {
2021 auto &info = getBlockByrefInfo(var);
2022 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2025 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2026 const BlockByrefInfo &info,
2028 const llvm::Twine &name) {
2029 // Chase the forwarding address if requested.
2030 if (followForward) {
2031 Address forwardingAddr =
2032 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2033 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2036 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2037 info.FieldOffset, name);
2040 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2045 /// void *__forwarding;
2046 /// int32_t __flags;
2048 /// void *__copy_helper; // only if needed
2049 /// void *__destroy_helper; // only if needed
2050 /// void *__byref_variable_layout;// only if needed
2051 /// char padding[X]; // only if needed
2055 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2056 auto it = BlockByrefInfos.find(D);
2057 if (it != BlockByrefInfos.end())
2060 llvm::StructType *byrefType =
2061 llvm::StructType::create(getLLVMContext(),
2062 "struct.__block_byref_" + D->getNameAsString());
2064 QualType Ty = D->getType();
2067 SmallVector<llvm::Type *, 8> types;
2070 types.push_back(Int8PtrTy);
2071 size += getPointerSize();
2073 // void *__forwarding;
2074 types.push_back(llvm::PointerType::getUnqual(byrefType));
2075 size += getPointerSize();
2078 types.push_back(Int32Ty);
2079 size += CharUnits::fromQuantity(4);
2082 types.push_back(Int32Ty);
2083 size += CharUnits::fromQuantity(4);
2085 // Note that this must match *exactly* the logic in buildByrefHelpers.
2086 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2087 if (hasCopyAndDispose) {
2088 /// void *__copy_helper;
2089 types.push_back(Int8PtrTy);
2090 size += getPointerSize();
2092 /// void *__destroy_helper;
2093 types.push_back(Int8PtrTy);
2094 size += getPointerSize();
2097 bool HasByrefExtendedLayout = false;
2098 Qualifiers::ObjCLifetime Lifetime;
2099 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2100 HasByrefExtendedLayout) {
2101 /// void *__byref_variable_layout;
2102 types.push_back(Int8PtrTy);
2103 size += CharUnits::fromQuantity(PointerSizeInBytes);
2107 llvm::Type *varTy = ConvertTypeForMem(Ty);
2109 bool packed = false;
2110 CharUnits varAlign = getContext().getDeclAlign(D);
2111 CharUnits varOffset = size.RoundUpToAlignment(varAlign);
2113 // We may have to insert padding.
2114 if (varOffset != size) {
2115 llvm::Type *paddingTy =
2116 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2118 types.push_back(paddingTy);
2121 // Conversely, we might have to prevent LLVM from inserting padding.
2122 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2123 > varAlign.getQuantity()) {
2126 types.push_back(varTy);
2128 byrefType->setBody(types, packed);
2130 BlockByrefInfo info;
2131 info.Type = byrefType;
2132 info.FieldIndex = types.size() - 1;
2133 info.FieldOffset = varOffset;
2134 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2136 auto pair = BlockByrefInfos.insert({D, info});
2137 assert(pair.second && "info was inserted recursively?");
2138 return pair.first->second;
2141 /// Initialize the structural components of a __block variable, i.e.
2142 /// everything but the actual object.
2143 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2144 // Find the address of the local.
2145 Address addr = emission.Addr;
2147 // That's an alloca of the byref structure type.
2148 llvm::StructType *byrefType = cast<llvm::StructType>(
2149 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2151 unsigned nextHeaderIndex = 0;
2152 CharUnits nextHeaderOffset;
2153 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2154 const Twine &name) {
2155 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2156 nextHeaderOffset, name);
2157 Builder.CreateStore(value, fieldAddr);
2160 nextHeaderOffset += fieldSize;
2163 // Build the byref helpers if necessary. This is null if we don't need any.
2164 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2166 const VarDecl &D = *emission.Variable;
2167 QualType type = D.getType();
2169 bool HasByrefExtendedLayout;
2170 Qualifiers::ObjCLifetime ByrefLifetime;
2171 bool ByRefHasLifetime =
2172 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2176 // Initialize the 'isa', which is just 0 or 1.
2178 if (type.isObjCGCWeak())
2180 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2181 storeHeaderField(V, getPointerSize(), "byref.isa");
2183 // Store the address of the variable into its own forwarding pointer.
2184 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2187 // c) the flags field is set to either 0 if no helper functions are
2188 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2190 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2191 if (ByRefHasLifetime) {
2192 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2193 else switch (ByrefLifetime) {
2194 case Qualifiers::OCL_Strong:
2195 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2197 case Qualifiers::OCL_Weak:
2198 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2200 case Qualifiers::OCL_ExplicitNone:
2201 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2203 case Qualifiers::OCL_None:
2204 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2205 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2210 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2211 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2212 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2213 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2214 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2215 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2216 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2217 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2218 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2219 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2220 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2221 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2222 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2223 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2224 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2225 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2230 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2231 getIntSize(), "byref.flags");
2233 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2234 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2235 storeHeaderField(V, getIntSize(), "byref.size");
2238 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2239 "byref.copyHelper");
2240 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2241 "byref.disposeHelper");
2244 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2245 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2246 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2250 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2251 llvm::Value *F = CGM.getBlockObjectDispose();
2252 llvm::Value *args[] = {
2253 Builder.CreateBitCast(V, Int8PtrTy),
2254 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2256 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2260 /// Release a __block variable.
2261 struct CallBlockRelease final : EHScopeStack::Cleanup {
2263 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2265 void Emit(CodeGenFunction &CGF, Flags flags) override {
2266 // Should we be passing FIELD_IS_WEAK here?
2267 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2270 } // end anonymous namespace
2272 /// Enter a cleanup to destroy a __block variable. Note that this
2273 /// cleanup should be a no-op if the variable hasn't left the stack
2274 /// yet; if a cleanup is required for the variable itself, that needs
2275 /// to be done externally.
2276 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2277 // We don't enter this cleanup if we're in pure-GC mode.
2278 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2281 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2282 emission.Addr.getPointer());
2285 /// Adjust the declaration of something from the blocks API.
2286 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2287 llvm::Constant *C) {
2288 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2290 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2291 if (GV->isDeclaration() && GV->hasExternalLinkage())
2292 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2295 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2296 if (BlockObjectDispose)
2297 return BlockObjectDispose;
2299 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2300 llvm::FunctionType *fty
2301 = llvm::FunctionType::get(VoidTy, args, false);
2302 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2303 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2304 return BlockObjectDispose;
2307 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2308 if (BlockObjectAssign)
2309 return BlockObjectAssign;
2311 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2312 llvm::FunctionType *fty
2313 = llvm::FunctionType::get(VoidTy, args, false);
2314 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2315 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2316 return BlockObjectAssign;
2319 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2320 if (NSConcreteGlobalBlock)
2321 return NSConcreteGlobalBlock;
2323 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2324 Int8PtrTy->getPointerTo(),
2326 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2327 return NSConcreteGlobalBlock;
2330 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2331 if (NSConcreteStackBlock)
2332 return NSConcreteStackBlock;
2334 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2335 Int8PtrTy->getPointerTo(),
2337 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2338 return NSConcreteStackBlock;