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 // Return if this is a function paramter. We shouldn't try to
266 // rematerialize default arguments of function parameters.
267 if (isa<ParmVarDecl>(var))
270 QualType type = var->getType();
272 // We can only do this if the variable is const.
273 if (!type.isConstQualified()) return nullptr;
275 // Furthermore, in C++ we have to worry about mutable fields:
276 // C++ [dcl.type.cv]p4:
277 // Except that any class member declared mutable can be
278 // modified, any attempt to modify a const object during its
279 // lifetime results in undefined behavior.
280 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
283 // If the variable doesn't have any initializer (shouldn't this be
284 // invalid?), it's not clear what we should do. Maybe capture as
286 const Expr *init = var->getInit();
287 if (!init) return nullptr;
289 return CGM.EmitConstantInit(*var, CGF);
292 /// Get the low bit of a nonzero character count. This is the
293 /// alignment of the nth byte if the 0th byte is universally aligned.
294 static CharUnits getLowBit(CharUnits v) {
295 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
298 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
299 SmallVectorImpl<llvm::Type*> &elementTypes) {
300 // The header is basically 'struct { void *; int; int; void *; void *; }'.
301 // Assert that that struct is packed.
302 assert(CGM.getIntSize() <= CGM.getPointerSize());
303 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
304 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
306 info.BlockAlign = CGM.getPointerAlign();
307 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
309 assert(elementTypes.empty());
310 elementTypes.push_back(CGM.VoidPtrTy);
311 elementTypes.push_back(CGM.IntTy);
312 elementTypes.push_back(CGM.IntTy);
313 elementTypes.push_back(CGM.VoidPtrTy);
314 elementTypes.push_back(CGM.getBlockDescriptorType());
316 assert(elementTypes.size() == BlockHeaderSize);
319 /// Compute the layout of the given block. Attempts to lay the block
320 /// out with minimal space requirements.
321 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
323 ASTContext &C = CGM.getContext();
324 const BlockDecl *block = info.getBlockDecl();
326 SmallVector<llvm::Type*, 8> elementTypes;
327 initializeForBlockHeader(CGM, info, elementTypes);
329 if (!block->hasCaptures()) {
331 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
332 info.CanBeGlobal = true;
335 else if (C.getLangOpts().ObjC1 &&
336 CGM.getLangOpts().getGC() == LangOptions::NonGC)
337 info.HasCapturedVariableLayout = true;
339 // Collect the layout chunks.
340 SmallVector<BlockLayoutChunk, 16> layout;
341 layout.reserve(block->capturesCXXThis() +
342 (block->capture_end() - block->capture_begin()));
344 CharUnits maxFieldAlign;
347 if (block->capturesCXXThis()) {
348 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
349 "Can't capture 'this' outside a method");
350 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
352 // Theoretically, this could be in a different address space, so
353 // don't assume standard pointer size/align.
354 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
355 std::pair<CharUnits,CharUnits> tinfo
356 = CGM.getContext().getTypeInfoInChars(thisType);
357 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
359 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
360 Qualifiers::OCL_None,
364 // Next, all the block captures.
365 for (const auto &CI : block->captures()) {
366 const VarDecl *variable = CI.getVariable();
369 // We have to copy/dispose of the __block reference.
370 info.NeedsCopyDispose = true;
372 // Just use void* instead of a pointer to the byref type.
373 CharUnits align = CGM.getPointerAlign();
374 maxFieldAlign = std::max(maxFieldAlign, align);
376 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
377 Qualifiers::OCL_None, &CI,
382 // Otherwise, build a layout chunk with the size and alignment of
384 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
385 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
389 // If we have a lifetime qualifier, honor it for capture purposes.
390 // That includes *not* copying it if it's __unsafe_unretained.
391 Qualifiers::ObjCLifetime lifetime =
392 variable->getType().getObjCLifetime();
395 case Qualifiers::OCL_None: llvm_unreachable("impossible");
396 case Qualifiers::OCL_ExplicitNone:
397 case Qualifiers::OCL_Autoreleasing:
400 case Qualifiers::OCL_Strong:
401 case Qualifiers::OCL_Weak:
402 info.NeedsCopyDispose = true;
405 // Block pointers require copy/dispose. So do Objective-C pointers.
406 } else if (variable->getType()->isObjCRetainableType()) {
407 // But honor the inert __unsafe_unretained qualifier, which doesn't
408 // actually make it into the type system.
409 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
410 lifetime = Qualifiers::OCL_ExplicitNone;
412 info.NeedsCopyDispose = true;
413 // used for mrr below.
414 lifetime = Qualifiers::OCL_Strong;
417 // So do types that require non-trivial copy construction.
418 } else if (CI.hasCopyExpr()) {
419 info.NeedsCopyDispose = true;
420 info.HasCXXObject = true;
422 // And so do types with destructors.
423 } else if (CGM.getLangOpts().CPlusPlus) {
424 if (const CXXRecordDecl *record =
425 variable->getType()->getAsCXXRecordDecl()) {
426 if (!record->hasTrivialDestructor()) {
427 info.HasCXXObject = true;
428 info.NeedsCopyDispose = true;
433 QualType VT = variable->getType();
434 CharUnits size = C.getTypeSizeInChars(VT);
435 CharUnits align = C.getDeclAlign(variable);
437 maxFieldAlign = std::max(maxFieldAlign, align);
439 llvm::Type *llvmType =
440 CGM.getTypes().ConvertTypeForMem(VT);
442 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
445 // If that was everything, we're done here.
446 if (layout.empty()) {
448 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
449 info.CanBeGlobal = true;
453 // Sort the layout by alignment. We have to use a stable sort here
454 // to get reproducible results. There should probably be an
455 // llvm::array_pod_stable_sort.
456 std::stable_sort(layout.begin(), layout.end());
458 // Needed for blocks layout info.
459 info.BlockHeaderForcedGapOffset = info.BlockSize;
460 info.BlockHeaderForcedGapSize = CharUnits::Zero();
462 CharUnits &blockSize = info.BlockSize;
463 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
465 // Assuming that the first byte in the header is maximally aligned,
466 // get the alignment of the first byte following the header.
467 CharUnits endAlign = getLowBit(blockSize);
469 // If the end of the header isn't satisfactorily aligned for the
470 // maximum thing, look for things that are okay with the header-end
471 // alignment, and keep appending them until we get something that's
472 // aligned right. This algorithm is only guaranteed optimal if
473 // that condition is satisfied at some point; otherwise we can get
475 // header // next byte has alignment 4
476 // something_with_size_5; // next byte has alignment 1
477 // something_with_alignment_8;
478 // which has 7 bytes of padding, as opposed to the naive solution
479 // which might have less (?).
480 if (endAlign < maxFieldAlign) {
481 SmallVectorImpl<BlockLayoutChunk>::iterator
482 li = layout.begin() + 1, le = layout.end();
484 // Look for something that the header end is already
485 // satisfactorily aligned for.
486 for (; li != le && endAlign < li->Alignment; ++li)
489 // If we found something that's naturally aligned for the end of
490 // the header, keep adding things...
492 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
493 for (; li != le; ++li) {
494 assert(endAlign >= li->Alignment);
496 li->setIndex(info, elementTypes.size(), blockSize);
497 elementTypes.push_back(li->Type);
498 blockSize += li->Size;
499 endAlign = getLowBit(blockSize);
501 // ...until we get to the alignment of the maximum field.
502 if (endAlign >= maxFieldAlign) {
506 // Don't re-append everything we just appended.
507 layout.erase(first, li);
511 assert(endAlign == getLowBit(blockSize));
513 // At this point, we just have to add padding if the end align still
514 // isn't aligned right.
515 if (endAlign < maxFieldAlign) {
516 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
517 CharUnits padding = newBlockSize - blockSize;
519 // If we haven't yet added any fields, remember that there was an
520 // initial gap; this need to go into the block layout bit map.
521 if (blockSize == info.BlockHeaderForcedGapOffset) {
522 info.BlockHeaderForcedGapSize = padding;
525 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
526 padding.getQuantity()));
527 blockSize = newBlockSize;
528 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
531 assert(endAlign >= maxFieldAlign);
532 assert(endAlign == getLowBit(blockSize));
533 // Slam everything else on now. This works because they have
534 // strictly decreasing alignment and we expect that size is always a
535 // multiple of alignment.
536 for (SmallVectorImpl<BlockLayoutChunk>::iterator
537 li = layout.begin(), le = layout.end(); li != le; ++li) {
538 if (endAlign < li->Alignment) {
539 // size may not be multiple of alignment. This can only happen with
540 // an over-aligned variable. We will be adding a padding field to
541 // make the size be multiple of alignment.
542 CharUnits padding = li->Alignment - endAlign;
543 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
544 padding.getQuantity()));
545 blockSize += padding;
546 endAlign = getLowBit(blockSize);
548 assert(endAlign >= li->Alignment);
549 li->setIndex(info, elementTypes.size(), blockSize);
550 elementTypes.push_back(li->Type);
551 blockSize += li->Size;
552 endAlign = getLowBit(blockSize);
556 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
559 /// Enter the scope of a block. This should be run at the entrance to
560 /// a full-expression so that the block's cleanups are pushed at the
561 /// right place in the stack.
562 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
563 assert(CGF.HaveInsertPoint());
565 // Allocate the block info and place it at the head of the list.
566 CGBlockInfo &blockInfo =
567 *new CGBlockInfo(block, CGF.CurFn->getName());
568 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
569 CGF.FirstBlockInfo = &blockInfo;
571 // Compute information about the layout, etc., of this block,
572 // pushing cleanups as necessary.
573 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
575 // Nothing else to do if it can be global.
576 if (blockInfo.CanBeGlobal) return;
578 // Make the allocation for the block.
579 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
580 blockInfo.BlockAlign, "block");
582 // If there are cleanups to emit, enter them (but inactive).
583 if (!blockInfo.NeedsCopyDispose) return;
585 // Walk through the captures (in order) and find the ones not
586 // captured by constant.
587 for (const auto &CI : block->captures()) {
588 // Ignore __block captures; there's nothing special in the
589 // on-stack block that we need to do for them.
590 if (CI.isByRef()) continue;
592 // Ignore variables that are constant-captured.
593 const VarDecl *variable = CI.getVariable();
594 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
595 if (capture.isConstant()) continue;
597 // Ignore objects that aren't destructed.
598 QualType::DestructionKind dtorKind =
599 variable->getType().isDestructedType();
600 if (dtorKind == QualType::DK_none) continue;
602 CodeGenFunction::Destroyer *destroyer;
604 // Block captures count as local values and have imprecise semantics.
605 // They also can't be arrays, so need to worry about that.
606 if (dtorKind == QualType::DK_objc_strong_lifetime) {
607 destroyer = CodeGenFunction::destroyARCStrongImprecise;
609 destroyer = CGF.getDestroyer(dtorKind);
612 // GEP down to the address.
613 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
615 capture.getOffset());
617 // We can use that GEP as the dominating IP.
618 if (!blockInfo.DominatingIP)
619 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
621 CleanupKind cleanupKind = InactiveNormalCleanup;
622 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623 if (useArrayEHCleanup)
624 cleanupKind = InactiveNormalAndEHCleanup;
626 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
627 destroyer, useArrayEHCleanup);
629 // Remember where that cleanup was.
630 capture.setCleanup(CGF.EHStack.stable_begin());
634 /// Enter a full-expression with a non-trivial number of objects to
635 /// clean up. This is in this file because, at the moment, the only
636 /// kind of cleanup object is a BlockDecl*.
637 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
638 assert(E->getNumObjects() != 0);
639 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
640 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
641 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642 enterBlockScope(*this, *i);
646 /// Find the layout for the given block in a linked list and remove it.
647 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
648 const BlockDecl *block) {
650 assert(head && *head);
651 CGBlockInfo *cur = *head;
653 // If this is the block we're looking for, splice it out of the list.
654 if (cur->getBlockDecl() == block) {
655 *head = cur->NextBlockInfo;
659 head = &cur->NextBlockInfo;
663 /// Destroy a chain of block layouts.
664 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
665 assert(head && "destroying an empty chain");
667 CGBlockInfo *cur = head;
668 head = cur->NextBlockInfo;
670 } while (head != nullptr);
673 /// Emit a block literal expression in the current function.
674 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
675 // If the block has no captures, we won't have a pre-computed
677 if (!blockExpr->getBlockDecl()->hasCaptures()) {
678 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
679 computeBlockInfo(CGM, this, blockInfo);
680 blockInfo.BlockExpression = blockExpr;
681 return EmitBlockLiteral(blockInfo);
684 // Find the block info for this block and take ownership of it.
685 std::unique_ptr<CGBlockInfo> blockInfo;
686 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687 blockExpr->getBlockDecl()));
689 blockInfo->BlockExpression = blockExpr;
690 return EmitBlockLiteral(*blockInfo);
693 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
694 // Using the computed layout, generate the actual block function.
695 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
696 llvm::Constant *blockFn
697 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
700 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
702 // If there is nothing to capture, we can emit this as a global block.
703 if (blockInfo.CanBeGlobal)
704 return buildGlobalBlock(CGM, blockInfo, blockFn);
706 // Otherwise, we have to emit this as a local block.
708 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
709 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
711 // Build the block descriptor.
712 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
714 Address blockAddr = blockInfo.LocalAddress;
715 assert(blockAddr.isValid() && "block has no address!");
717 // Compute the initial on-stack block flags.
718 BlockFlags flags = BLOCK_HAS_SIGNATURE;
719 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
720 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
722 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
725 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
726 return Builder.CreateStructGEP(blockAddr, index, offset, name);
729 [&](llvm::Value *value, unsigned index, CharUnits offset,
731 Builder.CreateStore(value, projectField(index, offset, name));
734 // Initialize the block header.
736 // We assume all the header fields are densely packed.
739 auto addHeaderField =
740 [&](llvm::Value *value, CharUnits size, const Twine &name) {
741 storeField(value, index, offset, name);
746 addHeaderField(isa, getPointerSize(), "block.isa");
747 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
748 getIntSize(), "block.flags");
749 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
750 getIntSize(), "block.reserved");
751 addHeaderField(blockFn, getPointerSize(), "block.invoke");
752 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
755 // Finally, capture all the values into the block.
756 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
759 if (blockDecl->capturesCXXThis()) {
760 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
761 "block.captured-this.addr");
762 Builder.CreateStore(LoadCXXThis(), addr);
765 // Next, captured variables.
766 for (const auto &CI : blockDecl->captures()) {
767 const VarDecl *variable = CI.getVariable();
768 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
770 // Ignore constant captures.
771 if (capture.isConstant()) continue;
773 QualType type = variable->getType();
775 // This will be a [[type]]*, except that a byref entry will just be
778 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
780 // Compute the address of the thing we're going to move into the
782 Address src = Address::invalid();
784 if (blockDecl->isConversionFromLambda()) {
785 // The lambda capture in a lambda's conversion-to-block-pointer is
786 // special; we'll simply emit it directly.
787 src = Address::invalid();
788 } else if (CI.isByRef()) {
789 if (BlockInfo && CI.isNested()) {
790 // We need to use the capture from the enclosing block.
791 const CGBlockInfo::Capture &enclosingCapture =
792 BlockInfo->getCapture(variable);
794 // This is a [[type]]*, except that a byref entry wil just be an i8**.
795 src = Builder.CreateStructGEP(LoadBlockStruct(),
796 enclosingCapture.getIndex(),
797 enclosingCapture.getOffset(),
798 "block.capture.addr");
800 auto I = LocalDeclMap.find(variable);
801 assert(I != LocalDeclMap.end());
805 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
806 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
807 type.getNonReferenceType(), VK_LValue,
809 src = EmitDeclRefLValue(&declRef).getAddress();
812 // For byrefs, we just write the pointer to the byref struct into
813 // the block field. There's no need to chase the forwarding
814 // pointer at this point, since we're building something that will
815 // live a shorter life than the stack byref anyway.
817 // Get a void* that points to the byref struct.
818 llvm::Value *byrefPointer;
820 byrefPointer = Builder.CreateLoad(src, "byref.capture");
822 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
824 // Write that void* into the capture field.
825 Builder.CreateStore(byrefPointer, blockField);
827 // If we have a copy constructor, evaluate that into the block field.
828 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
829 if (blockDecl->isConversionFromLambda()) {
830 // If we have a lambda conversion, emit the expression
831 // directly into the block instead.
833 AggValueSlot::forAddr(blockField, Qualifiers(),
834 AggValueSlot::IsDestructed,
835 AggValueSlot::DoesNotNeedGCBarriers,
836 AggValueSlot::IsNotAliased);
837 EmitAggExpr(copyExpr, Slot);
839 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
842 // If it's a reference variable, copy the reference into the block field.
843 } else if (type->isReferenceType()) {
844 Builder.CreateStore(src.getPointer(), blockField);
846 // If this is an ARC __strong block-pointer variable, don't do a
849 // TODO: this can be generalized into the normal initialization logic:
850 // we should never need to do a block-copy when initializing a local
851 // variable, because the local variable's lifetime should be strictly
852 // contained within the stack block's.
853 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
854 type->isBlockPointerType()) {
855 // Load the block and do a simple retain.
856 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
857 value = EmitARCRetainNonBlock(value);
859 // Do a primitive store to the block field.
860 Builder.CreateStore(value, blockField);
862 // Otherwise, fake up a POD copy into the block field.
864 // Fake up a new variable so that EmitScalarInit doesn't think
865 // we're referring to the variable in its own initializer.
866 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
867 SourceLocation(), /*name*/ nullptr,
870 // We use one of these or the other depending on whether the
871 // reference is nested.
872 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
873 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
874 type, VK_LValue, SourceLocation());
876 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
877 &declRef, VK_RValue);
878 // FIXME: Pass a specific location for the expr init so that the store is
879 // attributed to a reasonable location - otherwise it may be attributed to
880 // locations of subexpressions in the initialization.
881 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
882 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
883 /*captured by init*/ false);
886 // Activate the cleanup if layout pushed one.
888 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
889 if (cleanup.isValid())
890 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
894 // Cast to the converted block-pointer type, which happens (somewhat
895 // unfortunately) to be a pointer to function type.
896 llvm::Value *result =
897 Builder.CreateBitCast(blockAddr.getPointer(),
898 ConvertType(blockInfo.getBlockExpr()->getType()));
904 llvm::Type *CodeGenModule::getBlockDescriptorType() {
905 if (BlockDescriptorType)
906 return BlockDescriptorType;
908 llvm::Type *UnsignedLongTy =
909 getTypes().ConvertType(getContext().UnsignedLongTy);
911 // struct __block_descriptor {
912 // unsigned long reserved;
913 // unsigned long block_size;
915 // // later, the following will be added
918 // void (*copyHelper)();
919 // void (*copyHelper)();
920 // } helpers; // !!! optional
922 // const char *signature; // the block signature
923 // const char *layout; // reserved
925 BlockDescriptorType =
926 llvm::StructType::create("struct.__block_descriptor",
927 UnsignedLongTy, UnsignedLongTy, nullptr);
929 // Now form a pointer to that.
930 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
931 return BlockDescriptorType;
934 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
935 if (GenericBlockLiteralType)
936 return GenericBlockLiteralType;
938 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
940 // struct __block_literal_generic {
944 // void (*__invoke)(void *);
945 // struct __block_descriptor *__descriptor;
947 GenericBlockLiteralType =
948 llvm::StructType::create("struct.__block_literal_generic",
949 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
950 BlockDescPtrTy, nullptr);
952 return GenericBlockLiteralType;
955 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
956 ReturnValueSlot ReturnValue) {
957 const BlockPointerType *BPT =
958 E->getCallee()->getType()->getAs<BlockPointerType>();
960 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
962 // Get a pointer to the generic block literal.
963 llvm::Type *BlockLiteralTy =
964 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
966 // Bitcast the callee to a block literal.
967 llvm::Value *BlockLiteral =
968 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
970 // Get the function pointer from the literal.
971 llvm::Value *FuncPtr =
972 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
974 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
976 // Add the block literal.
978 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
980 QualType FnType = BPT->getPointeeType();
982 // And the rest of the arguments.
983 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
985 // Load the function.
986 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
988 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
989 const CGFunctionInfo &FnInfo =
990 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
992 // Cast the function pointer to the right type.
993 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
995 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
996 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
998 // And call the block.
999 return EmitCall(FnInfo, Func, ReturnValue, Args);
1002 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1004 assert(BlockInfo && "evaluating block ref without block information?");
1005 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1007 // Handle constant captures.
1008 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1011 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1012 capture.getOffset(), "block.capture.addr");
1015 // addr should be a void** right now. Load, then cast the result
1018 auto &byrefInfo = getBlockByrefInfo(variable);
1019 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1021 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1022 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1024 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1025 variable->getName());
1028 if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1029 addr = EmitLoadOfReference(addr, refType);
1036 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1038 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1039 blockInfo.BlockExpression = blockExpr;
1041 // Compute information about the layout, etc., of this block.
1042 computeBlockInfo(*this, nullptr, blockInfo);
1044 // Using that metadata, generate the actual block function.
1045 llvm::Constant *blockFn;
1047 CodeGenFunction::DeclMapTy LocalDeclMap;
1048 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1053 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1055 return buildGlobalBlock(*this, blockInfo, blockFn);
1058 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1059 const CGBlockInfo &blockInfo,
1060 llvm::Constant *blockFn) {
1061 assert(blockInfo.CanBeGlobal);
1063 // Generate the constants for the block literal initializer.
1064 llvm::Constant *fields[BlockHeaderSize];
1067 fields[0] = CGM.getNSConcreteGlobalBlock();
1070 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1071 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1073 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1076 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1079 fields[3] = blockFn;
1082 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1084 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1086 llvm::GlobalVariable *literal =
1087 new llvm::GlobalVariable(CGM.getModule(),
1090 llvm::GlobalVariable::InternalLinkage,
1092 "__block_literal_global");
1093 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1095 // Return a constant of the appropriately-casted type.
1096 llvm::Type *requiredType =
1097 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1098 return llvm::ConstantExpr::getBitCast(literal, requiredType);
1101 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1104 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1106 llvm::Value *localAddr = nullptr;
1107 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1108 // Allocate a stack slot to let the debug info survive the RA.
1109 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1110 Builder.CreateStore(arg, alloc);
1111 localAddr = Builder.CreateLoad(alloc);
1114 if (CGDebugInfo *DI = getDebugInfo()) {
1115 if (CGM.getCodeGenOpts().getDebugInfo() >=
1116 codegenoptions::LimitedDebugInfo) {
1117 DI->setLocation(D->getLocation());
1118 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1119 localAddr, Builder);
1123 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1124 ApplyDebugLocation Scope(*this, StartLoc);
1126 // Instead of messing around with LocalDeclMap, just set the value
1127 // directly as BlockPointer.
1128 BlockPointer = Builder.CreateBitCast(arg,
1129 BlockInfo->StructureType->getPointerTo(),
1133 Address CodeGenFunction::LoadBlockStruct() {
1134 assert(BlockInfo && "not in a block invocation function!");
1135 assert(BlockPointer && "no block pointer set!");
1136 return Address(BlockPointer, BlockInfo->BlockAlign);
1140 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1141 const CGBlockInfo &blockInfo,
1142 const DeclMapTy &ldm,
1143 bool IsLambdaConversionToBlock) {
1144 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1148 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1150 BlockInfo = &blockInfo;
1152 // Arrange for local static and local extern declarations to appear
1153 // to be local to this function as well, in case they're directly
1154 // referenced in a block.
1155 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1156 const auto *var = dyn_cast<VarDecl>(i->first);
1157 if (var && !var->hasLocalStorage())
1158 setAddrOfLocalVar(var, i->second);
1161 // Begin building the function declaration.
1163 // Build the argument list.
1164 FunctionArgList args;
1166 // The first argument is the block pointer. Just take it as a void*
1167 // and cast it later.
1168 QualType selfTy = getContext().VoidPtrTy;
1169 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1171 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1172 SourceLocation(), II, selfTy);
1173 args.push_back(&selfDecl);
1175 // Now add the rest of the parameters.
1176 args.append(blockDecl->param_begin(), blockDecl->param_end());
1178 // Create the function declaration.
1179 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1180 const CGFunctionInfo &fnInfo =
1181 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1182 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1183 blockInfo.UsesStret = true;
1185 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1187 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1188 llvm::Function *fn = llvm::Function::Create(
1189 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1190 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1192 // Begin generating the function.
1193 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1194 blockDecl->getLocation(),
1195 blockInfo.getBlockExpr()->getBody()->getLocStart());
1197 // Okay. Undo some of what StartFunction did.
1199 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1200 // won't delete the dbg.declare intrinsics for captured variables.
1201 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1202 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1203 // Allocate a stack slot for it, so we can point the debugger to it
1204 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1207 // Set the DebugLocation to empty, so the store is recognized as a
1208 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1209 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1210 Builder.CreateStore(BlockPointer, Alloca);
1211 BlockPointerDbgLoc = Alloca.getPointer();
1214 // If we have a C++ 'this' reference, go ahead and force it into
1216 if (blockDecl->capturesCXXThis()) {
1218 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1219 blockInfo.CXXThisOffset, "block.captured-this");
1220 CXXThisValue = Builder.CreateLoad(addr, "this");
1223 // Also force all the constant captures.
1224 for (const auto &CI : blockDecl->captures()) {
1225 const VarDecl *variable = CI.getVariable();
1226 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1227 if (!capture.isConstant()) continue;
1229 CharUnits align = getContext().getDeclAlign(variable);
1231 CreateMemTemp(variable->getType(), align, "block.captured-const");
1233 Builder.CreateStore(capture.getConstant(), alloca);
1235 setAddrOfLocalVar(variable, alloca);
1238 // Save a spot to insert the debug information for all the DeclRefExprs.
1239 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1240 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1243 if (IsLambdaConversionToBlock)
1244 EmitLambdaBlockInvokeBody();
1246 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1247 incrementProfileCounter(blockDecl->getBody());
1248 EmitStmt(blockDecl->getBody());
1251 // Remember where we were...
1252 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1254 // Go back to the entry.
1256 Builder.SetInsertPoint(entry, entry_ptr);
1258 // Emit debug information for all the DeclRefExprs.
1259 // FIXME: also for 'this'
1260 if (CGDebugInfo *DI = getDebugInfo()) {
1261 for (const auto &CI : blockDecl->captures()) {
1262 const VarDecl *variable = CI.getVariable();
1263 DI->EmitLocation(Builder, variable->getLocation());
1265 if (CGM.getCodeGenOpts().getDebugInfo() >=
1266 codegenoptions::LimitedDebugInfo) {
1267 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1268 if (capture.isConstant()) {
1269 auto addr = LocalDeclMap.find(variable)->second;
1270 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1275 DI->EmitDeclareOfBlockDeclRefVariable(
1276 variable, BlockPointerDbgLoc, Builder, blockInfo,
1277 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1280 // Recover location if it was changed in the above loop.
1281 DI->EmitLocation(Builder,
1282 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1285 // And resume where we left off.
1286 if (resume == nullptr)
1287 Builder.ClearInsertionPoint();
1289 Builder.SetInsertPoint(resume);
1291 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1297 notes.push_back(HelperInfo());
1298 HelperInfo ¬e = notes.back();
1299 note.index = capture.getIndex();
1300 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1301 note.cxxbar_import = ci->getCopyExpr();
1303 if (ci->isByRef()) {
1304 note.flag = BLOCK_FIELD_IS_BYREF;
1305 if (type.isObjCGCWeak())
1306 note.flag |= BLOCK_FIELD_IS_WEAK;
1307 } else if (type->isBlockPointerType()) {
1308 note.flag = BLOCK_FIELD_IS_BLOCK;
1310 note.flag = BLOCK_FIELD_IS_OBJECT;
1314 /// Generate the copy-helper function for a block closure object:
1315 /// static void block_copy_helper(block_t *dst, block_t *src);
1316 /// The runtime will have previously initialized 'dst' by doing a
1317 /// bit-copy of 'src'.
1319 /// Note that this copies an entire block closure object to the heap;
1320 /// it should not be confused with a 'byref copy helper', which moves
1321 /// the contents of an individual __block variable to the heap.
1323 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1324 ASTContext &C = getContext();
1326 FunctionArgList args;
1327 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1329 args.push_back(&dstDecl);
1330 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1332 args.push_back(&srcDecl);
1334 const CGFunctionInfo &FI =
1335 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1337 // FIXME: it would be nice if these were mergeable with things with
1338 // identical semantics.
1339 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1341 llvm::Function *Fn =
1342 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1343 "__copy_helper_block_", &CGM.getModule());
1346 = &CGM.getContext().Idents.get("__copy_helper_block_");
1348 FunctionDecl *FD = FunctionDecl::Create(C,
1349 C.getTranslationUnitDecl(),
1351 SourceLocation(), II, C.VoidTy,
1356 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1358 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1359 StartFunction(FD, C.VoidTy, Fn, FI, args);
1360 // Create a scope with an artificial location for the body of this function.
1361 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1362 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1364 Address src = GetAddrOfLocalVar(&srcDecl);
1365 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1366 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1368 Address dst = GetAddrOfLocalVar(&dstDecl);
1369 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1370 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1372 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1374 for (const auto &CI : blockDecl->captures()) {
1375 const VarDecl *variable = CI.getVariable();
1376 QualType type = variable->getType();
1378 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1379 if (capture.isConstant()) continue;
1381 const Expr *copyExpr = CI.getCopyExpr();
1382 BlockFieldFlags flags;
1384 bool useARCWeakCopy = false;
1385 bool useARCStrongCopy = false;
1388 assert(!CI.isByRef());
1389 // don't bother computing flags
1391 } else if (CI.isByRef()) {
1392 flags = BLOCK_FIELD_IS_BYREF;
1393 if (type.isObjCGCWeak())
1394 flags |= BLOCK_FIELD_IS_WEAK;
1396 } else if (type->isObjCRetainableType()) {
1397 flags = BLOCK_FIELD_IS_OBJECT;
1398 bool isBlockPointer = type->isBlockPointerType();
1400 flags = BLOCK_FIELD_IS_BLOCK;
1402 // Special rules for ARC captures:
1403 Qualifiers qs = type.getQualifiers();
1405 // We need to register __weak direct captures with the runtime.
1406 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1407 useARCWeakCopy = true;
1409 // We need to retain the copied value for __strong direct captures.
1410 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1411 // If it's a block pointer, we have to copy the block and
1412 // assign that to the destination pointer, so we might as
1413 // well use _Block_object_assign. Otherwise we can avoid that.
1414 if (!isBlockPointer)
1415 useARCStrongCopy = true;
1417 // Non-ARC captures of retainable pointers are strong and
1418 // therefore require a call to _Block_object_assign.
1419 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1422 // Otherwise the memcpy is fine.
1427 // For all other types, the memcpy is fine.
1432 unsigned index = capture.getIndex();
1433 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1434 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1436 // If there's an explicit copy expression, we do that.
1438 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1439 } else if (useARCWeakCopy) {
1440 EmitARCCopyWeak(dstField, srcField);
1442 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1443 if (useARCStrongCopy) {
1444 // At -O0, store null into the destination field (so that the
1445 // storeStrong doesn't over-release) and then call storeStrong.
1446 // This is a workaround to not having an initStrong call.
1447 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1448 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1449 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1450 Builder.CreateStore(null, dstField);
1451 EmitARCStoreStrongCall(dstField, srcValue, true);
1453 // With optimization enabled, take advantage of the fact that
1454 // the blocks runtime guarantees a memcpy of the block data, and
1455 // just emit a retain of the src field.
1457 EmitARCRetainNonBlock(srcValue);
1459 // We don't need this anymore, so kill it. It's not quite
1460 // worth the annoyance to avoid creating it in the first place.
1461 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1464 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1465 llvm::Value *dstAddr =
1466 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1467 llvm::Value *args[] = {
1468 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1471 bool copyCanThrow = false;
1472 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1473 const Expr *copyExpr =
1474 CGM.getContext().getBlockVarCopyInits(variable);
1476 copyCanThrow = true; // FIXME: reuse the noexcept logic
1481 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1483 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1491 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1494 /// Generate the destroy-helper function for a block closure object:
1495 /// static void block_destroy_helper(block_t *theBlock);
1497 /// Note that this destroys a heap-allocated block closure object;
1498 /// it should not be confused with a 'byref destroy helper', which
1499 /// destroys the heap-allocated contents of an individual __block
1502 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1503 ASTContext &C = getContext();
1505 FunctionArgList args;
1506 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1508 args.push_back(&srcDecl);
1510 const CGFunctionInfo &FI =
1511 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1513 // FIXME: We'd like to put these into a mergable by content, with
1514 // internal linkage.
1515 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1517 llvm::Function *Fn =
1518 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1519 "__destroy_helper_block_", &CGM.getModule());
1522 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1524 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1526 SourceLocation(), II, C.VoidTy,
1530 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1532 // Create a scope with an artificial location for the body of this function.
1533 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1534 StartFunction(FD, C.VoidTy, Fn, FI, args);
1535 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1537 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1539 Address src = GetAddrOfLocalVar(&srcDecl);
1540 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1541 src = Builder.CreateBitCast(src, structPtrTy, "block");
1543 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1545 CodeGenFunction::RunCleanupsScope cleanups(*this);
1547 for (const auto &CI : blockDecl->captures()) {
1548 const VarDecl *variable = CI.getVariable();
1549 QualType type = variable->getType();
1551 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1552 if (capture.isConstant()) continue;
1554 BlockFieldFlags flags;
1555 const CXXDestructorDecl *dtor = nullptr;
1557 bool useARCWeakDestroy = false;
1558 bool useARCStrongDestroy = false;
1561 flags = BLOCK_FIELD_IS_BYREF;
1562 if (type.isObjCGCWeak())
1563 flags |= BLOCK_FIELD_IS_WEAK;
1564 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1565 if (record->hasTrivialDestructor())
1567 dtor = record->getDestructor();
1568 } else if (type->isObjCRetainableType()) {
1569 flags = BLOCK_FIELD_IS_OBJECT;
1570 if (type->isBlockPointerType())
1571 flags = BLOCK_FIELD_IS_BLOCK;
1573 // Special rules for ARC captures.
1574 Qualifiers qs = type.getQualifiers();
1576 // Use objc_storeStrong for __strong direct captures; the
1577 // dynamic tools really like it when we do this.
1578 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1579 useARCStrongDestroy = true;
1581 // Support __weak direct captures.
1582 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1583 useARCWeakDestroy = true;
1585 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1586 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1589 // Otherwise, we have nothing to do.
1598 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1600 // If there's an explicit copy expression, we do that.
1602 PushDestructorCleanup(dtor, srcField);
1604 // If this is a __weak capture, emit the release directly.
1605 } else if (useARCWeakDestroy) {
1606 EmitARCDestroyWeak(srcField);
1608 // Destroy strong objects with a call if requested.
1609 } else if (useARCStrongDestroy) {
1610 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1612 // Otherwise we call _Block_object_dispose. It wouldn't be too
1613 // hard to just emit this as a cleanup if we wanted to make sure
1614 // that things were done in reverse.
1616 llvm::Value *value = Builder.CreateLoad(srcField);
1617 value = Builder.CreateBitCast(value, VoidPtrTy);
1618 BuildBlockRelease(value, flags);
1622 cleanups.ForceCleanup();
1626 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1631 /// Emits the copy/dispose helper functions for a __block object of id type.
1632 class ObjectByrefHelpers final : public BlockByrefHelpers {
1633 BlockFieldFlags Flags;
1636 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1637 : BlockByrefHelpers(alignment), Flags(flags) {}
1639 void emitCopy(CodeGenFunction &CGF, Address destField,
1640 Address srcField) override {
1641 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1643 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1644 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1646 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1648 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1649 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1651 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1652 CGF.EmitNounwindRuntimeCall(fn, args);
1655 void emitDispose(CodeGenFunction &CGF, Address field) override {
1656 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1657 llvm::Value *value = CGF.Builder.CreateLoad(field);
1659 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1662 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1663 id.AddInteger(Flags.getBitMask());
1667 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1668 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1670 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1672 void emitCopy(CodeGenFunction &CGF, Address destField,
1673 Address srcField) override {
1674 CGF.EmitARCMoveWeak(destField, srcField);
1677 void emitDispose(CodeGenFunction &CGF, Address field) override {
1678 CGF.EmitARCDestroyWeak(field);
1681 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1682 // 0 is distinguishable from all pointers and byref flags
1687 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1688 /// that's not of block-pointer type.
1689 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1691 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1693 void emitCopy(CodeGenFunction &CGF, Address destField,
1694 Address srcField) override {
1695 // Do a "move" by copying the value and then zeroing out the old
1698 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1701 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1703 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1704 CGF.Builder.CreateStore(null, destField);
1705 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1706 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1709 CGF.Builder.CreateStore(value, destField);
1710 CGF.Builder.CreateStore(null, srcField);
1713 void emitDispose(CodeGenFunction &CGF, Address field) override {
1714 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1717 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1718 // 1 is distinguishable from all pointers and byref flags
1723 /// Emits the copy/dispose helpers for an ARC __block __strong
1724 /// variable that's of block-pointer type.
1725 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1727 ARCStrongBlockByrefHelpers(CharUnits alignment)
1728 : BlockByrefHelpers(alignment) {}
1730 void emitCopy(CodeGenFunction &CGF, Address destField,
1731 Address srcField) override {
1732 // Do the copy with objc_retainBlock; that's all that
1733 // _Block_object_assign would do anyway, and we'd have to pass the
1734 // right arguments to make sure it doesn't get no-op'ed.
1735 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1736 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1737 CGF.Builder.CreateStore(copy, destField);
1740 void emitDispose(CodeGenFunction &CGF, Address field) override {
1741 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1744 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1745 // 2 is distinguishable from all pointers and byref flags
1750 /// Emits the copy/dispose helpers for a __block variable with a
1751 /// nontrivial copy constructor or destructor.
1752 class CXXByrefHelpers final : public BlockByrefHelpers {
1754 const Expr *CopyExpr;
1757 CXXByrefHelpers(CharUnits alignment, QualType type,
1758 const Expr *copyExpr)
1759 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1761 bool needsCopy() const override { return CopyExpr != nullptr; }
1762 void emitCopy(CodeGenFunction &CGF, Address destField,
1763 Address srcField) override {
1764 if (!CopyExpr) return;
1765 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1768 void emitDispose(CodeGenFunction &CGF, Address field) override {
1769 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1770 CGF.PushDestructorCleanup(VarType, field);
1771 CGF.PopCleanupBlocks(cleanupDepth);
1774 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1775 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1778 } // end anonymous namespace
1780 static llvm::Constant *
1781 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1782 BlockByrefHelpers &generator) {
1783 ASTContext &Context = CGF.getContext();
1785 QualType R = Context.VoidTy;
1787 FunctionArgList args;
1788 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1790 args.push_back(&dst);
1792 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1794 args.push_back(&src);
1796 const CGFunctionInfo &FI =
1797 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1799 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1801 // FIXME: We'd like to put these into a mergable by content, with
1802 // internal linkage.
1803 llvm::Function *Fn =
1804 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1805 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1808 = &Context.Idents.get("__Block_byref_object_copy_");
1810 FunctionDecl *FD = FunctionDecl::Create(Context,
1811 Context.getTranslationUnitDecl(),
1813 SourceLocation(), II, R, nullptr,
1817 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1819 CGF.StartFunction(FD, R, Fn, FI, args);
1821 if (generator.needsCopy()) {
1822 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1825 Address destField = CGF.GetAddrOfLocalVar(&dst);
1826 destField = Address(CGF.Builder.CreateLoad(destField),
1827 byrefInfo.ByrefAlignment);
1828 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1829 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1833 Address srcField = CGF.GetAddrOfLocalVar(&src);
1834 srcField = Address(CGF.Builder.CreateLoad(srcField),
1835 byrefInfo.ByrefAlignment);
1836 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1837 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1840 generator.emitCopy(CGF, destField, srcField);
1843 CGF.FinishFunction();
1845 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1848 /// Build the copy helper for a __block variable.
1849 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1850 const BlockByrefInfo &byrefInfo,
1851 BlockByrefHelpers &generator) {
1852 CodeGenFunction CGF(CGM);
1853 return generateByrefCopyHelper(CGF, byrefInfo, generator);
1856 /// Generate code for a __block variable's dispose helper.
1857 static llvm::Constant *
1858 generateByrefDisposeHelper(CodeGenFunction &CGF,
1859 const BlockByrefInfo &byrefInfo,
1860 BlockByrefHelpers &generator) {
1861 ASTContext &Context = CGF.getContext();
1862 QualType R = Context.VoidTy;
1864 FunctionArgList args;
1865 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1867 args.push_back(&src);
1869 const CGFunctionInfo &FI =
1870 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1872 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1874 // FIXME: We'd like to put these into a mergable by content, with
1875 // internal linkage.
1876 llvm::Function *Fn =
1877 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1878 "__Block_byref_object_dispose_",
1879 &CGF.CGM.getModule());
1882 = &Context.Idents.get("__Block_byref_object_dispose_");
1884 FunctionDecl *FD = FunctionDecl::Create(Context,
1885 Context.getTranslationUnitDecl(),
1887 SourceLocation(), II, R, nullptr,
1891 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1893 CGF.StartFunction(FD, R, Fn, FI, args);
1895 if (generator.needsDispose()) {
1896 Address addr = CGF.GetAddrOfLocalVar(&src);
1897 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1898 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1899 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1900 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1902 generator.emitDispose(CGF, addr);
1905 CGF.FinishFunction();
1907 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1910 /// Build the dispose helper for a __block variable.
1911 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1912 const BlockByrefInfo &byrefInfo,
1913 BlockByrefHelpers &generator) {
1914 CodeGenFunction CGF(CGM);
1915 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1918 /// Lazily build the copy and dispose helpers for a __block variable
1919 /// with the given information.
1921 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1923 llvm::FoldingSetNodeID id;
1924 generator.Profile(id);
1927 BlockByrefHelpers *node
1928 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1929 if (node) return static_cast<T*>(node);
1931 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1932 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1934 T *copy = new (CGM.getContext()) T(std::move(generator));
1935 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1939 /// Build the copy and dispose helpers for the given __block variable
1940 /// emission. Places the helpers in the global cache. Returns null
1941 /// if no helpers are required.
1943 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1944 const AutoVarEmission &emission) {
1945 const VarDecl &var = *emission.Variable;
1946 QualType type = var.getType();
1948 auto &byrefInfo = getBlockByrefInfo(&var);
1950 // The alignment we care about for the purposes of uniquing byref
1951 // helpers is the alignment of the actual byref value field.
1952 CharUnits valueAlignment =
1953 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1955 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1956 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1957 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1959 return ::buildByrefHelpers(
1960 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1963 // Otherwise, if we don't have a retainable type, there's nothing to do.
1964 // that the runtime does extra copies.
1965 if (!type->isObjCRetainableType()) return nullptr;
1967 Qualifiers qs = type.getQualifiers();
1969 // If we have lifetime, that dominates.
1970 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1972 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1974 // These are just bits as far as the runtime is concerned.
1975 case Qualifiers::OCL_ExplicitNone:
1976 case Qualifiers::OCL_Autoreleasing:
1979 // Tell the runtime that this is ARC __weak, called by the
1981 case Qualifiers::OCL_Weak:
1982 return ::buildByrefHelpers(CGM, byrefInfo,
1983 ARCWeakByrefHelpers(valueAlignment));
1985 // ARC __strong __block variables need to be retained.
1986 case Qualifiers::OCL_Strong:
1987 // Block pointers need to be copied, and there's no direct
1988 // transfer possible.
1989 if (type->isBlockPointerType()) {
1990 return ::buildByrefHelpers(CGM, byrefInfo,
1991 ARCStrongBlockByrefHelpers(valueAlignment));
1993 // Otherwise, we transfer ownership of the retain from the stack
1996 return ::buildByrefHelpers(CGM, byrefInfo,
1997 ARCStrongByrefHelpers(valueAlignment));
2000 llvm_unreachable("fell out of lifetime switch!");
2003 BlockFieldFlags flags;
2004 if (type->isBlockPointerType()) {
2005 flags |= BLOCK_FIELD_IS_BLOCK;
2006 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2007 type->isObjCObjectPointerType()) {
2008 flags |= BLOCK_FIELD_IS_OBJECT;
2013 if (type.isObjCGCWeak())
2014 flags |= BLOCK_FIELD_IS_WEAK;
2016 return ::buildByrefHelpers(CGM, byrefInfo,
2017 ObjectByrefHelpers(valueAlignment, flags));
2020 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2022 bool followForward) {
2023 auto &info = getBlockByrefInfo(var);
2024 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2027 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2028 const BlockByrefInfo &info,
2030 const llvm::Twine &name) {
2031 // Chase the forwarding address if requested.
2032 if (followForward) {
2033 Address forwardingAddr =
2034 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2035 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2038 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2039 info.FieldOffset, name);
2042 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2047 /// void *__forwarding;
2048 /// int32_t __flags;
2050 /// void *__copy_helper; // only if needed
2051 /// void *__destroy_helper; // only if needed
2052 /// void *__byref_variable_layout;// only if needed
2053 /// char padding[X]; // only if needed
2057 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2058 auto it = BlockByrefInfos.find(D);
2059 if (it != BlockByrefInfos.end())
2062 llvm::StructType *byrefType =
2063 llvm::StructType::create(getLLVMContext(),
2064 "struct.__block_byref_" + D->getNameAsString());
2066 QualType Ty = D->getType();
2069 SmallVector<llvm::Type *, 8> types;
2072 types.push_back(Int8PtrTy);
2073 size += getPointerSize();
2075 // void *__forwarding;
2076 types.push_back(llvm::PointerType::getUnqual(byrefType));
2077 size += getPointerSize();
2080 types.push_back(Int32Ty);
2081 size += CharUnits::fromQuantity(4);
2084 types.push_back(Int32Ty);
2085 size += CharUnits::fromQuantity(4);
2087 // Note that this must match *exactly* the logic in buildByrefHelpers.
2088 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2089 if (hasCopyAndDispose) {
2090 /// void *__copy_helper;
2091 types.push_back(Int8PtrTy);
2092 size += getPointerSize();
2094 /// void *__destroy_helper;
2095 types.push_back(Int8PtrTy);
2096 size += getPointerSize();
2099 bool HasByrefExtendedLayout = false;
2100 Qualifiers::ObjCLifetime Lifetime;
2101 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2102 HasByrefExtendedLayout) {
2103 /// void *__byref_variable_layout;
2104 types.push_back(Int8PtrTy);
2105 size += CharUnits::fromQuantity(PointerSizeInBytes);
2109 llvm::Type *varTy = ConvertTypeForMem(Ty);
2111 bool packed = false;
2112 CharUnits varAlign = getContext().getDeclAlign(D);
2113 CharUnits varOffset = size.alignTo(varAlign);
2115 // We may have to insert padding.
2116 if (varOffset != size) {
2117 llvm::Type *paddingTy =
2118 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2120 types.push_back(paddingTy);
2123 // Conversely, we might have to prevent LLVM from inserting padding.
2124 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2125 > varAlign.getQuantity()) {
2128 types.push_back(varTy);
2130 byrefType->setBody(types, packed);
2132 BlockByrefInfo info;
2133 info.Type = byrefType;
2134 info.FieldIndex = types.size() - 1;
2135 info.FieldOffset = varOffset;
2136 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2138 auto pair = BlockByrefInfos.insert({D, info});
2139 assert(pair.second && "info was inserted recursively?");
2140 return pair.first->second;
2143 /// Initialize the structural components of a __block variable, i.e.
2144 /// everything but the actual object.
2145 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2146 // Find the address of the local.
2147 Address addr = emission.Addr;
2149 // That's an alloca of the byref structure type.
2150 llvm::StructType *byrefType = cast<llvm::StructType>(
2151 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2153 unsigned nextHeaderIndex = 0;
2154 CharUnits nextHeaderOffset;
2155 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2156 const Twine &name) {
2157 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2158 nextHeaderOffset, name);
2159 Builder.CreateStore(value, fieldAddr);
2162 nextHeaderOffset += fieldSize;
2165 // Build the byref helpers if necessary. This is null if we don't need any.
2166 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2168 const VarDecl &D = *emission.Variable;
2169 QualType type = D.getType();
2171 bool HasByrefExtendedLayout;
2172 Qualifiers::ObjCLifetime ByrefLifetime;
2173 bool ByRefHasLifetime =
2174 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2178 // Initialize the 'isa', which is just 0 or 1.
2180 if (type.isObjCGCWeak())
2182 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2183 storeHeaderField(V, getPointerSize(), "byref.isa");
2185 // Store the address of the variable into its own forwarding pointer.
2186 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2189 // c) the flags field is set to either 0 if no helper functions are
2190 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2192 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2193 if (ByRefHasLifetime) {
2194 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2195 else switch (ByrefLifetime) {
2196 case Qualifiers::OCL_Strong:
2197 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2199 case Qualifiers::OCL_Weak:
2200 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2202 case Qualifiers::OCL_ExplicitNone:
2203 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2205 case Qualifiers::OCL_None:
2206 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2207 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2212 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2213 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2214 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2215 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2216 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2217 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2218 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2219 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2220 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2221 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2222 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2223 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2224 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2225 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2226 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2227 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2232 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2233 getIntSize(), "byref.flags");
2235 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2236 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2237 storeHeaderField(V, getIntSize(), "byref.size");
2240 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2241 "byref.copyHelper");
2242 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2243 "byref.disposeHelper");
2246 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2247 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2248 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2252 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2253 llvm::Value *F = CGM.getBlockObjectDispose();
2254 llvm::Value *args[] = {
2255 Builder.CreateBitCast(V, Int8PtrTy),
2256 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2258 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2262 /// Release a __block variable.
2263 struct CallBlockRelease final : EHScopeStack::Cleanup {
2265 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2267 void Emit(CodeGenFunction &CGF, Flags flags) override {
2268 // Should we be passing FIELD_IS_WEAK here?
2269 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2272 } // end anonymous namespace
2274 /// Enter a cleanup to destroy a __block variable. Note that this
2275 /// cleanup should be a no-op if the variable hasn't left the stack
2276 /// yet; if a cleanup is required for the variable itself, that needs
2277 /// to be done externally.
2278 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2279 // We don't enter this cleanup if we're in pure-GC mode.
2280 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2283 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2284 emission.Addr.getPointer());
2287 /// Adjust the declaration of something from the blocks API.
2288 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2289 llvm::Constant *C) {
2290 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2292 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2293 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2294 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2295 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2297 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2298 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2299 "expected Function or GlobalVariable");
2301 const NamedDecl *ND = nullptr;
2302 for (const auto &Result : DC->lookup(&II))
2303 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2304 (ND = dyn_cast<VarDecl>(Result)))
2307 // TODO: support static blocks runtime
2308 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2309 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2310 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2312 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2313 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2317 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2320 if (GV->isDeclaration() && GV->hasExternalLinkage())
2321 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2324 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2325 if (BlockObjectDispose)
2326 return BlockObjectDispose;
2328 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2329 llvm::FunctionType *fty
2330 = llvm::FunctionType::get(VoidTy, args, false);
2331 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2332 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2333 return BlockObjectDispose;
2336 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2337 if (BlockObjectAssign)
2338 return BlockObjectAssign;
2340 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2341 llvm::FunctionType *fty
2342 = llvm::FunctionType::get(VoidTy, args, false);
2343 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2344 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2345 return BlockObjectAssign;
2348 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2349 if (NSConcreteGlobalBlock)
2350 return NSConcreteGlobalBlock;
2352 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2353 Int8PtrTy->getPointerTo(),
2355 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2356 return NSConcreteGlobalBlock;
2359 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2360 if (NSConcreteStackBlock)
2361 return NSConcreteStackBlock;
2363 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2364 Int8PtrTy->getPointerTo(),
2366 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2367 return NSConcreteStackBlock;