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 "CGOpenCLRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/CodeGen/ConstantInitBuilder.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Module.h"
31 using namespace clang;
32 using namespace CodeGen;
34 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
35 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
36 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
37 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
38 DominatingIP(nullptr) {
40 // Skip asm prefix, if any. 'name' is usually taken directly from
41 // the mangled name of the enclosing function.
42 if (!name.empty() && name[0] == '\01')
43 name = name.substr(1);
46 // Anchor the vtable to this translation unit.
47 BlockByrefHelpers::~BlockByrefHelpers() {}
49 /// Build the given block as a global block.
50 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo,
52 llvm::Constant *blockFn);
54 /// Build the helper function to copy a block.
55 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
60 /// Build the helper function to dispose of a block.
61 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
62 const CGBlockInfo &blockInfo) {
63 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
66 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
67 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
68 /// meta-data and contains stationary information about the block literal.
69 /// Its definition will have 4 (or optinally 6) words.
71 /// struct Block_descriptor {
72 /// unsigned long reserved;
73 /// unsigned long size; // size of Block_literal metadata in bytes.
74 /// void *copy_func_helper_decl; // optional copy helper.
75 /// void *destroy_func_decl; // optioanl destructor helper.
76 /// void *block_method_encoding_address; // @encode for block literal signature.
77 /// void *block_layout_info; // encoding of captured block variables.
80 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
81 const CGBlockInfo &blockInfo) {
82 ASTContext &C = CGM.getContext();
84 llvm::IntegerType *ulong =
85 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
86 llvm::PointerType *i8p = nullptr;
87 if (CGM.getLangOpts().OpenCL)
89 llvm::Type::getInt8PtrTy(
90 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
94 ConstantInitBuilder builder(CGM);
95 auto elements = builder.beginStruct();
98 elements.addInt(ulong, 0);
101 // FIXME: What is the right way to say this doesn't fit? We should give
102 // a user diagnostic in that case. Better fix would be to change the
104 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
106 // Optional copy/dispose helpers.
107 if (blockInfo.NeedsCopyDispose) {
108 // copy_func_helper_decl
109 elements.add(buildCopyHelper(CGM, blockInfo));
112 elements.add(buildDisposeHelper(CGM, blockInfo));
115 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
116 std::string typeAtEncoding =
117 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
118 elements.add(llvm::ConstantExpr::getBitCast(
119 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
122 if (C.getLangOpts().ObjC1) {
123 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
124 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
126 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
129 elements.addNullPointer(i8p);
131 unsigned AddrSpace = 0;
132 if (C.getLangOpts().OpenCL)
133 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
135 llvm::GlobalVariable *global =
136 elements.finishAndCreateGlobal("__block_descriptor_tmp",
137 CGM.getPointerAlign(),
139 llvm::GlobalValue::InternalLinkage,
142 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
146 Purely notional variadic template describing the layout of a block.
148 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
149 struct Block_literal {
150 /// Initialized to one of:
151 /// extern void *_NSConcreteStackBlock[];
152 /// extern void *_NSConcreteGlobalBlock[];
154 /// In theory, we could start one off malloc'ed by setting
155 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
157 /// extern void *_NSConcreteMallocBlock[];
158 struct objc_class *isa;
160 /// These are the flags (with corresponding bit number) that the
161 /// compiler is actually supposed to know about.
162 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
163 /// descriptor provides copy and dispose helper functions
164 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
165 /// object with a nontrivial destructor or copy constructor
166 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
168 /// 29. BLOCK_USE_STRET - indicates that the block function
169 /// uses stret, which objc_msgSend needs to know about
170 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
171 /// @encoded signature string
172 /// And we're not supposed to manipulate these:
173 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
174 /// to malloc'ed memory
175 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
176 /// to GC-allocated memory
177 /// Additionally, the bottom 16 bits are a reference count which
178 /// should be zero on the stack.
181 /// Reserved; should be zero-initialized.
184 /// Function pointer generated from block literal.
185 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
187 /// Block description metadata generated from block literal.
188 struct Block_descriptor *block_descriptor;
190 /// Captured values follow.
191 _CapturesTypes captures...;
196 /// A chunk of data that we actually have to capture in the block.
197 struct BlockLayoutChunk {
200 Qualifiers::ObjCLifetime Lifetime;
201 const BlockDecl::Capture *Capture; // null for 'this'
205 BlockLayoutChunk(CharUnits align, CharUnits size,
206 Qualifiers::ObjCLifetime lifetime,
207 const BlockDecl::Capture *capture,
208 llvm::Type *type, QualType fieldType)
209 : Alignment(align), Size(size), Lifetime(lifetime),
210 Capture(capture), Type(type), FieldType(fieldType) {}
212 /// Tell the block info that this chunk has the given field index.
213 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
215 info.CXXThisIndex = index;
216 info.CXXThisOffset = offset;
218 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
219 info.Captures.insert({Capture->getVariable(), C});
224 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
225 /// all __weak together. Preserve descending alignment in all situations.
226 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
227 if (left.Alignment != right.Alignment)
228 return left.Alignment > right.Alignment;
230 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
231 if (chunk.Capture && chunk.Capture->isByRef())
233 if (chunk.Lifetime == Qualifiers::OCL_Strong)
235 if (chunk.Lifetime == Qualifiers::OCL_Weak)
240 return getPrefOrder(left) < getPrefOrder(right);
242 } // end anonymous namespace
244 /// Determines if the given type is safe for constant capture in C++.
245 static bool isSafeForCXXConstantCapture(QualType type) {
246 const RecordType *recordType =
247 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
249 // Only records can be unsafe.
250 if (!recordType) return true;
252 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
254 // Maintain semantics for classes with non-trivial dtors or copy ctors.
255 if (!record->hasTrivialDestructor()) return false;
256 if (record->hasNonTrivialCopyConstructor()) return false;
258 // Otherwise, we just have to make sure there aren't any mutable
259 // fields that might have changed since initialization.
260 return !record->hasMutableFields();
263 /// It is illegal to modify a const object after initialization.
264 /// Therefore, if a const object has a constant initializer, we don't
265 /// actually need to keep storage for it in the block; we'll just
266 /// rematerialize it at the start of the block function. This is
267 /// acceptable because we make no promises about address stability of
268 /// captured variables.
269 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
270 CodeGenFunction *CGF,
271 const VarDecl *var) {
272 // Return if this is a function parameter. We shouldn't try to
273 // rematerialize default arguments of function parameters.
274 if (isa<ParmVarDecl>(var))
277 QualType type = var->getType();
279 // We can only do this if the variable is const.
280 if (!type.isConstQualified()) return nullptr;
282 // Furthermore, in C++ we have to worry about mutable fields:
283 // C++ [dcl.type.cv]p4:
284 // Except that any class member declared mutable can be
285 // modified, any attempt to modify a const object during its
286 // lifetime results in undefined behavior.
287 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
290 // If the variable doesn't have any initializer (shouldn't this be
291 // invalid?), it's not clear what we should do. Maybe capture as
293 const Expr *init = var->getInit();
294 if (!init) return nullptr;
296 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
299 /// Get the low bit of a nonzero character count. This is the
300 /// alignment of the nth byte if the 0th byte is universally aligned.
301 static CharUnits getLowBit(CharUnits v) {
302 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
305 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
306 SmallVectorImpl<llvm::Type*> &elementTypes) {
308 assert(elementTypes.empty());
309 if (CGM.getLangOpts().OpenCL) {
310 // The header is basically 'struct { int; int; generic void *;
311 // custom_fields; }'. Assert that struct is packed.
313 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
315 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
317 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
318 assert(CGM.getIntSize() <= GenPtrSize);
319 assert(CGM.getIntAlign() <= GenPtrAlign);
320 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
321 elementTypes.push_back(CGM.IntTy); /* total size */
322 elementTypes.push_back(CGM.IntTy); /* align */
323 elementTypes.push_back(
324 CGM.getOpenCLRuntime()
325 .getGenericVoidPointerType()); /* invoke function */
327 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
328 unsigned BlockAlign = GenPtrAlign.getQuantity();
330 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
331 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
332 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
333 // If necessary, add padding fields to the custom fields.
334 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
335 if (BlockAlign < Align)
337 assert(Offset % Align == 0);
338 Offset += CGM.getDataLayout().getTypeAllocSize(I);
339 elementTypes.push_back(I);
342 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
343 info.BlockSize = CharUnits::fromQuantity(Offset);
345 // The header is basically 'struct { void *; int; int; void *; void *; }'.
346 // Assert that that struct is packed.
347 assert(CGM.getIntSize() <= CGM.getPointerSize());
348 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
349 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
350 info.BlockAlign = CGM.getPointerAlign();
351 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
352 elementTypes.push_back(CGM.VoidPtrTy);
353 elementTypes.push_back(CGM.IntTy);
354 elementTypes.push_back(CGM.IntTy);
355 elementTypes.push_back(CGM.VoidPtrTy);
356 elementTypes.push_back(CGM.getBlockDescriptorType());
360 static QualType getCaptureFieldType(const CodeGenFunction &CGF,
361 const BlockDecl::Capture &CI) {
362 const VarDecl *VD = CI.getVariable();
364 // If the variable is captured by an enclosing block or lambda expression,
365 // use the type of the capture field.
366 if (CGF.BlockInfo && CI.isNested())
367 return CGF.BlockInfo->getCapture(VD).fieldType();
368 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
369 return FD->getType();
370 return VD->getType();
373 /// Compute the layout of the given block. Attempts to lay the block
374 /// out with minimal space requirements.
375 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
377 ASTContext &C = CGM.getContext();
378 const BlockDecl *block = info.getBlockDecl();
380 SmallVector<llvm::Type*, 8> elementTypes;
381 initializeForBlockHeader(CGM, info, elementTypes);
382 bool hasNonConstantCustomFields = false;
383 if (auto *OpenCLHelper =
384 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
385 hasNonConstantCustomFields =
386 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
387 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
389 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
390 info.CanBeGlobal = true;
393 else if (C.getLangOpts().ObjC1 &&
394 CGM.getLangOpts().getGC() == LangOptions::NonGC)
395 info.HasCapturedVariableLayout = true;
397 // Collect the layout chunks.
398 SmallVector<BlockLayoutChunk, 16> layout;
399 layout.reserve(block->capturesCXXThis() +
400 (block->capture_end() - block->capture_begin()));
402 CharUnits maxFieldAlign;
405 if (block->capturesCXXThis()) {
406 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
407 "Can't capture 'this' outside a method");
408 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
410 // Theoretically, this could be in a different address space, so
411 // don't assume standard pointer size/align.
412 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
413 std::pair<CharUnits,CharUnits> tinfo
414 = CGM.getContext().getTypeInfoInChars(thisType);
415 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
417 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
418 Qualifiers::OCL_None,
419 nullptr, llvmType, thisType));
422 // Next, all the block captures.
423 for (const auto &CI : block->captures()) {
424 const VarDecl *variable = CI.getVariable();
427 // We have to copy/dispose of the __block reference.
428 info.NeedsCopyDispose = true;
430 // Just use void* instead of a pointer to the byref type.
431 CharUnits align = CGM.getPointerAlign();
432 maxFieldAlign = std::max(maxFieldAlign, align);
434 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
435 Qualifiers::OCL_None, &CI,
436 CGM.VoidPtrTy, variable->getType()));
440 // Otherwise, build a layout chunk with the size and alignment of
442 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
443 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
447 // If we have a lifetime qualifier, honor it for capture purposes.
448 // That includes *not* copying it if it's __unsafe_unretained.
449 Qualifiers::ObjCLifetime lifetime =
450 variable->getType().getObjCLifetime();
453 case Qualifiers::OCL_None: llvm_unreachable("impossible");
454 case Qualifiers::OCL_ExplicitNone:
455 case Qualifiers::OCL_Autoreleasing:
458 case Qualifiers::OCL_Strong:
459 case Qualifiers::OCL_Weak:
460 info.NeedsCopyDispose = true;
463 // Block pointers require copy/dispose. So do Objective-C pointers.
464 } else if (variable->getType()->isObjCRetainableType()) {
465 // But honor the inert __unsafe_unretained qualifier, which doesn't
466 // actually make it into the type system.
467 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
468 lifetime = Qualifiers::OCL_ExplicitNone;
470 info.NeedsCopyDispose = true;
471 // used for mrr below.
472 lifetime = Qualifiers::OCL_Strong;
475 // So do types that require non-trivial copy construction.
476 } else if (CI.hasCopyExpr()) {
477 info.NeedsCopyDispose = true;
478 info.HasCXXObject = true;
480 // And so do types with destructors.
481 } else if (CGM.getLangOpts().CPlusPlus) {
482 if (const CXXRecordDecl *record =
483 variable->getType()->getAsCXXRecordDecl()) {
484 if (!record->hasTrivialDestructor()) {
485 info.HasCXXObject = true;
486 info.NeedsCopyDispose = true;
491 QualType VT = getCaptureFieldType(*CGF, CI);
492 CharUnits size = C.getTypeSizeInChars(VT);
493 CharUnits align = C.getDeclAlign(variable);
495 maxFieldAlign = std::max(maxFieldAlign, align);
497 llvm::Type *llvmType =
498 CGM.getTypes().ConvertTypeForMem(VT);
501 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
504 // If that was everything, we're done here.
505 if (layout.empty()) {
507 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
508 info.CanBeGlobal = true;
512 // Sort the layout by alignment. We have to use a stable sort here
513 // to get reproducible results. There should probably be an
514 // llvm::array_pod_stable_sort.
515 std::stable_sort(layout.begin(), layout.end());
517 // Needed for blocks layout info.
518 info.BlockHeaderForcedGapOffset = info.BlockSize;
519 info.BlockHeaderForcedGapSize = CharUnits::Zero();
521 CharUnits &blockSize = info.BlockSize;
522 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
524 // Assuming that the first byte in the header is maximally aligned,
525 // get the alignment of the first byte following the header.
526 CharUnits endAlign = getLowBit(blockSize);
528 // If the end of the header isn't satisfactorily aligned for the
529 // maximum thing, look for things that are okay with the header-end
530 // alignment, and keep appending them until we get something that's
531 // aligned right. This algorithm is only guaranteed optimal if
532 // that condition is satisfied at some point; otherwise we can get
534 // header // next byte has alignment 4
535 // something_with_size_5; // next byte has alignment 1
536 // something_with_alignment_8;
537 // which has 7 bytes of padding, as opposed to the naive solution
538 // which might have less (?).
539 if (endAlign < maxFieldAlign) {
540 SmallVectorImpl<BlockLayoutChunk>::iterator
541 li = layout.begin() + 1, le = layout.end();
543 // Look for something that the header end is already
544 // satisfactorily aligned for.
545 for (; li != le && endAlign < li->Alignment; ++li)
548 // If we found something that's naturally aligned for the end of
549 // the header, keep adding things...
551 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
552 for (; li != le; ++li) {
553 assert(endAlign >= li->Alignment);
555 li->setIndex(info, elementTypes.size(), blockSize);
556 elementTypes.push_back(li->Type);
557 blockSize += li->Size;
558 endAlign = getLowBit(blockSize);
560 // ...until we get to the alignment of the maximum field.
561 if (endAlign >= maxFieldAlign) {
565 // Don't re-append everything we just appended.
566 layout.erase(first, li);
570 assert(endAlign == getLowBit(blockSize));
572 // At this point, we just have to add padding if the end align still
573 // isn't aligned right.
574 if (endAlign < maxFieldAlign) {
575 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
576 CharUnits padding = newBlockSize - blockSize;
578 // If we haven't yet added any fields, remember that there was an
579 // initial gap; this need to go into the block layout bit map.
580 if (blockSize == info.BlockHeaderForcedGapOffset) {
581 info.BlockHeaderForcedGapSize = padding;
584 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
585 padding.getQuantity()));
586 blockSize = newBlockSize;
587 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
590 assert(endAlign >= maxFieldAlign);
591 assert(endAlign == getLowBit(blockSize));
592 // Slam everything else on now. This works because they have
593 // strictly decreasing alignment and we expect that size is always a
594 // multiple of alignment.
595 for (SmallVectorImpl<BlockLayoutChunk>::iterator
596 li = layout.begin(), le = layout.end(); li != le; ++li) {
597 if (endAlign < li->Alignment) {
598 // size may not be multiple of alignment. This can only happen with
599 // an over-aligned variable. We will be adding a padding field to
600 // make the size be multiple of alignment.
601 CharUnits padding = li->Alignment - endAlign;
602 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
603 padding.getQuantity()));
604 blockSize += padding;
605 endAlign = getLowBit(blockSize);
607 assert(endAlign >= li->Alignment);
608 li->setIndex(info, elementTypes.size(), blockSize);
609 elementTypes.push_back(li->Type);
610 blockSize += li->Size;
611 endAlign = getLowBit(blockSize);
615 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
618 /// Enter the scope of a block. This should be run at the entrance to
619 /// a full-expression so that the block's cleanups are pushed at the
620 /// right place in the stack.
621 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
622 assert(CGF.HaveInsertPoint());
624 // Allocate the block info and place it at the head of the list.
625 CGBlockInfo &blockInfo =
626 *new CGBlockInfo(block, CGF.CurFn->getName());
627 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
628 CGF.FirstBlockInfo = &blockInfo;
630 // Compute information about the layout, etc., of this block,
631 // pushing cleanups as necessary.
632 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
634 // Nothing else to do if it can be global.
635 if (blockInfo.CanBeGlobal) return;
637 // Make the allocation for the block.
638 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
639 blockInfo.BlockAlign, "block");
641 // If there are cleanups to emit, enter them (but inactive).
642 if (!blockInfo.NeedsCopyDispose) return;
644 // Walk through the captures (in order) and find the ones not
645 // captured by constant.
646 for (const auto &CI : block->captures()) {
647 // Ignore __block captures; there's nothing special in the
648 // on-stack block that we need to do for them.
649 if (CI.isByRef()) continue;
651 // Ignore variables that are constant-captured.
652 const VarDecl *variable = CI.getVariable();
653 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
654 if (capture.isConstant()) continue;
656 // Ignore objects that aren't destructed.
657 QualType VT = getCaptureFieldType(CGF, CI);
658 QualType::DestructionKind dtorKind = VT.isDestructedType();
659 if (dtorKind == QualType::DK_none) continue;
661 CodeGenFunction::Destroyer *destroyer;
663 // Block captures count as local values and have imprecise semantics.
664 // They also can't be arrays, so need to worry about that.
666 // For const-qualified captures, emit clang.arc.use to ensure the captured
667 // object doesn't get released while we are still depending on its validity
669 if (VT.isConstQualified() &&
670 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
671 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
672 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
673 "expected ObjC ARC to be enabled");
674 destroyer = CodeGenFunction::emitARCIntrinsicUse;
675 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
676 destroyer = CodeGenFunction::destroyARCStrongImprecise;
678 destroyer = CGF.getDestroyer(dtorKind);
681 // GEP down to the address.
682 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
684 capture.getOffset());
686 // We can use that GEP as the dominating IP.
687 if (!blockInfo.DominatingIP)
688 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
690 CleanupKind cleanupKind = InactiveNormalCleanup;
691 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
692 if (useArrayEHCleanup)
693 cleanupKind = InactiveNormalAndEHCleanup;
695 CGF.pushDestroy(cleanupKind, addr, VT,
696 destroyer, useArrayEHCleanup);
698 // Remember where that cleanup was.
699 capture.setCleanup(CGF.EHStack.stable_begin());
703 /// Enter a full-expression with a non-trivial number of objects to
704 /// clean up. This is in this file because, at the moment, the only
705 /// kind of cleanup object is a BlockDecl*.
706 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
707 assert(E->getNumObjects() != 0);
708 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
709 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
710 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
711 enterBlockScope(*this, *i);
715 /// Find the layout for the given block in a linked list and remove it.
716 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
717 const BlockDecl *block) {
719 assert(head && *head);
720 CGBlockInfo *cur = *head;
722 // If this is the block we're looking for, splice it out of the list.
723 if (cur->getBlockDecl() == block) {
724 *head = cur->NextBlockInfo;
728 head = &cur->NextBlockInfo;
732 /// Destroy a chain of block layouts.
733 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
734 assert(head && "destroying an empty chain");
736 CGBlockInfo *cur = head;
737 head = cur->NextBlockInfo;
739 } while (head != nullptr);
742 /// Emit a block literal expression in the current function.
743 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr,
744 llvm::Function **InvokeF) {
745 // If the block has no captures, we won't have a pre-computed
747 if (!blockExpr->getBlockDecl()->hasCaptures()) {
748 // The block literal is emitted as a global variable, and the block invoke
749 // function has to be extracted from its initializer.
750 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
752 auto *GV = cast<llvm::GlobalVariable>(
753 cast<llvm::Constant>(Block)->stripPointerCasts());
754 auto *BlockInit = cast<llvm::ConstantStruct>(GV->getInitializer());
755 *InvokeF = cast<llvm::Function>(
756 BlockInit->getAggregateElement(2)->stripPointerCasts());
760 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
761 computeBlockInfo(CGM, this, blockInfo);
762 blockInfo.BlockExpression = blockExpr;
763 return EmitBlockLiteral(blockInfo, InvokeF);
766 // Find the block info for this block and take ownership of it.
767 std::unique_ptr<CGBlockInfo> blockInfo;
768 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
769 blockExpr->getBlockDecl()));
771 blockInfo->BlockExpression = blockExpr;
772 return EmitBlockLiteral(*blockInfo, InvokeF);
775 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo,
776 llvm::Function **InvokeF) {
777 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
779 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
780 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
781 auto GenVoidPtrSize = CharUnits::fromQuantity(
782 CGM.getTarget().getPointerWidth(
783 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
785 // Using the computed layout, generate the actual block function.
786 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
787 CodeGenFunction BlockCGF{CGM, true};
788 BlockCGF.SanOpts = SanOpts;
789 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
790 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
793 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
795 // If there is nothing to capture, we can emit this as a global block.
796 if (blockInfo.CanBeGlobal)
797 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
799 // Otherwise, we have to emit this as a local block.
801 Address blockAddr = blockInfo.LocalAddress;
802 assert(blockAddr.isValid() && "block has no address!");
805 llvm::Constant *descriptor;
808 isa = llvm::ConstantExpr::getBitCast(CGM.getNSConcreteStackBlock(),
811 // Build the block descriptor.
812 descriptor = buildBlockDescriptor(CGM, blockInfo);
814 // Compute the initial on-stack block flags.
815 flags = BLOCK_HAS_SIGNATURE;
816 if (blockInfo.HasCapturedVariableLayout)
817 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
818 if (blockInfo.NeedsCopyDispose)
819 flags |= BLOCK_HAS_COPY_DISPOSE;
820 if (blockInfo.HasCXXObject)
821 flags |= BLOCK_HAS_CXX_OBJ;
822 if (blockInfo.UsesStret)
823 flags |= BLOCK_USE_STRET;
827 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
828 return Builder.CreateStructGEP(blockAddr, index, offset, name);
831 [&](llvm::Value *value, unsigned index, CharUnits offset,
833 Builder.CreateStore(value, projectField(index, offset, name));
836 // Initialize the block header.
838 // We assume all the header fields are densely packed.
841 auto addHeaderField =
842 [&](llvm::Value *value, CharUnits size, const Twine &name) {
843 storeField(value, index, offset, name);
849 addHeaderField(isa, getPointerSize(), "block.isa");
850 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
851 getIntSize(), "block.flags");
852 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
856 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
857 getIntSize(), "block.size");
859 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
860 getIntSize(), "block.align");
862 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
864 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
865 else if (auto *Helper =
866 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
867 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
870 CharUnits::fromQuantity(
871 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
877 // Finally, capture all the values into the block.
878 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
881 if (blockDecl->capturesCXXThis()) {
882 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
883 "block.captured-this.addr");
884 Builder.CreateStore(LoadCXXThis(), addr);
887 // Next, captured variables.
888 for (const auto &CI : blockDecl->captures()) {
889 const VarDecl *variable = CI.getVariable();
890 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
892 // Ignore constant captures.
893 if (capture.isConstant()) continue;
895 QualType type = capture.fieldType();
897 // This will be a [[type]]*, except that a byref entry will just be
900 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
902 // Compute the address of the thing we're going to move into the
904 Address src = Address::invalid();
906 if (blockDecl->isConversionFromLambda()) {
907 // The lambda capture in a lambda's conversion-to-block-pointer is
908 // special; we'll simply emit it directly.
909 src = Address::invalid();
910 } else if (CI.isByRef()) {
911 if (BlockInfo && CI.isNested()) {
912 // We need to use the capture from the enclosing block.
913 const CGBlockInfo::Capture &enclosingCapture =
914 BlockInfo->getCapture(variable);
916 // This is a [[type]]*, except that a byref entry wil just be an i8**.
917 src = Builder.CreateStructGEP(LoadBlockStruct(),
918 enclosingCapture.getIndex(),
919 enclosingCapture.getOffset(),
920 "block.capture.addr");
922 auto I = LocalDeclMap.find(variable);
923 assert(I != LocalDeclMap.end());
927 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
928 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
929 type.getNonReferenceType(), VK_LValue,
931 src = EmitDeclRefLValue(&declRef).getAddress();
934 // For byrefs, we just write the pointer to the byref struct into
935 // the block field. There's no need to chase the forwarding
936 // pointer at this point, since we're building something that will
937 // live a shorter life than the stack byref anyway.
939 // Get a void* that points to the byref struct.
940 llvm::Value *byrefPointer;
942 byrefPointer = Builder.CreateLoad(src, "byref.capture");
944 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
946 // Write that void* into the capture field.
947 Builder.CreateStore(byrefPointer, blockField);
949 // If we have a copy constructor, evaluate that into the block field.
950 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
951 if (blockDecl->isConversionFromLambda()) {
952 // If we have a lambda conversion, emit the expression
953 // directly into the block instead.
955 AggValueSlot::forAddr(blockField, Qualifiers(),
956 AggValueSlot::IsDestructed,
957 AggValueSlot::DoesNotNeedGCBarriers,
958 AggValueSlot::IsNotAliased);
959 EmitAggExpr(copyExpr, Slot);
961 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
964 // If it's a reference variable, copy the reference into the block field.
965 } else if (type->isReferenceType()) {
966 Builder.CreateStore(src.getPointer(), blockField);
968 // If type is const-qualified, copy the value into the block field.
969 } else if (type.isConstQualified() &&
970 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
971 CGM.getCodeGenOpts().OptimizationLevel != 0) {
972 llvm::Value *value = Builder.CreateLoad(src, "captured");
973 Builder.CreateStore(value, blockField);
975 // If this is an ARC __strong block-pointer variable, don't do a
978 // TODO: this can be generalized into the normal initialization logic:
979 // we should never need to do a block-copy when initializing a local
980 // variable, because the local variable's lifetime should be strictly
981 // contained within the stack block's.
982 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
983 type->isBlockPointerType()) {
984 // Load the block and do a simple retain.
985 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
986 value = EmitARCRetainNonBlock(value);
988 // Do a primitive store to the block field.
989 Builder.CreateStore(value, blockField);
991 // Otherwise, fake up a POD copy into the block field.
993 // Fake up a new variable so that EmitScalarInit doesn't think
994 // we're referring to the variable in its own initializer.
995 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
996 ImplicitParamDecl::Other);
998 // We use one of these or the other depending on whether the
999 // reference is nested.
1000 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
1001 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1002 type, VK_LValue, SourceLocation());
1004 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1005 &declRef, VK_RValue);
1006 // FIXME: Pass a specific location for the expr init so that the store is
1007 // attributed to a reasonable location - otherwise it may be attributed to
1008 // locations of subexpressions in the initialization.
1009 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1010 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1011 /*captured by init*/ false);
1014 // Activate the cleanup if layout pushed one.
1015 if (!CI.isByRef()) {
1016 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1017 if (cleanup.isValid())
1018 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
1022 // Cast to the converted block-pointer type, which happens (somewhat
1023 // unfortunately) to be a pointer to function type.
1024 llvm::Value *result = Builder.CreatePointerCast(
1025 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1031 llvm::Type *CodeGenModule::getBlockDescriptorType() {
1032 if (BlockDescriptorType)
1033 return BlockDescriptorType;
1035 llvm::Type *UnsignedLongTy =
1036 getTypes().ConvertType(getContext().UnsignedLongTy);
1038 // struct __block_descriptor {
1039 // unsigned long reserved;
1040 // unsigned long block_size;
1042 // // later, the following will be added
1045 // void (*copyHelper)();
1046 // void (*copyHelper)();
1047 // } helpers; // !!! optional
1049 // const char *signature; // the block signature
1050 // const char *layout; // reserved
1052 BlockDescriptorType = llvm::StructType::create(
1053 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1055 // Now form a pointer to that.
1056 unsigned AddrSpace = 0;
1057 if (getLangOpts().OpenCL)
1058 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1059 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1060 return BlockDescriptorType;
1063 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1064 if (GenericBlockLiteralType)
1065 return GenericBlockLiteralType;
1067 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1069 if (getLangOpts().OpenCL) {
1070 // struct __opencl_block_literal_generic {
1073 // __generic void *__invoke;
1074 // /* custom fields */
1076 SmallVector<llvm::Type *, 8> StructFields(
1077 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1078 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1079 for (auto I : Helper->getCustomFieldTypes())
1080 StructFields.push_back(I);
1082 GenericBlockLiteralType = llvm::StructType::create(
1083 StructFields, "struct.__opencl_block_literal_generic");
1085 // struct __block_literal_generic {
1089 // void (*__invoke)(void *);
1090 // struct __block_descriptor *__descriptor;
1092 GenericBlockLiteralType =
1093 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1094 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1097 return GenericBlockLiteralType;
1100 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1101 ReturnValueSlot ReturnValue) {
1102 const BlockPointerType *BPT =
1103 E->getCallee()->getType()->getAs<BlockPointerType>();
1105 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1107 // Get a pointer to the generic block literal.
1108 // For OpenCL we generate generic AS void ptr to be able to reuse the same
1109 // block definition for blocks with captures generated as private AS local
1110 // variables and without captures generated as global AS program scope
1112 unsigned AddrSpace = 0;
1113 if (getLangOpts().OpenCL)
1114 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1116 llvm::Type *BlockLiteralTy =
1117 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), AddrSpace);
1119 // Bitcast the callee to a block literal.
1121 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
1123 // Get the function pointer from the literal.
1124 llvm::Value *FuncPtr =
1125 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr,
1126 CGM.getLangOpts().OpenCL ? 2 : 3);
1128 // Add the block literal.
1131 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1132 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1133 if (getLangOpts().OpenCL) {
1134 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
1136 getContext().getPointerType(getContext().getAddrSpaceQualType(
1137 getContext().VoidTy, LangAS::opencl_generic));
1140 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1141 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
1143 QualType FnType = BPT->getPointeeType();
1145 // And the rest of the arguments.
1146 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1148 // Load the function.
1149 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1151 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1152 const CGFunctionInfo &FnInfo =
1153 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1155 // Cast the function pointer to the right type.
1156 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1158 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1159 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1161 // Prepare the callee.
1162 CGCallee Callee(CGCalleeInfo(), Func);
1164 // And call the block.
1165 return EmitCall(FnInfo, Callee, ReturnValue, Args);
1168 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1170 assert(BlockInfo && "evaluating block ref without block information?");
1171 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1173 // Handle constant captures.
1174 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1177 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1178 capture.getOffset(), "block.capture.addr");
1181 // addr should be a void** right now. Load, then cast the result
1184 auto &byrefInfo = getBlockByrefInfo(variable);
1185 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1187 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1188 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1190 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1191 variable->getName());
1194 if (capture.fieldType()->isReferenceType())
1195 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1200 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1201 llvm::Constant *Addr) {
1202 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1204 assert(Ok && "Trying to replace an already-existing global block!");
1208 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1210 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1213 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1214 blockInfo.BlockExpression = BE;
1216 // Compute information about the layout, etc., of this block.
1217 computeBlockInfo(*this, nullptr, blockInfo);
1219 // Using that metadata, generate the actual block function.
1221 CodeGenFunction::DeclMapTy LocalDeclMap;
1222 CodeGenFunction(*this).GenerateBlockFunction(
1223 GlobalDecl(), blockInfo, LocalDeclMap,
1224 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1227 return getAddrOfGlobalBlockIfEmitted(BE);
1230 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1231 const CGBlockInfo &blockInfo,
1232 llvm::Constant *blockFn) {
1233 assert(blockInfo.CanBeGlobal);
1234 // Callers should detect this case on their own: calling this function
1235 // generally requires computing layout information, which is a waste of time
1236 // if we've already emitted this block.
1237 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1238 "Refusing to re-emit a global block.");
1240 // Generate the constants for the block literal initializer.
1241 ConstantInitBuilder builder(CGM);
1242 auto fields = builder.beginStruct();
1244 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1247 fields.add(CGM.getNSConcreteGlobalBlock());
1250 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1251 if (blockInfo.UsesStret)
1252 flags |= BLOCK_USE_STRET;
1254 fields.addInt(CGM.IntTy, flags.getBitMask());
1257 fields.addInt(CGM.IntTy, 0);
1259 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1260 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1264 fields.add(blockFn);
1268 fields.add(buildBlockDescriptor(CGM, blockInfo));
1269 } else if (auto *Helper =
1270 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1271 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1276 unsigned AddrSpace = 0;
1277 if (CGM.getContext().getLangOpts().OpenCL)
1278 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1280 llvm::Constant *literal = fields.finishAndCreateGlobal(
1281 "__block_literal_global", blockInfo.BlockAlign,
1282 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1284 // Return a constant of the appropriately-casted type.
1285 llvm::Type *RequiredType =
1286 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1287 llvm::Constant *Result =
1288 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1289 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1293 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1296 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1298 // Allocate a stack slot like for any local variable to guarantee optimal
1299 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1300 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1301 Builder.CreateStore(arg, alloc);
1302 if (CGDebugInfo *DI = getDebugInfo()) {
1303 if (CGM.getCodeGenOpts().getDebugInfo() >=
1304 codegenoptions::LimitedDebugInfo) {
1305 DI->setLocation(D->getLocation());
1306 DI->EmitDeclareOfBlockLiteralArgVariable(
1307 *BlockInfo, D->getName(), argNum,
1308 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1312 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1313 ApplyDebugLocation Scope(*this, StartLoc);
1315 // Instead of messing around with LocalDeclMap, just set the value
1316 // directly as BlockPointer.
1317 BlockPointer = Builder.CreatePointerCast(
1319 BlockInfo->StructureType->getPointerTo(
1320 getContext().getLangOpts().OpenCL
1321 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1326 Address CodeGenFunction::LoadBlockStruct() {
1327 assert(BlockInfo && "not in a block invocation function!");
1328 assert(BlockPointer && "no block pointer set!");
1329 return Address(BlockPointer, BlockInfo->BlockAlign);
1333 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1334 const CGBlockInfo &blockInfo,
1335 const DeclMapTy &ldm,
1336 bool IsLambdaConversionToBlock,
1337 bool BuildGlobalBlock) {
1338 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1342 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1344 BlockInfo = &blockInfo;
1346 // Arrange for local static and local extern declarations to appear
1347 // to be local to this function as well, in case they're directly
1348 // referenced in a block.
1349 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1350 const auto *var = dyn_cast<VarDecl>(i->first);
1351 if (var && !var->hasLocalStorage())
1352 setAddrOfLocalVar(var, i->second);
1355 // Begin building the function declaration.
1357 // Build the argument list.
1358 FunctionArgList args;
1360 // The first argument is the block pointer. Just take it as a void*
1361 // and cast it later.
1362 QualType selfTy = getContext().VoidPtrTy;
1364 // For OpenCL passed block pointer can be private AS local variable or
1365 // global AS program scope variable (for the case with and without captures).
1366 // Generic AS is used therefore to be able to accommodate both private and
1367 // generic AS in one implementation.
1368 if (getLangOpts().OpenCL)
1369 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1370 getContext().VoidTy, LangAS::opencl_generic));
1372 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1374 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1375 SourceLocation(), II, selfTy,
1376 ImplicitParamDecl::ObjCSelf);
1377 args.push_back(&SelfDecl);
1379 // Now add the rest of the parameters.
1380 args.append(blockDecl->param_begin(), blockDecl->param_end());
1382 // Create the function declaration.
1383 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1384 const CGFunctionInfo &fnInfo =
1385 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1386 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1387 blockInfo.UsesStret = true;
1389 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1391 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1392 llvm::Function *fn = llvm::Function::Create(
1393 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1394 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1396 if (BuildGlobalBlock) {
1397 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1398 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1400 buildGlobalBlock(CGM, blockInfo,
1401 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1404 // Begin generating the function.
1405 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1406 blockDecl->getLocation(),
1407 blockInfo.getBlockExpr()->getBody()->getLocStart());
1409 // Okay. Undo some of what StartFunction did.
1411 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1412 // won't delete the dbg.declare intrinsics for captured variables.
1413 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1414 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1415 // Allocate a stack slot for it, so we can point the debugger to it
1416 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1419 // Set the DebugLocation to empty, so the store is recognized as a
1420 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1421 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1422 Builder.CreateStore(BlockPointer, Alloca);
1423 BlockPointerDbgLoc = Alloca.getPointer();
1426 // If we have a C++ 'this' reference, go ahead and force it into
1428 if (blockDecl->capturesCXXThis()) {
1430 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1431 blockInfo.CXXThisOffset, "block.captured-this");
1432 CXXThisValue = Builder.CreateLoad(addr, "this");
1435 // Also force all the constant captures.
1436 for (const auto &CI : blockDecl->captures()) {
1437 const VarDecl *variable = CI.getVariable();
1438 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1439 if (!capture.isConstant()) continue;
1441 CharUnits align = getContext().getDeclAlign(variable);
1443 CreateMemTemp(variable->getType(), align, "block.captured-const");
1445 Builder.CreateStore(capture.getConstant(), alloca);
1447 setAddrOfLocalVar(variable, alloca);
1450 // Save a spot to insert the debug information for all the DeclRefExprs.
1451 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1452 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1455 if (IsLambdaConversionToBlock)
1456 EmitLambdaBlockInvokeBody();
1458 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1459 incrementProfileCounter(blockDecl->getBody());
1460 EmitStmt(blockDecl->getBody());
1463 // Remember where we were...
1464 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1466 // Go back to the entry.
1468 Builder.SetInsertPoint(entry, entry_ptr);
1470 // Emit debug information for all the DeclRefExprs.
1471 // FIXME: also for 'this'
1472 if (CGDebugInfo *DI = getDebugInfo()) {
1473 for (const auto &CI : blockDecl->captures()) {
1474 const VarDecl *variable = CI.getVariable();
1475 DI->EmitLocation(Builder, variable->getLocation());
1477 if (CGM.getCodeGenOpts().getDebugInfo() >=
1478 codegenoptions::LimitedDebugInfo) {
1479 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1480 if (capture.isConstant()) {
1481 auto addr = LocalDeclMap.find(variable)->second;
1482 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1487 DI->EmitDeclareOfBlockDeclRefVariable(
1488 variable, BlockPointerDbgLoc, Builder, blockInfo,
1489 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1492 // Recover location if it was changed in the above loop.
1493 DI->EmitLocation(Builder,
1494 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1497 // And resume where we left off.
1498 if (resume == nullptr)
1499 Builder.ClearInsertionPoint();
1501 Builder.SetInsertPoint(resume);
1503 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1510 /// Represents a type of copy/destroy operation that should be performed for an
1511 /// entity that's captured by a block.
1512 enum class BlockCaptureEntityKind {
1513 CXXRecord, // Copy or destroy
1516 BlockObject, // Assign or release
1520 /// Represents a captured entity that requires extra operations in order for
1521 /// this entity to be copied or destroyed correctly.
1522 struct BlockCaptureManagedEntity {
1523 BlockCaptureEntityKind Kind;
1524 BlockFieldFlags Flags;
1525 const BlockDecl::Capture &CI;
1526 const CGBlockInfo::Capture &Capture;
1528 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1529 const BlockDecl::Capture &CI,
1530 const CGBlockInfo::Capture &Capture)
1531 : Kind(Type), Flags(Flags), CI(CI), Capture(Capture) {}
1534 } // end anonymous namespace
1536 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1537 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1538 const LangOptions &LangOpts) {
1539 if (CI.getCopyExpr()) {
1540 assert(!CI.isByRef());
1541 // don't bother computing flags
1542 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1544 BlockFieldFlags Flags;
1546 Flags = BLOCK_FIELD_IS_BYREF;
1547 if (T.isObjCGCWeak())
1548 Flags |= BLOCK_FIELD_IS_WEAK;
1549 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1551 if (!T->isObjCRetainableType())
1552 // For all other types, the memcpy is fine.
1553 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1555 Flags = BLOCK_FIELD_IS_OBJECT;
1556 bool isBlockPointer = T->isBlockPointerType();
1558 Flags = BLOCK_FIELD_IS_BLOCK;
1560 // Special rules for ARC captures:
1561 Qualifiers QS = T.getQualifiers();
1563 // We need to register __weak direct captures with the runtime.
1564 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1565 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1567 // We need to retain the copied value for __strong direct captures.
1568 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong) {
1569 // If it's a block pointer, we have to copy the block and
1570 // assign that to the destination pointer, so we might as
1571 // well use _Block_object_assign. Otherwise we can avoid that.
1572 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1573 : BlockCaptureEntityKind::BlockObject,
1577 // Non-ARC captures of retainable pointers are strong and
1578 // therefore require a call to _Block_object_assign.
1579 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1580 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1582 // Otherwise the memcpy is fine.
1583 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1586 /// Find the set of block captures that need to be explicitly copied or destroy.
1587 static void findBlockCapturedManagedEntities(
1588 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1589 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1590 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1591 const BlockDecl::Capture &, QualType, const LangOptions &)>
1593 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1594 const VarDecl *Variable = CI.getVariable();
1595 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1596 if (Capture.isConstant())
1599 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1600 if (Info.first != BlockCaptureEntityKind::None)
1601 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1605 /// Generate the copy-helper function for a block closure object:
1606 /// static void block_copy_helper(block_t *dst, block_t *src);
1607 /// The runtime will have previously initialized 'dst' by doing a
1608 /// bit-copy of 'src'.
1610 /// Note that this copies an entire block closure object to the heap;
1611 /// it should not be confused with a 'byref copy helper', which moves
1612 /// the contents of an individual __block variable to the heap.
1614 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1615 ASTContext &C = getContext();
1617 FunctionArgList args;
1618 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1619 ImplicitParamDecl::Other);
1620 args.push_back(&DstDecl);
1621 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1622 ImplicitParamDecl::Other);
1623 args.push_back(&SrcDecl);
1625 const CGFunctionInfo &FI =
1626 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1628 // FIXME: it would be nice if these were mergeable with things with
1629 // identical semantics.
1630 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1632 llvm::Function *Fn =
1633 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1634 "__copy_helper_block_", &CGM.getModule());
1637 = &CGM.getContext().Idents.get("__copy_helper_block_");
1639 FunctionDecl *FD = FunctionDecl::Create(C,
1640 C.getTranslationUnitDecl(),
1642 SourceLocation(), II, C.VoidTy,
1647 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1649 StartFunction(FD, C.VoidTy, Fn, FI, args);
1650 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
1651 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1653 Address src = GetAddrOfLocalVar(&SrcDecl);
1654 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1655 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1657 Address dst = GetAddrOfLocalVar(&DstDecl);
1658 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1659 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1661 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1662 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1663 computeCopyInfoForBlockCapture);
1665 for (const auto &CopiedCapture : CopiedCaptures) {
1666 const BlockDecl::Capture &CI = CopiedCapture.CI;
1667 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
1668 BlockFieldFlags flags = CopiedCapture.Flags;
1670 unsigned index = capture.getIndex();
1671 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1672 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1674 // If there's an explicit copy expression, we do that.
1675 if (CI.getCopyExpr()) {
1676 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1677 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1678 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
1679 EmitARCCopyWeak(dstField, srcField);
1681 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1682 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
1683 // At -O0, store null into the destination field (so that the
1684 // storeStrong doesn't over-release) and then call storeStrong.
1685 // This is a workaround to not having an initStrong call.
1686 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1687 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1688 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1689 Builder.CreateStore(null, dstField);
1690 EmitARCStoreStrongCall(dstField, srcValue, true);
1692 // With optimization enabled, take advantage of the fact that
1693 // the blocks runtime guarantees a memcpy of the block data, and
1694 // just emit a retain of the src field.
1696 EmitARCRetainNonBlock(srcValue);
1698 // We don't need this anymore, so kill it. It's not quite
1699 // worth the annoyance to avoid creating it in the first place.
1700 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1703 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
1704 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1705 llvm::Value *dstAddr =
1706 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1707 llvm::Value *args[] = {
1708 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1711 const VarDecl *variable = CI.getVariable();
1712 bool copyCanThrow = false;
1713 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1714 const Expr *copyExpr =
1715 CGM.getContext().getBlockVarCopyInits(variable);
1717 copyCanThrow = true; // FIXME: reuse the noexcept logic
1722 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1724 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1732 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1735 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1736 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1737 const LangOptions &LangOpts) {
1738 BlockFieldFlags Flags;
1740 Flags = BLOCK_FIELD_IS_BYREF;
1741 if (T.isObjCGCWeak())
1742 Flags |= BLOCK_FIELD_IS_WEAK;
1743 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1746 if (const CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1747 if (Record->hasTrivialDestructor())
1748 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1749 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1752 // Other types don't need to be destroy explicitly.
1753 if (!T->isObjCRetainableType())
1754 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1756 Flags = BLOCK_FIELD_IS_OBJECT;
1757 if (T->isBlockPointerType())
1758 Flags = BLOCK_FIELD_IS_BLOCK;
1760 // Special rules for ARC captures.
1761 Qualifiers QS = T.getQualifiers();
1763 // Use objc_storeStrong for __strong direct captures; the
1764 // dynamic tools really like it when we do this.
1765 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong)
1766 return std::make_pair(BlockCaptureEntityKind::ARCStrong, Flags);
1768 // Support __weak direct captures.
1769 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1770 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1772 // Non-ARC captures are strong, and we need to use
1773 // _Block_object_dispose.
1774 if (!QS.hasObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1775 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1777 // Otherwise, we have nothing to do.
1778 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1781 /// Generate the destroy-helper function for a block closure object:
1782 /// static void block_destroy_helper(block_t *theBlock);
1784 /// Note that this destroys a heap-allocated block closure object;
1785 /// it should not be confused with a 'byref destroy helper', which
1786 /// destroys the heap-allocated contents of an individual __block
1789 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1790 ASTContext &C = getContext();
1792 FunctionArgList args;
1793 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1794 ImplicitParamDecl::Other);
1795 args.push_back(&SrcDecl);
1797 const CGFunctionInfo &FI =
1798 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1800 // FIXME: We'd like to put these into a mergable by content, with
1801 // internal linkage.
1802 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1804 llvm::Function *Fn =
1805 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1806 "__destroy_helper_block_", &CGM.getModule());
1809 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1811 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1813 SourceLocation(), II, C.VoidTy,
1817 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1819 StartFunction(FD, C.VoidTy, Fn, FI, args);
1820 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
1822 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1824 Address src = GetAddrOfLocalVar(&SrcDecl);
1825 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1826 src = Builder.CreateBitCast(src, structPtrTy, "block");
1828 CodeGenFunction::RunCleanupsScope cleanups(*this);
1830 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1831 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1832 computeDestroyInfoForBlockCapture);
1834 for (const auto &DestroyedCapture : DestroyedCaptures) {
1835 const BlockDecl::Capture &CI = DestroyedCapture.CI;
1836 const CGBlockInfo::Capture &capture = DestroyedCapture.Capture;
1837 BlockFieldFlags flags = DestroyedCapture.Flags;
1840 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1842 // If the captured record has a destructor then call it.
1843 if (DestroyedCapture.Kind == BlockCaptureEntityKind::CXXRecord) {
1845 CI.getVariable()->getType()->getAsCXXRecordDecl()->getDestructor();
1846 PushDestructorCleanup(Dtor, srcField);
1848 // If this is a __weak capture, emit the release directly.
1849 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
1850 EmitARCDestroyWeak(srcField);
1852 // Destroy strong objects with a call if requested.
1853 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
1854 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1856 // Otherwise we call _Block_object_dispose. It wouldn't be too
1857 // hard to just emit this as a cleanup if we wanted to make sure
1858 // that things were done in reverse.
1860 assert(DestroyedCapture.Kind == BlockCaptureEntityKind::BlockObject);
1861 llvm::Value *value = Builder.CreateLoad(srcField);
1862 value = Builder.CreateBitCast(value, VoidPtrTy);
1863 BuildBlockRelease(value, flags);
1867 cleanups.ForceCleanup();
1871 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1876 /// Emits the copy/dispose helper functions for a __block object of id type.
1877 class ObjectByrefHelpers final : public BlockByrefHelpers {
1878 BlockFieldFlags Flags;
1881 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1882 : BlockByrefHelpers(alignment), Flags(flags) {}
1884 void emitCopy(CodeGenFunction &CGF, Address destField,
1885 Address srcField) override {
1886 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1888 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1889 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1891 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1893 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1894 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1896 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1897 CGF.EmitNounwindRuntimeCall(fn, args);
1900 void emitDispose(CodeGenFunction &CGF, Address field) override {
1901 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1902 llvm::Value *value = CGF.Builder.CreateLoad(field);
1904 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1907 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1908 id.AddInteger(Flags.getBitMask());
1912 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1913 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1915 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1917 void emitCopy(CodeGenFunction &CGF, Address destField,
1918 Address srcField) override {
1919 CGF.EmitARCMoveWeak(destField, srcField);
1922 void emitDispose(CodeGenFunction &CGF, Address field) override {
1923 CGF.EmitARCDestroyWeak(field);
1926 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1927 // 0 is distinguishable from all pointers and byref flags
1932 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1933 /// that's not of block-pointer type.
1934 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1936 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1938 void emitCopy(CodeGenFunction &CGF, Address destField,
1939 Address srcField) override {
1940 // Do a "move" by copying the value and then zeroing out the old
1943 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1946 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1948 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1949 CGF.Builder.CreateStore(null, destField);
1950 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1951 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1954 CGF.Builder.CreateStore(value, destField);
1955 CGF.Builder.CreateStore(null, srcField);
1958 void emitDispose(CodeGenFunction &CGF, Address field) override {
1959 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1962 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1963 // 1 is distinguishable from all pointers and byref flags
1968 /// Emits the copy/dispose helpers for an ARC __block __strong
1969 /// variable that's of block-pointer type.
1970 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1972 ARCStrongBlockByrefHelpers(CharUnits alignment)
1973 : BlockByrefHelpers(alignment) {}
1975 void emitCopy(CodeGenFunction &CGF, Address destField,
1976 Address srcField) override {
1977 // Do the copy with objc_retainBlock; that's all that
1978 // _Block_object_assign would do anyway, and we'd have to pass the
1979 // right arguments to make sure it doesn't get no-op'ed.
1980 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1981 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1982 CGF.Builder.CreateStore(copy, destField);
1985 void emitDispose(CodeGenFunction &CGF, Address field) override {
1986 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1989 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1990 // 2 is distinguishable from all pointers and byref flags
1995 /// Emits the copy/dispose helpers for a __block variable with a
1996 /// nontrivial copy constructor or destructor.
1997 class CXXByrefHelpers final : public BlockByrefHelpers {
1999 const Expr *CopyExpr;
2002 CXXByrefHelpers(CharUnits alignment, QualType type,
2003 const Expr *copyExpr)
2004 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2006 bool needsCopy() const override { return CopyExpr != nullptr; }
2007 void emitCopy(CodeGenFunction &CGF, Address destField,
2008 Address srcField) override {
2009 if (!CopyExpr) return;
2010 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2013 void emitDispose(CodeGenFunction &CGF, Address field) override {
2014 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2015 CGF.PushDestructorCleanup(VarType, field);
2016 CGF.PopCleanupBlocks(cleanupDepth);
2019 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2020 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2023 } // end anonymous namespace
2025 static llvm::Constant *
2026 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2027 BlockByrefHelpers &generator) {
2028 ASTContext &Context = CGF.getContext();
2030 QualType R = Context.VoidTy;
2032 FunctionArgList args;
2033 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2034 ImplicitParamDecl::Other);
2035 args.push_back(&Dst);
2037 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2038 ImplicitParamDecl::Other);
2039 args.push_back(&Src);
2041 const CGFunctionInfo &FI =
2042 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2044 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2046 // FIXME: We'd like to put these into a mergable by content, with
2047 // internal linkage.
2048 llvm::Function *Fn =
2049 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2050 "__Block_byref_object_copy_", &CGF.CGM.getModule());
2053 = &Context.Idents.get("__Block_byref_object_copy_");
2055 FunctionDecl *FD = FunctionDecl::Create(Context,
2056 Context.getTranslationUnitDecl(),
2058 SourceLocation(), II, R, nullptr,
2062 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2064 CGF.StartFunction(FD, R, Fn, FI, args);
2066 if (generator.needsCopy()) {
2067 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
2070 Address destField = CGF.GetAddrOfLocalVar(&Dst);
2071 destField = Address(CGF.Builder.CreateLoad(destField),
2072 byrefInfo.ByrefAlignment);
2073 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
2074 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2078 Address srcField = CGF.GetAddrOfLocalVar(&Src);
2079 srcField = Address(CGF.Builder.CreateLoad(srcField),
2080 byrefInfo.ByrefAlignment);
2081 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
2082 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2085 generator.emitCopy(CGF, destField, srcField);
2088 CGF.FinishFunction();
2090 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2093 /// Build the copy helper for a __block variable.
2094 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2095 const BlockByrefInfo &byrefInfo,
2096 BlockByrefHelpers &generator) {
2097 CodeGenFunction CGF(CGM);
2098 return generateByrefCopyHelper(CGF, byrefInfo, generator);
2101 /// Generate code for a __block variable's dispose helper.
2102 static llvm::Constant *
2103 generateByrefDisposeHelper(CodeGenFunction &CGF,
2104 const BlockByrefInfo &byrefInfo,
2105 BlockByrefHelpers &generator) {
2106 ASTContext &Context = CGF.getContext();
2107 QualType R = Context.VoidTy;
2109 FunctionArgList args;
2110 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2111 ImplicitParamDecl::Other);
2112 args.push_back(&Src);
2114 const CGFunctionInfo &FI =
2115 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2117 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2119 // FIXME: We'd like to put these into a mergable by content, with
2120 // internal linkage.
2121 llvm::Function *Fn =
2122 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2123 "__Block_byref_object_dispose_",
2124 &CGF.CGM.getModule());
2127 = &Context.Idents.get("__Block_byref_object_dispose_");
2129 FunctionDecl *FD = FunctionDecl::Create(Context,
2130 Context.getTranslationUnitDecl(),
2132 SourceLocation(), II, R, nullptr,
2136 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2138 CGF.StartFunction(FD, R, Fn, FI, args);
2140 if (generator.needsDispose()) {
2141 Address addr = CGF.GetAddrOfLocalVar(&Src);
2142 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2143 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2144 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2145 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2147 generator.emitDispose(CGF, addr);
2150 CGF.FinishFunction();
2152 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2155 /// Build the dispose helper for a __block variable.
2156 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2157 const BlockByrefInfo &byrefInfo,
2158 BlockByrefHelpers &generator) {
2159 CodeGenFunction CGF(CGM);
2160 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2163 /// Lazily build the copy and dispose helpers for a __block variable
2164 /// with the given information.
2166 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2168 llvm::FoldingSetNodeID id;
2169 generator.Profile(id);
2172 BlockByrefHelpers *node
2173 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2174 if (node) return static_cast<T*>(node);
2176 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2177 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2179 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2180 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2184 /// Build the copy and dispose helpers for the given __block variable
2185 /// emission. Places the helpers in the global cache. Returns null
2186 /// if no helpers are required.
2188 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2189 const AutoVarEmission &emission) {
2190 const VarDecl &var = *emission.Variable;
2191 QualType type = var.getType();
2193 auto &byrefInfo = getBlockByrefInfo(&var);
2195 // The alignment we care about for the purposes of uniquing byref
2196 // helpers is the alignment of the actual byref value field.
2197 CharUnits valueAlignment =
2198 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2200 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2201 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
2202 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2204 return ::buildByrefHelpers(
2205 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2208 // Otherwise, if we don't have a retainable type, there's nothing to do.
2209 // that the runtime does extra copies.
2210 if (!type->isObjCRetainableType()) return nullptr;
2212 Qualifiers qs = type.getQualifiers();
2214 // If we have lifetime, that dominates.
2215 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2217 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2219 // These are just bits as far as the runtime is concerned.
2220 case Qualifiers::OCL_ExplicitNone:
2221 case Qualifiers::OCL_Autoreleasing:
2224 // Tell the runtime that this is ARC __weak, called by the
2226 case Qualifiers::OCL_Weak:
2227 return ::buildByrefHelpers(CGM, byrefInfo,
2228 ARCWeakByrefHelpers(valueAlignment));
2230 // ARC __strong __block variables need to be retained.
2231 case Qualifiers::OCL_Strong:
2232 // Block pointers need to be copied, and there's no direct
2233 // transfer possible.
2234 if (type->isBlockPointerType()) {
2235 return ::buildByrefHelpers(CGM, byrefInfo,
2236 ARCStrongBlockByrefHelpers(valueAlignment));
2238 // Otherwise, we transfer ownership of the retain from the stack
2241 return ::buildByrefHelpers(CGM, byrefInfo,
2242 ARCStrongByrefHelpers(valueAlignment));
2245 llvm_unreachable("fell out of lifetime switch!");
2248 BlockFieldFlags flags;
2249 if (type->isBlockPointerType()) {
2250 flags |= BLOCK_FIELD_IS_BLOCK;
2251 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2252 type->isObjCObjectPointerType()) {
2253 flags |= BLOCK_FIELD_IS_OBJECT;
2258 if (type.isObjCGCWeak())
2259 flags |= BLOCK_FIELD_IS_WEAK;
2261 return ::buildByrefHelpers(CGM, byrefInfo,
2262 ObjectByrefHelpers(valueAlignment, flags));
2265 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2267 bool followForward) {
2268 auto &info = getBlockByrefInfo(var);
2269 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2272 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2273 const BlockByrefInfo &info,
2275 const llvm::Twine &name) {
2276 // Chase the forwarding address if requested.
2277 if (followForward) {
2278 Address forwardingAddr =
2279 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2280 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2283 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2284 info.FieldOffset, name);
2287 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2292 /// void *__forwarding;
2293 /// int32_t __flags;
2295 /// void *__copy_helper; // only if needed
2296 /// void *__destroy_helper; // only if needed
2297 /// void *__byref_variable_layout;// only if needed
2298 /// char padding[X]; // only if needed
2302 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2303 auto it = BlockByrefInfos.find(D);
2304 if (it != BlockByrefInfos.end())
2307 llvm::StructType *byrefType =
2308 llvm::StructType::create(getLLVMContext(),
2309 "struct.__block_byref_" + D->getNameAsString());
2311 QualType Ty = D->getType();
2314 SmallVector<llvm::Type *, 8> types;
2317 types.push_back(Int8PtrTy);
2318 size += getPointerSize();
2320 // void *__forwarding;
2321 types.push_back(llvm::PointerType::getUnqual(byrefType));
2322 size += getPointerSize();
2325 types.push_back(Int32Ty);
2326 size += CharUnits::fromQuantity(4);
2329 types.push_back(Int32Ty);
2330 size += CharUnits::fromQuantity(4);
2332 // Note that this must match *exactly* the logic in buildByrefHelpers.
2333 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2334 if (hasCopyAndDispose) {
2335 /// void *__copy_helper;
2336 types.push_back(Int8PtrTy);
2337 size += getPointerSize();
2339 /// void *__destroy_helper;
2340 types.push_back(Int8PtrTy);
2341 size += getPointerSize();
2344 bool HasByrefExtendedLayout = false;
2345 Qualifiers::ObjCLifetime Lifetime;
2346 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2347 HasByrefExtendedLayout) {
2348 /// void *__byref_variable_layout;
2349 types.push_back(Int8PtrTy);
2350 size += CharUnits::fromQuantity(PointerSizeInBytes);
2354 llvm::Type *varTy = ConvertTypeForMem(Ty);
2356 bool packed = false;
2357 CharUnits varAlign = getContext().getDeclAlign(D);
2358 CharUnits varOffset = size.alignTo(varAlign);
2360 // We may have to insert padding.
2361 if (varOffset != size) {
2362 llvm::Type *paddingTy =
2363 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2365 types.push_back(paddingTy);
2368 // Conversely, we might have to prevent LLVM from inserting padding.
2369 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2370 > varAlign.getQuantity()) {
2373 types.push_back(varTy);
2375 byrefType->setBody(types, packed);
2377 BlockByrefInfo info;
2378 info.Type = byrefType;
2379 info.FieldIndex = types.size() - 1;
2380 info.FieldOffset = varOffset;
2381 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2383 auto pair = BlockByrefInfos.insert({D, info});
2384 assert(pair.second && "info was inserted recursively?");
2385 return pair.first->second;
2388 /// Initialize the structural components of a __block variable, i.e.
2389 /// everything but the actual object.
2390 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2391 // Find the address of the local.
2392 Address addr = emission.Addr;
2394 // That's an alloca of the byref structure type.
2395 llvm::StructType *byrefType = cast<llvm::StructType>(
2396 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2398 unsigned nextHeaderIndex = 0;
2399 CharUnits nextHeaderOffset;
2400 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2401 const Twine &name) {
2402 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2403 nextHeaderOffset, name);
2404 Builder.CreateStore(value, fieldAddr);
2407 nextHeaderOffset += fieldSize;
2410 // Build the byref helpers if necessary. This is null if we don't need any.
2411 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2413 const VarDecl &D = *emission.Variable;
2414 QualType type = D.getType();
2416 bool HasByrefExtendedLayout;
2417 Qualifiers::ObjCLifetime ByrefLifetime;
2418 bool ByRefHasLifetime =
2419 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2423 // Initialize the 'isa', which is just 0 or 1.
2425 if (type.isObjCGCWeak())
2427 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2428 storeHeaderField(V, getPointerSize(), "byref.isa");
2430 // Store the address of the variable into its own forwarding pointer.
2431 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2434 // c) the flags field is set to either 0 if no helper functions are
2435 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2437 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2438 if (ByRefHasLifetime) {
2439 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2440 else switch (ByrefLifetime) {
2441 case Qualifiers::OCL_Strong:
2442 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2444 case Qualifiers::OCL_Weak:
2445 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2447 case Qualifiers::OCL_ExplicitNone:
2448 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2450 case Qualifiers::OCL_None:
2451 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2452 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2457 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2458 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2459 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2460 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2461 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2462 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2463 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2464 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2465 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2466 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2467 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2468 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2469 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2470 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2471 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2472 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2477 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2478 getIntSize(), "byref.flags");
2480 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2481 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2482 storeHeaderField(V, getIntSize(), "byref.size");
2485 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2486 "byref.copyHelper");
2487 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2488 "byref.disposeHelper");
2491 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2492 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2493 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2497 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2498 llvm::Value *F = CGM.getBlockObjectDispose();
2499 llvm::Value *args[] = {
2500 Builder.CreateBitCast(V, Int8PtrTy),
2501 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2503 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2507 /// Release a __block variable.
2508 struct CallBlockRelease final : EHScopeStack::Cleanup {
2510 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2512 void Emit(CodeGenFunction &CGF, Flags flags) override {
2513 // Should we be passing FIELD_IS_WEAK here?
2514 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2517 } // end anonymous namespace
2519 /// Enter a cleanup to destroy a __block variable. Note that this
2520 /// cleanup should be a no-op if the variable hasn't left the stack
2521 /// yet; if a cleanup is required for the variable itself, that needs
2522 /// to be done externally.
2523 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2524 // We don't enter this cleanup if we're in pure-GC mode.
2525 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2528 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2529 emission.Addr.getPointer());
2532 /// Adjust the declaration of something from the blocks API.
2533 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2534 llvm::Constant *C) {
2535 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2537 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2538 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2539 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2540 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2542 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2543 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2544 "expected Function or GlobalVariable");
2546 const NamedDecl *ND = nullptr;
2547 for (const auto &Result : DC->lookup(&II))
2548 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2549 (ND = dyn_cast<VarDecl>(Result)))
2552 // TODO: support static blocks runtime
2553 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2554 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2555 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2557 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2558 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2562 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2565 if (GV->isDeclaration() && GV->hasExternalLinkage())
2566 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2569 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2570 if (BlockObjectDispose)
2571 return BlockObjectDispose;
2573 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2574 llvm::FunctionType *fty
2575 = llvm::FunctionType::get(VoidTy, args, false);
2576 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2577 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2578 return BlockObjectDispose;
2581 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2582 if (BlockObjectAssign)
2583 return BlockObjectAssign;
2585 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2586 llvm::FunctionType *fty
2587 = llvm::FunctionType::get(VoidTy, args, false);
2588 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2589 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2590 return BlockObjectAssign;
2593 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2594 if (NSConcreteGlobalBlock)
2595 return NSConcreteGlobalBlock;
2597 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2598 Int8PtrTy->getPointerTo(),
2600 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2601 return NSConcreteGlobalBlock;
2604 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2605 if (NSConcreteStackBlock)
2606 return NSConcreteStackBlock;
2608 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2609 Int8PtrTy->getPointerTo(),
2611 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2612 return NSConcreteStackBlock;