1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This contains code to emit blocks.
11 //===----------------------------------------------------------------------===//
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/DataLayout.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/ScopedPrinter.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 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
38 StructureType(nullptr), Block(block), 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);
68 /// Represents a type of copy/destroy operation that should be performed for an
69 /// entity that's captured by a block.
70 enum class BlockCaptureEntityKind {
71 CXXRecord, // Copy or destroy
75 BlockObject, // Assign or release
79 /// Represents a captured entity that requires extra operations in order for
80 /// this entity to be copied or destroyed correctly.
81 struct BlockCaptureManagedEntity {
82 BlockCaptureEntityKind CopyKind, DisposeKind;
83 BlockFieldFlags CopyFlags, DisposeFlags;
84 const BlockDecl::Capture *CI;
85 const CGBlockInfo::Capture *Capture;
87 BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
88 BlockCaptureEntityKind DisposeType,
89 BlockFieldFlags CopyFlags,
90 BlockFieldFlags DisposeFlags,
91 const BlockDecl::Capture &CI,
92 const CGBlockInfo::Capture &Capture)
93 : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
94 DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
96 bool operator<(const BlockCaptureManagedEntity &Other) const {
97 return Capture->getOffset() < Other.Capture->getOffset();
101 enum class CaptureStrKind {
102 // String for the copy helper.
104 // String for the dispose helper.
106 // Merge the strings for the copy helper and dispose helper.
110 } // end anonymous namespace
112 static void findBlockCapturedManagedEntities(
113 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
114 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
116 static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
117 CaptureStrKind StrKind,
118 CharUnits BlockAlignment,
121 static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
122 CodeGenModule &CGM) {
123 std::string Name = "__block_descriptor_";
124 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
126 if (BlockInfo.needsCopyDisposeHelpers()) {
127 if (CGM.getLangOpts().Exceptions)
129 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
131 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
133 SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
134 findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
137 for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
138 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
140 if (E.CopyKind == E.DisposeKind) {
141 // If CopyKind and DisposeKind are the same, merge the capture
143 assert(E.CopyKind != BlockCaptureEntityKind::None &&
144 "shouldn't see BlockCaptureManagedEntity that is None");
145 Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
146 BlockInfo.BlockAlign, CGM);
148 // If CopyKind and DisposeKind are not the same, which can happen when
149 // either Kind is None or the captured object is a __strong block,
150 // concatenate the copy and dispose strings.
151 Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
152 BlockInfo.BlockAlign, CGM);
153 Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
154 BlockInfo.BlockAlign, CGM);
160 std::string TypeAtEncoding =
161 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
162 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
163 /// a separator between symbol name and symbol version.
164 std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
165 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
166 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
170 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
171 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
172 /// meta-data and contains stationary information about the block literal.
173 /// Its definition will have 4 (or optionally 6) words.
175 /// struct Block_descriptor {
176 /// unsigned long reserved;
177 /// unsigned long size; // size of Block_literal metadata in bytes.
178 /// void *copy_func_helper_decl; // optional copy helper.
179 /// void *destroy_func_decl; // optional destructor helper.
180 /// void *block_method_encoding_address; // @encode for block literal signature.
181 /// void *block_layout_info; // encoding of captured block variables.
184 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
185 const CGBlockInfo &blockInfo) {
186 ASTContext &C = CGM.getContext();
188 llvm::IntegerType *ulong =
189 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
190 llvm::PointerType *i8p = nullptr;
191 if (CGM.getLangOpts().OpenCL)
193 llvm::Type::getInt8PtrTy(
194 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
198 std::string descName;
200 // If an equivalent block descriptor global variable exists, return it.
201 if (C.getLangOpts().ObjC &&
202 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
203 descName = getBlockDescriptorName(blockInfo, CGM);
204 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
205 return llvm::ConstantExpr::getBitCast(desc,
206 CGM.getBlockDescriptorType());
209 // If there isn't an equivalent block descriptor global variable, create a new
211 ConstantInitBuilder builder(CGM);
212 auto elements = builder.beginStruct();
215 elements.addInt(ulong, 0);
218 // FIXME: What is the right way to say this doesn't fit? We should give
219 // a user diagnostic in that case. Better fix would be to change the
221 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
223 // Optional copy/dispose helpers.
224 bool hasInternalHelper = false;
225 if (blockInfo.needsCopyDisposeHelpers()) {
226 // copy_func_helper_decl
227 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
228 elements.add(copyHelper);
231 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
232 elements.add(disposeHelper);
234 if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
235 cast<llvm::Function>(disposeHelper->getOperand(0))
236 ->hasInternalLinkage())
237 hasInternalHelper = true;
240 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
241 std::string typeAtEncoding =
242 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
243 elements.add(llvm::ConstantExpr::getBitCast(
244 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
247 if (C.getLangOpts().ObjC) {
248 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
249 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
251 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
254 elements.addNullPointer(i8p);
256 unsigned AddrSpace = 0;
257 if (C.getLangOpts().OpenCL)
258 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
260 llvm::GlobalValue::LinkageTypes linkage;
261 if (descName.empty()) {
262 linkage = llvm::GlobalValue::InternalLinkage;
263 descName = "__block_descriptor_tmp";
264 } else if (hasInternalHelper) {
265 // If either the copy helper or the dispose helper has internal linkage,
266 // the block descriptor must have internal linkage too.
267 linkage = llvm::GlobalValue::InternalLinkage;
269 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
272 llvm::GlobalVariable *global =
273 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
274 /*constant*/ true, linkage, AddrSpace);
276 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
277 if (CGM.supportsCOMDAT())
278 global->setComdat(CGM.getModule().getOrInsertComdat(descName));
279 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
280 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
283 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
287 Purely notional variadic template describing the layout of a block.
289 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
290 struct Block_literal {
291 /// Initialized to one of:
292 /// extern void *_NSConcreteStackBlock[];
293 /// extern void *_NSConcreteGlobalBlock[];
295 /// In theory, we could start one off malloc'ed by setting
296 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
298 /// extern void *_NSConcreteMallocBlock[];
299 struct objc_class *isa;
301 /// These are the flags (with corresponding bit number) that the
302 /// compiler is actually supposed to know about.
303 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
304 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
305 /// descriptor provides copy and dispose helper functions
306 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
307 /// object with a nontrivial destructor or copy constructor
308 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
310 /// 29. BLOCK_USE_STRET - indicates that the block function
311 /// uses stret, which objc_msgSend needs to know about
312 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
313 /// @encoded signature string
314 /// And we're not supposed to manipulate these:
315 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
316 /// to malloc'ed memory
317 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
318 /// to GC-allocated memory
319 /// Additionally, the bottom 16 bits are a reference count which
320 /// should be zero on the stack.
323 /// Reserved; should be zero-initialized.
326 /// Function pointer generated from block literal.
327 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
329 /// Block description metadata generated from block literal.
330 struct Block_descriptor *block_descriptor;
332 /// Captured values follow.
333 _CapturesTypes captures...;
338 /// A chunk of data that we actually have to capture in the block.
339 struct BlockLayoutChunk {
342 Qualifiers::ObjCLifetime Lifetime;
343 const BlockDecl::Capture *Capture; // null for 'this'
347 BlockLayoutChunk(CharUnits align, CharUnits size,
348 Qualifiers::ObjCLifetime lifetime,
349 const BlockDecl::Capture *capture,
350 llvm::Type *type, QualType fieldType)
351 : Alignment(align), Size(size), Lifetime(lifetime),
352 Capture(capture), Type(type), FieldType(fieldType) {}
354 /// Tell the block info that this chunk has the given field index.
355 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
357 info.CXXThisIndex = index;
358 info.CXXThisOffset = offset;
360 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
361 info.Captures.insert({Capture->getVariable(), C});
366 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
367 /// all __weak together. Preserve descending alignment in all situations.
368 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
369 if (left.Alignment != right.Alignment)
370 return left.Alignment > right.Alignment;
372 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
373 if (chunk.Capture && chunk.Capture->isByRef())
375 if (chunk.Lifetime == Qualifiers::OCL_Strong)
377 if (chunk.Lifetime == Qualifiers::OCL_Weak)
382 return getPrefOrder(left) < getPrefOrder(right);
384 } // end anonymous namespace
386 /// Determines if the given type is safe for constant capture in C++.
387 static bool isSafeForCXXConstantCapture(QualType type) {
388 const RecordType *recordType =
389 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
391 // Only records can be unsafe.
392 if (!recordType) return true;
394 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
396 // Maintain semantics for classes with non-trivial dtors or copy ctors.
397 if (!record->hasTrivialDestructor()) return false;
398 if (record->hasNonTrivialCopyConstructor()) return false;
400 // Otherwise, we just have to make sure there aren't any mutable
401 // fields that might have changed since initialization.
402 return !record->hasMutableFields();
405 /// It is illegal to modify a const object after initialization.
406 /// Therefore, if a const object has a constant initializer, we don't
407 /// actually need to keep storage for it in the block; we'll just
408 /// rematerialize it at the start of the block function. This is
409 /// acceptable because we make no promises about address stability of
410 /// captured variables.
411 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
412 CodeGenFunction *CGF,
413 const VarDecl *var) {
414 // Return if this is a function parameter. We shouldn't try to
415 // rematerialize default arguments of function parameters.
416 if (isa<ParmVarDecl>(var))
419 QualType type = var->getType();
421 // We can only do this if the variable is const.
422 if (!type.isConstQualified()) return nullptr;
424 // Furthermore, in C++ we have to worry about mutable fields:
425 // C++ [dcl.type.cv]p4:
426 // Except that any class member declared mutable can be
427 // modified, any attempt to modify a const object during its
428 // lifetime results in undefined behavior.
429 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
432 // If the variable doesn't have any initializer (shouldn't this be
433 // invalid?), it's not clear what we should do. Maybe capture as
435 const Expr *init = var->getInit();
436 if (!init) return nullptr;
438 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
441 /// Get the low bit of a nonzero character count. This is the
442 /// alignment of the nth byte if the 0th byte is universally aligned.
443 static CharUnits getLowBit(CharUnits v) {
444 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
447 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
448 SmallVectorImpl<llvm::Type*> &elementTypes) {
450 assert(elementTypes.empty());
451 if (CGM.getLangOpts().OpenCL) {
452 // The header is basically 'struct { int; int; generic void *;
453 // custom_fields; }'. Assert that struct is packed.
455 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
457 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
459 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
460 assert(CGM.getIntSize() <= GenPtrSize);
461 assert(CGM.getIntAlign() <= GenPtrAlign);
462 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
463 elementTypes.push_back(CGM.IntTy); /* total size */
464 elementTypes.push_back(CGM.IntTy); /* align */
465 elementTypes.push_back(
466 CGM.getOpenCLRuntime()
467 .getGenericVoidPointerType()); /* invoke function */
469 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
470 unsigned BlockAlign = GenPtrAlign.getQuantity();
472 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
473 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
474 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
475 // If necessary, add padding fields to the custom fields.
476 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
477 if (BlockAlign < Align)
479 assert(Offset % Align == 0);
480 Offset += CGM.getDataLayout().getTypeAllocSize(I);
481 elementTypes.push_back(I);
484 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
485 info.BlockSize = CharUnits::fromQuantity(Offset);
487 // The header is basically 'struct { void *; int; int; void *; void *; }'.
488 // Assert that the struct is packed.
489 assert(CGM.getIntSize() <= CGM.getPointerSize());
490 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
491 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
492 info.BlockAlign = CGM.getPointerAlign();
493 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
494 elementTypes.push_back(CGM.VoidPtrTy);
495 elementTypes.push_back(CGM.IntTy);
496 elementTypes.push_back(CGM.IntTy);
497 elementTypes.push_back(CGM.VoidPtrTy);
498 elementTypes.push_back(CGM.getBlockDescriptorType());
502 static QualType getCaptureFieldType(const CodeGenFunction &CGF,
503 const BlockDecl::Capture &CI) {
504 const VarDecl *VD = CI.getVariable();
506 // If the variable is captured by an enclosing block or lambda expression,
507 // use the type of the capture field.
508 if (CGF.BlockInfo && CI.isNested())
509 return CGF.BlockInfo->getCapture(VD).fieldType();
510 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
511 return FD->getType();
512 // If the captured variable is a non-escaping __block variable, the field
513 // type is the reference type. If the variable is a __block variable that
514 // already has a reference type, the field type is the variable's type.
515 return VD->isNonEscapingByref() ?
516 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
519 /// Compute the layout of the given block. Attempts to lay the block
520 /// out with minimal space requirements.
521 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
523 ASTContext &C = CGM.getContext();
524 const BlockDecl *block = info.getBlockDecl();
526 SmallVector<llvm::Type*, 8> elementTypes;
527 initializeForBlockHeader(CGM, info, elementTypes);
528 bool hasNonConstantCustomFields = false;
529 if (auto *OpenCLHelper =
530 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
531 hasNonConstantCustomFields =
532 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
533 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
535 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
536 info.CanBeGlobal = true;
539 else if (C.getLangOpts().ObjC &&
540 CGM.getLangOpts().getGC() == LangOptions::NonGC)
541 info.HasCapturedVariableLayout = true;
543 // Collect the layout chunks.
544 SmallVector<BlockLayoutChunk, 16> layout;
545 layout.reserve(block->capturesCXXThis() +
546 (block->capture_end() - block->capture_begin()));
548 CharUnits maxFieldAlign;
551 if (block->capturesCXXThis()) {
552 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
553 "Can't capture 'this' outside a method");
554 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
556 // Theoretically, this could be in a different address space, so
557 // don't assume standard pointer size/align.
558 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
559 std::pair<CharUnits,CharUnits> tinfo
560 = CGM.getContext().getTypeInfoInChars(thisType);
561 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
563 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
564 Qualifiers::OCL_None,
565 nullptr, llvmType, thisType));
568 // Next, all the block captures.
569 for (const auto &CI : block->captures()) {
570 const VarDecl *variable = CI.getVariable();
572 if (CI.isEscapingByref()) {
573 // We have to copy/dispose of the __block reference.
574 info.NeedsCopyDispose = true;
576 // Just use void* instead of a pointer to the byref type.
577 CharUnits align = CGM.getPointerAlign();
578 maxFieldAlign = std::max(maxFieldAlign, align);
580 // Since a __block variable cannot be captured by lambdas, its type and
581 // the capture field type should always match.
582 assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
583 "capture type differs from the variable type");
584 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
585 Qualifiers::OCL_None, &CI,
586 CGM.VoidPtrTy, variable->getType()));
590 // Otherwise, build a layout chunk with the size and alignment of
592 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
593 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
597 QualType VT = getCaptureFieldType(*CGF, CI);
599 // If we have a lifetime qualifier, honor it for capture purposes.
600 // That includes *not* copying it if it's __unsafe_unretained.
601 Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
604 case Qualifiers::OCL_None: llvm_unreachable("impossible");
605 case Qualifiers::OCL_ExplicitNone:
606 case Qualifiers::OCL_Autoreleasing:
609 case Qualifiers::OCL_Strong:
610 case Qualifiers::OCL_Weak:
611 info.NeedsCopyDispose = true;
614 // Block pointers require copy/dispose. So do Objective-C pointers.
615 } else if (VT->isObjCRetainableType()) {
616 // But honor the inert __unsafe_unretained qualifier, which doesn't
617 // actually make it into the type system.
618 if (VT->isObjCInertUnsafeUnretainedType()) {
619 lifetime = Qualifiers::OCL_ExplicitNone;
621 info.NeedsCopyDispose = true;
622 // used for mrr below.
623 lifetime = Qualifiers::OCL_Strong;
626 // So do types that require non-trivial copy construction.
627 } else if (CI.hasCopyExpr()) {
628 info.NeedsCopyDispose = true;
629 info.HasCXXObject = true;
630 if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
631 info.CapturesNonExternalType = true;
633 // So do C structs that require non-trivial copy construction or
635 } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
636 VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
637 info.NeedsCopyDispose = true;
639 // And so do types with destructors.
640 } else if (CGM.getLangOpts().CPlusPlus) {
641 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
642 if (!record->hasTrivialDestructor()) {
643 info.HasCXXObject = true;
644 info.NeedsCopyDispose = true;
645 if (!record->isExternallyVisible())
646 info.CapturesNonExternalType = true;
651 CharUnits size = C.getTypeSizeInChars(VT);
652 CharUnits align = C.getDeclAlign(variable);
654 maxFieldAlign = std::max(maxFieldAlign, align);
656 llvm::Type *llvmType =
657 CGM.getTypes().ConvertTypeForMem(VT);
660 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
663 // If that was everything, we're done here.
664 if (layout.empty()) {
666 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
667 info.CanBeGlobal = true;
671 // Sort the layout by alignment. We have to use a stable sort here
672 // to get reproducible results. There should probably be an
673 // llvm::array_pod_stable_sort.
674 llvm::stable_sort(layout);
676 // Needed for blocks layout info.
677 info.BlockHeaderForcedGapOffset = info.BlockSize;
678 info.BlockHeaderForcedGapSize = CharUnits::Zero();
680 CharUnits &blockSize = info.BlockSize;
681 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
683 // Assuming that the first byte in the header is maximally aligned,
684 // get the alignment of the first byte following the header.
685 CharUnits endAlign = getLowBit(blockSize);
687 // If the end of the header isn't satisfactorily aligned for the
688 // maximum thing, look for things that are okay with the header-end
689 // alignment, and keep appending them until we get something that's
690 // aligned right. This algorithm is only guaranteed optimal if
691 // that condition is satisfied at some point; otherwise we can get
693 // header // next byte has alignment 4
694 // something_with_size_5; // next byte has alignment 1
695 // something_with_alignment_8;
696 // which has 7 bytes of padding, as opposed to the naive solution
697 // which might have less (?).
698 if (endAlign < maxFieldAlign) {
699 SmallVectorImpl<BlockLayoutChunk>::iterator
700 li = layout.begin() + 1, le = layout.end();
702 // Look for something that the header end is already
703 // satisfactorily aligned for.
704 for (; li != le && endAlign < li->Alignment; ++li)
707 // If we found something that's naturally aligned for the end of
708 // the header, keep adding things...
710 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
711 for (; li != le; ++li) {
712 assert(endAlign >= li->Alignment);
714 li->setIndex(info, elementTypes.size(), blockSize);
715 elementTypes.push_back(li->Type);
716 blockSize += li->Size;
717 endAlign = getLowBit(blockSize);
719 // ...until we get to the alignment of the maximum field.
720 if (endAlign >= maxFieldAlign) {
724 // Don't re-append everything we just appended.
725 layout.erase(first, li);
729 assert(endAlign == getLowBit(blockSize));
731 // At this point, we just have to add padding if the end align still
732 // isn't aligned right.
733 if (endAlign < maxFieldAlign) {
734 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
735 CharUnits padding = newBlockSize - blockSize;
737 // If we haven't yet added any fields, remember that there was an
738 // initial gap; this need to go into the block layout bit map.
739 if (blockSize == info.BlockHeaderForcedGapOffset) {
740 info.BlockHeaderForcedGapSize = padding;
743 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
744 padding.getQuantity()));
745 blockSize = newBlockSize;
746 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
749 assert(endAlign >= maxFieldAlign);
750 assert(endAlign == getLowBit(blockSize));
751 // Slam everything else on now. This works because they have
752 // strictly decreasing alignment and we expect that size is always a
753 // multiple of alignment.
754 for (SmallVectorImpl<BlockLayoutChunk>::iterator
755 li = layout.begin(), le = layout.end(); li != le; ++li) {
756 if (endAlign < li->Alignment) {
757 // size may not be multiple of alignment. This can only happen with
758 // an over-aligned variable. We will be adding a padding field to
759 // make the size be multiple of alignment.
760 CharUnits padding = li->Alignment - endAlign;
761 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
762 padding.getQuantity()));
763 blockSize += padding;
764 endAlign = getLowBit(blockSize);
766 assert(endAlign >= li->Alignment);
767 li->setIndex(info, elementTypes.size(), blockSize);
768 elementTypes.push_back(li->Type);
769 blockSize += li->Size;
770 endAlign = getLowBit(blockSize);
774 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
777 /// Enter the scope of a block. This should be run at the entrance to
778 /// a full-expression so that the block's cleanups are pushed at the
779 /// right place in the stack.
780 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
781 assert(CGF.HaveInsertPoint());
783 // Allocate the block info and place it at the head of the list.
784 CGBlockInfo &blockInfo =
785 *new CGBlockInfo(block, CGF.CurFn->getName());
786 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
787 CGF.FirstBlockInfo = &blockInfo;
789 // Compute information about the layout, etc., of this block,
790 // pushing cleanups as necessary.
791 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
793 // Nothing else to do if it can be global.
794 if (blockInfo.CanBeGlobal) return;
796 // Make the allocation for the block.
797 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
798 blockInfo.BlockAlign, "block");
800 // If there are cleanups to emit, enter them (but inactive).
801 if (!blockInfo.NeedsCopyDispose) return;
803 // Walk through the captures (in order) and find the ones not
804 // captured by constant.
805 for (const auto &CI : block->captures()) {
806 // Ignore __block captures; there's nothing special in the
807 // on-stack block that we need to do for them.
808 if (CI.isByRef()) continue;
810 // Ignore variables that are constant-captured.
811 const VarDecl *variable = CI.getVariable();
812 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
813 if (capture.isConstant()) continue;
815 // Ignore objects that aren't destructed.
816 QualType VT = getCaptureFieldType(CGF, CI);
817 QualType::DestructionKind dtorKind = VT.isDestructedType();
818 if (dtorKind == QualType::DK_none) continue;
820 CodeGenFunction::Destroyer *destroyer;
822 // Block captures count as local values and have imprecise semantics.
823 // They also can't be arrays, so need to worry about that.
825 // For const-qualified captures, emit clang.arc.use to ensure the captured
826 // object doesn't get released while we are still depending on its validity
828 if (VT.isConstQualified() &&
829 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
830 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
831 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
832 "expected ObjC ARC to be enabled");
833 destroyer = CodeGenFunction::emitARCIntrinsicUse;
834 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
835 destroyer = CodeGenFunction::destroyARCStrongImprecise;
837 destroyer = CGF.getDestroyer(dtorKind);
840 // GEP down to the address.
842 CGF.Builder.CreateStructGEP(blockInfo.LocalAddress, capture.getIndex());
844 // We can use that GEP as the dominating IP.
845 if (!blockInfo.DominatingIP)
846 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
848 CleanupKind cleanupKind = InactiveNormalCleanup;
849 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
850 if (useArrayEHCleanup)
851 cleanupKind = InactiveNormalAndEHCleanup;
853 CGF.pushDestroy(cleanupKind, addr, VT,
854 destroyer, useArrayEHCleanup);
856 // Remember where that cleanup was.
857 capture.setCleanup(CGF.EHStack.stable_begin());
861 /// Enter a full-expression with a non-trivial number of objects to
862 /// clean up. This is in this file because, at the moment, the only
863 /// kind of cleanup object is a BlockDecl*.
864 void CodeGenFunction::enterNonTrivialFullExpression(const FullExpr *E) {
865 if (const auto EWC = dyn_cast<ExprWithCleanups>(E)) {
866 assert(EWC->getNumObjects() != 0);
867 for (const ExprWithCleanups::CleanupObject &C : EWC->getObjects())
868 enterBlockScope(*this, C);
872 /// Find the layout for the given block in a linked list and remove it.
873 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
874 const BlockDecl *block) {
876 assert(head && *head);
877 CGBlockInfo *cur = *head;
879 // If this is the block we're looking for, splice it out of the list.
880 if (cur->getBlockDecl() == block) {
881 *head = cur->NextBlockInfo;
885 head = &cur->NextBlockInfo;
889 /// Destroy a chain of block layouts.
890 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
891 assert(head && "destroying an empty chain");
893 CGBlockInfo *cur = head;
894 head = cur->NextBlockInfo;
896 } while (head != nullptr);
899 /// Emit a block literal expression in the current function.
900 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
901 // If the block has no captures, we won't have a pre-computed
903 if (!blockExpr->getBlockDecl()->hasCaptures()) {
904 // The block literal is emitted as a global variable, and the block invoke
905 // function has to be extracted from its initializer.
906 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
909 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
910 computeBlockInfo(CGM, this, blockInfo);
911 blockInfo.BlockExpression = blockExpr;
912 return EmitBlockLiteral(blockInfo);
915 // Find the block info for this block and take ownership of it.
916 std::unique_ptr<CGBlockInfo> blockInfo;
917 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
918 blockExpr->getBlockDecl()));
920 blockInfo->BlockExpression = blockExpr;
921 return EmitBlockLiteral(*blockInfo);
924 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
925 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
927 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
928 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
929 auto GenVoidPtrSize = CharUnits::fromQuantity(
930 CGM.getTarget().getPointerWidth(
931 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
933 // Using the computed layout, generate the actual block function.
934 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
935 CodeGenFunction BlockCGF{CGM, true};
936 BlockCGF.SanOpts = SanOpts;
937 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
938 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
939 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
941 // If there is nothing to capture, we can emit this as a global block.
942 if (blockInfo.CanBeGlobal)
943 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
945 // Otherwise, we have to emit this as a local block.
947 Address blockAddr = blockInfo.LocalAddress;
948 assert(blockAddr.isValid() && "block has no address!");
951 llvm::Constant *descriptor;
954 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
955 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
956 // block just returns the original block and releasing it is a no-op.
957 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
958 ? CGM.getNSConcreteGlobalBlock()
959 : CGM.getNSConcreteStackBlock();
960 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
962 // Build the block descriptor.
963 descriptor = buildBlockDescriptor(CGM, blockInfo);
965 // Compute the initial on-stack block flags.
966 flags = BLOCK_HAS_SIGNATURE;
967 if (blockInfo.HasCapturedVariableLayout)
968 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
969 if (blockInfo.needsCopyDisposeHelpers())
970 flags |= BLOCK_HAS_COPY_DISPOSE;
971 if (blockInfo.HasCXXObject)
972 flags |= BLOCK_HAS_CXX_OBJ;
973 if (blockInfo.UsesStret)
974 flags |= BLOCK_USE_STRET;
975 if (blockInfo.getBlockDecl()->doesNotEscape())
976 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
979 auto projectField = [&](unsigned index, const Twine &name) -> Address {
980 return Builder.CreateStructGEP(blockAddr, index, name);
982 auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
983 Builder.CreateStore(value, projectField(index, name));
986 // Initialize the block header.
988 // We assume all the header fields are densely packed.
991 auto addHeaderField = [&](llvm::Value *value, CharUnits size,
993 storeField(value, index, name);
999 addHeaderField(isa, getPointerSize(), "block.isa");
1000 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1001 getIntSize(), "block.flags");
1002 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
1006 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
1007 getIntSize(), "block.size");
1009 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
1010 getIntSize(), "block.align");
1012 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
1014 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
1015 else if (auto *Helper =
1016 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1017 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
1020 CharUnits::fromQuantity(
1021 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
1027 // Finally, capture all the values into the block.
1028 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1031 if (blockDecl->capturesCXXThis()) {
1033 projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
1034 Builder.CreateStore(LoadCXXThis(), addr);
1037 // Next, captured variables.
1038 for (const auto &CI : blockDecl->captures()) {
1039 const VarDecl *variable = CI.getVariable();
1040 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1042 // Ignore constant captures.
1043 if (capture.isConstant()) continue;
1045 QualType type = capture.fieldType();
1047 // This will be a [[type]]*, except that a byref entry will just be
1049 Address blockField = projectField(capture.getIndex(), "block.captured");
1051 // Compute the address of the thing we're going to move into the
1053 Address src = Address::invalid();
1055 if (blockDecl->isConversionFromLambda()) {
1056 // The lambda capture in a lambda's conversion-to-block-pointer is
1057 // special; we'll simply emit it directly.
1058 src = Address::invalid();
1059 } else if (CI.isEscapingByref()) {
1060 if (BlockInfo && CI.isNested()) {
1061 // We need to use the capture from the enclosing block.
1062 const CGBlockInfo::Capture &enclosingCapture =
1063 BlockInfo->getCapture(variable);
1065 // This is a [[type]]*, except that a byref entry will just be an i8**.
1066 src = Builder.CreateStructGEP(LoadBlockStruct(),
1067 enclosingCapture.getIndex(),
1068 "block.capture.addr");
1070 auto I = LocalDeclMap.find(variable);
1071 assert(I != LocalDeclMap.end());
1075 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1076 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1077 type.getNonReferenceType(), VK_LValue,
1079 src = EmitDeclRefLValue(&declRef).getAddress();
1082 // For byrefs, we just write the pointer to the byref struct into
1083 // the block field. There's no need to chase the forwarding
1084 // pointer at this point, since we're building something that will
1085 // live a shorter life than the stack byref anyway.
1086 if (CI.isEscapingByref()) {
1087 // Get a void* that points to the byref struct.
1088 llvm::Value *byrefPointer;
1090 byrefPointer = Builder.CreateLoad(src, "byref.capture");
1092 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
1094 // Write that void* into the capture field.
1095 Builder.CreateStore(byrefPointer, blockField);
1097 // If we have a copy constructor, evaluate that into the block field.
1098 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
1099 if (blockDecl->isConversionFromLambda()) {
1100 // If we have a lambda conversion, emit the expression
1101 // directly into the block instead.
1103 AggValueSlot::forAddr(blockField, Qualifiers(),
1104 AggValueSlot::IsDestructed,
1105 AggValueSlot::DoesNotNeedGCBarriers,
1106 AggValueSlot::IsNotAliased,
1107 AggValueSlot::DoesNotOverlap);
1108 EmitAggExpr(copyExpr, Slot);
1110 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
1113 // If it's a reference variable, copy the reference into the block field.
1114 } else if (type->isReferenceType()) {
1115 Builder.CreateStore(src.getPointer(), blockField);
1117 // If type is const-qualified, copy the value into the block field.
1118 } else if (type.isConstQualified() &&
1119 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1120 CGM.getCodeGenOpts().OptimizationLevel != 0) {
1121 llvm::Value *value = Builder.CreateLoad(src, "captured");
1122 Builder.CreateStore(value, blockField);
1124 // If this is an ARC __strong block-pointer variable, don't do a
1127 // TODO: this can be generalized into the normal initialization logic:
1128 // we should never need to do a block-copy when initializing a local
1129 // variable, because the local variable's lifetime should be strictly
1130 // contained within the stack block's.
1131 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1132 type->isBlockPointerType()) {
1133 // Load the block and do a simple retain.
1134 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1135 value = EmitARCRetainNonBlock(value);
1137 // Do a primitive store to the block field.
1138 Builder.CreateStore(value, blockField);
1140 // Otherwise, fake up a POD copy into the block field.
1142 // Fake up a new variable so that EmitScalarInit doesn't think
1143 // we're referring to the variable in its own initializer.
1144 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1145 ImplicitParamDecl::Other);
1147 // We use one of these or the other depending on whether the
1148 // reference is nested.
1149 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1150 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1151 type, VK_LValue, SourceLocation());
1153 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1154 &declRef, VK_RValue);
1155 // FIXME: Pass a specific location for the expr init so that the store is
1156 // attributed to a reasonable location - otherwise it may be attributed to
1157 // locations of subexpressions in the initialization.
1158 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1159 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1160 /*captured by init*/ false);
1163 // Activate the cleanup if layout pushed one.
1164 if (!CI.isByRef()) {
1165 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1166 if (cleanup.isValid())
1167 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
1171 // Cast to the converted block-pointer type, which happens (somewhat
1172 // unfortunately) to be a pointer to function type.
1173 llvm::Value *result = Builder.CreatePointerCast(
1174 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1177 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1185 llvm::Type *CodeGenModule::getBlockDescriptorType() {
1186 if (BlockDescriptorType)
1187 return BlockDescriptorType;
1189 llvm::Type *UnsignedLongTy =
1190 getTypes().ConvertType(getContext().UnsignedLongTy);
1192 // struct __block_descriptor {
1193 // unsigned long reserved;
1194 // unsigned long block_size;
1196 // // later, the following will be added
1199 // void (*copyHelper)();
1200 // void (*copyHelper)();
1201 // } helpers; // !!! optional
1203 // const char *signature; // the block signature
1204 // const char *layout; // reserved
1206 BlockDescriptorType = llvm::StructType::create(
1207 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1209 // Now form a pointer to that.
1210 unsigned AddrSpace = 0;
1211 if (getLangOpts().OpenCL)
1212 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1213 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1214 return BlockDescriptorType;
1217 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1218 if (GenericBlockLiteralType)
1219 return GenericBlockLiteralType;
1221 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1223 if (getLangOpts().OpenCL) {
1224 // struct __opencl_block_literal_generic {
1227 // __generic void *__invoke;
1228 // /* custom fields */
1230 SmallVector<llvm::Type *, 8> StructFields(
1231 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1232 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1233 for (auto I : Helper->getCustomFieldTypes())
1234 StructFields.push_back(I);
1236 GenericBlockLiteralType = llvm::StructType::create(
1237 StructFields, "struct.__opencl_block_literal_generic");
1239 // struct __block_literal_generic {
1243 // void (*__invoke)(void *);
1244 // struct __block_descriptor *__descriptor;
1246 GenericBlockLiteralType =
1247 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1248 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1251 return GenericBlockLiteralType;
1254 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1255 ReturnValueSlot ReturnValue) {
1256 const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
1257 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1258 llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1259 llvm::Value *Func = nullptr;
1260 QualType FnType = BPT->getPointeeType();
1261 ASTContext &Ctx = getContext();
1264 if (getLangOpts().OpenCL) {
1265 // For OpenCL, BlockPtr is already casted to generic block literal.
1267 // First argument of a block call is a generic block literal casted to
1268 // generic void pointer, i.e. i8 addrspace(4)*
1269 llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1270 BlockPtr, CGM.getOpenCLRuntime().getGenericVoidPointerType());
1271 QualType VoidPtrQualTy = Ctx.getPointerType(
1272 Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1273 Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1274 // And the rest of the arguments.
1275 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1277 // We *can* call the block directly unless it is a function argument.
1278 if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1279 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1281 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1282 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1285 // Bitcast the block literal to a generic block literal.
1286 BlockPtr = Builder.CreatePointerCast(
1287 BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1288 // Get pointer to the block invoke function
1289 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1291 // First argument is a block literal casted to a void pointer
1292 BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1293 Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1294 // And the rest of the arguments.
1295 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1297 // Load the function.
1298 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1301 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1302 const CGFunctionInfo &FnInfo =
1303 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1305 // Cast the function pointer to the right type.
1306 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1308 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1309 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1311 // Prepare the callee.
1312 CGCallee Callee(CGCalleeInfo(), Func);
1314 // And call the block.
1315 return EmitCall(FnInfo, Callee, ReturnValue, Args);
1318 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1319 assert(BlockInfo && "evaluating block ref without block information?");
1320 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1322 // Handle constant captures.
1323 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1325 Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1326 "block.capture.addr");
1328 if (variable->isEscapingByref()) {
1329 // addr should be a void** right now. Load, then cast the result
1332 auto &byrefInfo = getBlockByrefInfo(variable);
1333 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1335 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1336 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1338 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1339 variable->getName());
1342 assert((!variable->isNonEscapingByref() ||
1343 capture.fieldType()->isReferenceType()) &&
1344 "the capture field of a non-escaping variable should have a "
1346 if (capture.fieldType()->isReferenceType())
1347 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1352 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1353 llvm::Constant *Addr) {
1354 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1356 assert(Ok && "Trying to replace an already-existing global block!");
1360 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1362 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1365 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1366 blockInfo.BlockExpression = BE;
1368 // Compute information about the layout, etc., of this block.
1369 computeBlockInfo(*this, nullptr, blockInfo);
1371 // Using that metadata, generate the actual block function.
1373 CodeGenFunction::DeclMapTy LocalDeclMap;
1374 CodeGenFunction(*this).GenerateBlockFunction(
1375 GlobalDecl(), blockInfo, LocalDeclMap,
1376 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1379 return getAddrOfGlobalBlockIfEmitted(BE);
1382 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1383 const CGBlockInfo &blockInfo,
1384 llvm::Constant *blockFn) {
1385 assert(blockInfo.CanBeGlobal);
1386 // Callers should detect this case on their own: calling this function
1387 // generally requires computing layout information, which is a waste of time
1388 // if we've already emitted this block.
1389 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1390 "Refusing to re-emit a global block.");
1392 // Generate the constants for the block literal initializer.
1393 ConstantInitBuilder builder(CGM);
1394 auto fields = builder.beginStruct();
1396 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1397 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1401 fields.addNullPointer(CGM.Int8PtrPtrTy);
1403 fields.add(CGM.getNSConcreteGlobalBlock());
1406 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1407 if (blockInfo.UsesStret)
1408 flags |= BLOCK_USE_STRET;
1410 fields.addInt(CGM.IntTy, flags.getBitMask());
1413 fields.addInt(CGM.IntTy, 0);
1415 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1416 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1420 fields.add(blockFn);
1424 fields.add(buildBlockDescriptor(CGM, blockInfo));
1425 } else if (auto *Helper =
1426 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1427 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1432 unsigned AddrSpace = 0;
1433 if (CGM.getContext().getLangOpts().OpenCL)
1434 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1436 llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
1437 "__block_literal_global", blockInfo.BlockAlign,
1438 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1440 literal->addAttribute("objc_arc_inert");
1442 // Windows does not allow globals to be initialised to point to globals in
1443 // different DLLs. Any such variables must run code to initialise them.
1445 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1446 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1448 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1450 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1451 b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
1453 // We can't use the normal LLVM global initialisation array, because we
1454 // need to specify that this runs early in library initialisation.
1455 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1456 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1457 Init, ".block_isa_init_ptr");
1458 InitVar->setSection(".CRT$XCLa");
1459 CGM.addUsedGlobal(InitVar);
1462 // Return a constant of the appropriately-casted type.
1463 llvm::Type *RequiredType =
1464 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1465 llvm::Constant *Result =
1466 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1467 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1468 if (CGM.getContext().getLangOpts().OpenCL)
1469 CGM.getOpenCLRuntime().recordBlockInfo(
1470 blockInfo.BlockExpression,
1471 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
1475 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1478 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1480 // Allocate a stack slot like for any local variable to guarantee optimal
1481 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1482 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1483 Builder.CreateStore(arg, alloc);
1484 if (CGDebugInfo *DI = getDebugInfo()) {
1485 if (CGM.getCodeGenOpts().getDebugInfo() >=
1486 codegenoptions::LimitedDebugInfo) {
1487 DI->setLocation(D->getLocation());
1488 DI->EmitDeclareOfBlockLiteralArgVariable(
1489 *BlockInfo, D->getName(), argNum,
1490 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1494 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1495 ApplyDebugLocation Scope(*this, StartLoc);
1497 // Instead of messing around with LocalDeclMap, just set the value
1498 // directly as BlockPointer.
1499 BlockPointer = Builder.CreatePointerCast(
1501 BlockInfo->StructureType->getPointerTo(
1502 getContext().getLangOpts().OpenCL
1503 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1508 Address CodeGenFunction::LoadBlockStruct() {
1509 assert(BlockInfo && "not in a block invocation function!");
1510 assert(BlockPointer && "no block pointer set!");
1511 return Address(BlockPointer, BlockInfo->BlockAlign);
1515 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1516 const CGBlockInfo &blockInfo,
1517 const DeclMapTy &ldm,
1518 bool IsLambdaConversionToBlock,
1519 bool BuildGlobalBlock) {
1520 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1524 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1526 BlockInfo = &blockInfo;
1528 // Arrange for local static and local extern declarations to appear
1529 // to be local to this function as well, in case they're directly
1530 // referenced in a block.
1531 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1532 const auto *var = dyn_cast<VarDecl>(i->first);
1533 if (var && !var->hasLocalStorage())
1534 setAddrOfLocalVar(var, i->second);
1537 // Begin building the function declaration.
1539 // Build the argument list.
1540 FunctionArgList args;
1542 // The first argument is the block pointer. Just take it as a void*
1543 // and cast it later.
1544 QualType selfTy = getContext().VoidPtrTy;
1546 // For OpenCL passed block pointer can be private AS local variable or
1547 // global AS program scope variable (for the case with and without captures).
1548 // Generic AS is used therefore to be able to accommodate both private and
1549 // generic AS in one implementation.
1550 if (getLangOpts().OpenCL)
1551 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1552 getContext().VoidTy, LangAS::opencl_generic));
1554 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1556 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1557 SourceLocation(), II, selfTy,
1558 ImplicitParamDecl::ObjCSelf);
1559 args.push_back(&SelfDecl);
1561 // Now add the rest of the parameters.
1562 args.append(blockDecl->param_begin(), blockDecl->param_end());
1564 // Create the function declaration.
1565 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1566 const CGFunctionInfo &fnInfo =
1567 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1568 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1569 blockInfo.UsesStret = true;
1571 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1573 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1574 llvm::Function *fn = llvm::Function::Create(
1575 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1576 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1578 if (BuildGlobalBlock) {
1579 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1580 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1582 buildGlobalBlock(CGM, blockInfo,
1583 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1586 // Begin generating the function.
1587 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1588 blockDecl->getLocation(),
1589 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1591 // Okay. Undo some of what StartFunction did.
1593 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1594 // won't delete the dbg.declare intrinsics for captured variables.
1595 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1596 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1597 // Allocate a stack slot for it, so we can point the debugger to it
1598 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1601 // Set the DebugLocation to empty, so the store is recognized as a
1602 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1603 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1604 Builder.CreateStore(BlockPointer, Alloca);
1605 BlockPointerDbgLoc = Alloca.getPointer();
1608 // If we have a C++ 'this' reference, go ahead and force it into
1610 if (blockDecl->capturesCXXThis()) {
1611 Address addr = Builder.CreateStructGEP(
1612 LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
1613 CXXThisValue = Builder.CreateLoad(addr, "this");
1616 // Also force all the constant captures.
1617 for (const auto &CI : blockDecl->captures()) {
1618 const VarDecl *variable = CI.getVariable();
1619 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1620 if (!capture.isConstant()) continue;
1622 CharUnits align = getContext().getDeclAlign(variable);
1624 CreateMemTemp(variable->getType(), align, "block.captured-const");
1626 Builder.CreateStore(capture.getConstant(), alloca);
1628 setAddrOfLocalVar(variable, alloca);
1631 // Save a spot to insert the debug information for all the DeclRefExprs.
1632 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1633 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1636 if (IsLambdaConversionToBlock)
1637 EmitLambdaBlockInvokeBody();
1639 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1640 incrementProfileCounter(blockDecl->getBody());
1641 EmitStmt(blockDecl->getBody());
1644 // Remember where we were...
1645 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1647 // Go back to the entry.
1649 Builder.SetInsertPoint(entry, entry_ptr);
1651 // Emit debug information for all the DeclRefExprs.
1652 // FIXME: also for 'this'
1653 if (CGDebugInfo *DI = getDebugInfo()) {
1654 for (const auto &CI : blockDecl->captures()) {
1655 const VarDecl *variable = CI.getVariable();
1656 DI->EmitLocation(Builder, variable->getLocation());
1658 if (CGM.getCodeGenOpts().getDebugInfo() >=
1659 codegenoptions::LimitedDebugInfo) {
1660 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1661 if (capture.isConstant()) {
1662 auto addr = LocalDeclMap.find(variable)->second;
1663 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1668 DI->EmitDeclareOfBlockDeclRefVariable(
1669 variable, BlockPointerDbgLoc, Builder, blockInfo,
1670 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1673 // Recover location if it was changed in the above loop.
1674 DI->EmitLocation(Builder,
1675 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1678 // And resume where we left off.
1679 if (resume == nullptr)
1680 Builder.ClearInsertionPoint();
1682 Builder.SetInsertPoint(resume);
1684 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1689 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1690 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1691 const LangOptions &LangOpts) {
1692 if (CI.getCopyExpr()) {
1693 assert(!CI.isByRef());
1694 // don't bother computing flags
1695 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1697 BlockFieldFlags Flags;
1698 if (CI.isEscapingByref()) {
1699 Flags = BLOCK_FIELD_IS_BYREF;
1700 if (T.isObjCGCWeak())
1701 Flags |= BLOCK_FIELD_IS_WEAK;
1702 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1705 Flags = BLOCK_FIELD_IS_OBJECT;
1706 bool isBlockPointer = T->isBlockPointerType();
1708 Flags = BLOCK_FIELD_IS_BLOCK;
1710 switch (T.isNonTrivialToPrimitiveCopy()) {
1711 case QualType::PCK_Struct:
1712 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1714 case QualType::PCK_ARCWeak:
1715 // We need to register __weak direct captures with the runtime.
1716 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1717 case QualType::PCK_ARCStrong:
1718 // We need to retain the copied value for __strong direct captures.
1719 // If it's a block pointer, we have to copy the block and assign that to
1720 // the destination pointer, so we might as well use _Block_object_assign.
1721 // Otherwise we can avoid that.
1722 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1723 : BlockCaptureEntityKind::BlockObject,
1725 case QualType::PCK_Trivial:
1726 case QualType::PCK_VolatileTrivial: {
1727 if (!T->isObjCRetainableType())
1728 // For all other types, the memcpy is fine.
1729 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1731 // Special rules for ARC captures:
1732 Qualifiers QS = T.getQualifiers();
1734 // Non-ARC captures of retainable pointers are strong and
1735 // therefore require a call to _Block_object_assign.
1736 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1737 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1739 // Otherwise the memcpy is fine.
1740 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1743 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1746 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1747 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1748 const LangOptions &LangOpts);
1750 /// Find the set of block captures that need to be explicitly copied or destroy.
1751 static void findBlockCapturedManagedEntities(
1752 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1753 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
1754 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1755 const VarDecl *Variable = CI.getVariable();
1756 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1757 if (Capture.isConstant())
1760 QualType VT = Capture.fieldType();
1761 auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1762 auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
1763 if (CopyInfo.first != BlockCaptureEntityKind::None ||
1764 DisposeInfo.first != BlockCaptureEntityKind::None)
1765 ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1766 CopyInfo.second, DisposeInfo.second, CI,
1770 // Sort the captures by offset.
1771 llvm::sort(ManagedCaptures);
1775 /// Release a __block variable.
1776 struct CallBlockRelease final : EHScopeStack::Cleanup {
1778 BlockFieldFlags FieldFlags;
1779 bool LoadBlockVarAddr, CanThrow;
1781 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1783 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1786 void Emit(CodeGenFunction &CGF, Flags flags) override {
1787 llvm::Value *BlockVarAddr;
1788 if (LoadBlockVarAddr) {
1789 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1790 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1792 BlockVarAddr = Addr.getPointer();
1795 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1798 } // end anonymous namespace
1800 /// Check if \p T is a C++ class that has a destructor that can throw.
1801 bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1802 if (const auto *RD = T->getAsCXXRecordDecl())
1803 if (const CXXDestructorDecl *DD = RD->getDestructor())
1804 return DD->getType()->castAs<FunctionProtoType>()->canThrow();
1808 // Return a string that has the information about a capture.
1809 static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1810 CaptureStrKind StrKind,
1811 CharUnits BlockAlignment,
1812 CodeGenModule &CGM) {
1814 ASTContext &Ctx = CGM.getContext();
1815 const BlockDecl::Capture &CI = *E.CI;
1816 QualType CaptureTy = CI.getVariable()->getType();
1818 BlockCaptureEntityKind Kind;
1819 BlockFieldFlags Flags;
1821 // CaptureStrKind::Merged should be passed only when the operations and the
1822 // flags are the same for copy and dispose.
1823 assert((StrKind != CaptureStrKind::Merged ||
1824 (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
1825 "different operations and flags");
1827 if (StrKind == CaptureStrKind::DisposeHelper) {
1828 Kind = E.DisposeKind;
1829 Flags = E.DisposeFlags;
1832 Flags = E.CopyFlags;
1836 case BlockCaptureEntityKind::CXXRecord: {
1838 SmallString<256> TyStr;
1839 llvm::raw_svector_ostream Out(TyStr);
1840 CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
1841 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1844 case BlockCaptureEntityKind::ARCWeak:
1847 case BlockCaptureEntityKind::ARCStrong:
1850 case BlockCaptureEntityKind::BlockObject: {
1851 const VarDecl *Var = CI.getVariable();
1852 unsigned F = Flags.getBitMask();
1853 if (F & BLOCK_FIELD_IS_BYREF) {
1855 if (F & BLOCK_FIELD_IS_WEAK)
1858 // If CaptureStrKind::Merged is passed, check both the copy expression
1859 // and the destructor.
1860 if (StrKind != CaptureStrKind::DisposeHelper) {
1861 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1864 if (StrKind != CaptureStrKind::CopyHelper) {
1865 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1870 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1871 if (F == BLOCK_FIELD_IS_BLOCK)
1878 case BlockCaptureEntityKind::NonTrivialCStruct: {
1879 bool IsVolatile = CaptureTy.isVolatileQualified();
1880 CharUnits Alignment =
1881 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1884 std::string FuncStr;
1885 if (StrKind == CaptureStrKind::DisposeHelper)
1886 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1887 CaptureTy, Alignment, IsVolatile, Ctx);
1889 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1890 // It has all the information that the destructor string has.
1891 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1892 CaptureTy, Alignment, IsVolatile, Ctx);
1893 // The underscore is necessary here because non-trivial copy constructor
1894 // and destructor strings can start with a number.
1895 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1898 case BlockCaptureEntityKind::None:
1905 static std::string getCopyDestroyHelperFuncName(
1906 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1907 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1908 assert((StrKind == CaptureStrKind::CopyHelper ||
1909 StrKind == CaptureStrKind::DisposeHelper) &&
1910 "unexpected CaptureStrKind");
1911 std::string Name = StrKind == CaptureStrKind::CopyHelper
1912 ? "__copy_helper_block_"
1913 : "__destroy_helper_block_";
1914 if (CGM.getLangOpts().Exceptions)
1916 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1918 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1920 for (const BlockCaptureManagedEntity &E : Captures) {
1921 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
1922 Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
1928 static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1929 Address Field, QualType CaptureType,
1930 BlockFieldFlags Flags, bool ForCopyHelper,
1931 VarDecl *Var, CodeGenFunction &CGF) {
1932 bool EHOnly = ForCopyHelper;
1934 switch (CaptureKind) {
1935 case BlockCaptureEntityKind::CXXRecord:
1936 case BlockCaptureEntityKind::ARCWeak:
1937 case BlockCaptureEntityKind::NonTrivialCStruct:
1938 case BlockCaptureEntityKind::ARCStrong: {
1939 if (CaptureType.isDestructedType() &&
1940 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1941 CodeGenFunction::Destroyer *Destroyer =
1942 CaptureKind == BlockCaptureEntityKind::ARCStrong
1943 ? CodeGenFunction::destroyARCStrongImprecise
1944 : CGF.getDestroyer(CaptureType.isDestructedType());
1947 : CGF.getCleanupKind(CaptureType.isDestructedType());
1948 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1952 case BlockCaptureEntityKind::BlockObject: {
1953 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1954 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1955 // Calls to _Block_object_dispose along the EH path in the copy helper
1956 // function don't throw as newly-copied __block variables always have a
1957 // reference count of 2.
1959 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1960 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1965 case BlockCaptureEntityKind::None:
1970 static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1972 const CGFunctionInfo &FI,
1973 CodeGenModule &CGM) {
1974 if (CapturesNonExternalType) {
1975 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1977 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1978 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1979 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
1980 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1983 /// Generate the copy-helper function for a block closure object:
1984 /// static void block_copy_helper(block_t *dst, block_t *src);
1985 /// The runtime will have previously initialized 'dst' by doing a
1986 /// bit-copy of 'src'.
1988 /// Note that this copies an entire block closure object to the heap;
1989 /// it should not be confused with a 'byref copy helper', which moves
1990 /// the contents of an individual __block variable to the heap.
1992 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1993 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1994 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
1995 std::string FuncName =
1996 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
1997 CaptureStrKind::CopyHelper, CGM);
1999 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2000 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2002 ASTContext &C = getContext();
2004 QualType ReturnTy = C.VoidTy;
2006 FunctionArgList args;
2007 ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2008 args.push_back(&DstDecl);
2009 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2010 args.push_back(&SrcDecl);
2012 const CGFunctionInfo &FI =
2013 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2015 // FIXME: it would be nice if these were mergeable with things with
2016 // identical semantics.
2017 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2019 llvm::Function *Fn =
2020 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2021 FuncName, &CGM.getModule());
2022 if (CGM.supportsCOMDAT())
2023 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2025 IdentifierInfo *II = &C.Idents.get(FuncName);
2027 SmallVector<QualType, 2> ArgTys;
2028 ArgTys.push_back(C.VoidPtrTy);
2029 ArgTys.push_back(C.VoidPtrTy);
2030 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2032 FunctionDecl *FD = FunctionDecl::Create(
2033 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2034 FunctionTy, nullptr, SC_Static, false, false);
2036 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2038 StartFunction(FD, ReturnTy, Fn, FI, args);
2039 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
2040 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
2042 Address src = GetAddrOfLocalVar(&SrcDecl);
2043 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
2044 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
2046 Address dst = GetAddrOfLocalVar(&DstDecl);
2047 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
2048 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
2050 for (const auto &CopiedCapture : CopiedCaptures) {
2051 const BlockDecl::Capture &CI = *CopiedCapture.CI;
2052 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
2053 QualType captureType = CI.getVariable()->getType();
2054 BlockFieldFlags flags = CopiedCapture.CopyFlags;
2056 unsigned index = capture.getIndex();
2057 Address srcField = Builder.CreateStructGEP(src, index);
2058 Address dstField = Builder.CreateStructGEP(dst, index);
2060 switch (CopiedCapture.CopyKind) {
2061 case BlockCaptureEntityKind::CXXRecord:
2062 // If there's an explicit copy expression, we do that.
2063 assert(CI.getCopyExpr() && "copy expression for variable is missing");
2064 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
2066 case BlockCaptureEntityKind::ARCWeak:
2067 EmitARCCopyWeak(dstField, srcField);
2069 case BlockCaptureEntityKind::NonTrivialCStruct: {
2070 // If this is a C struct that requires non-trivial copy construction,
2071 // emit a call to its copy constructor.
2072 QualType varType = CI.getVariable()->getType();
2073 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2074 MakeAddrLValue(srcField, varType));
2077 case BlockCaptureEntityKind::ARCStrong: {
2078 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2079 // At -O0, store null into the destination field (so that the
2080 // storeStrong doesn't over-release) and then call storeStrong.
2081 // This is a workaround to not having an initStrong call.
2082 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2083 auto *ty = cast<llvm::PointerType>(srcValue->getType());
2084 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2085 Builder.CreateStore(null, dstField);
2086 EmitARCStoreStrongCall(dstField, srcValue, true);
2088 // With optimization enabled, take advantage of the fact that
2089 // the blocks runtime guarantees a memcpy of the block data, and
2090 // just emit a retain of the src field.
2092 EmitARCRetainNonBlock(srcValue);
2094 // Unless EH cleanup is required, we don't need this anymore, so kill
2095 // it. It's not quite worth the annoyance to avoid creating it in the
2097 if (!needsEHCleanup(captureType.isDestructedType()))
2098 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
2102 case BlockCaptureEntityKind::BlockObject: {
2103 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2104 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2105 llvm::Value *dstAddr =
2106 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2107 llvm::Value *args[] = {
2108 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2111 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2112 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2114 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2117 case BlockCaptureEntityKind::None:
2121 // Ensure that we destroy the copied object if an exception is thrown later
2122 // in the helper function.
2123 pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
2124 /*ForCopyHelper*/ true, CI.getVariable(), *this);
2129 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2132 static BlockFieldFlags
2133 getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2135 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2136 if (T->isBlockPointerType())
2137 Flags = BLOCK_FIELD_IS_BLOCK;
2141 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2142 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2143 const LangOptions &LangOpts) {
2144 if (CI.isEscapingByref()) {
2145 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2146 if (T.isObjCGCWeak())
2147 Flags |= BLOCK_FIELD_IS_WEAK;
2148 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2151 switch (T.isDestructedType()) {
2152 case QualType::DK_cxx_destructor:
2153 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2154 case QualType::DK_objc_strong_lifetime:
2155 // Use objc_storeStrong for __strong direct captures; the
2156 // dynamic tools really like it when we do this.
2157 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2158 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2159 case QualType::DK_objc_weak_lifetime:
2160 // Support __weak direct captures.
2161 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2162 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2163 case QualType::DK_nontrivial_c_struct:
2164 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2166 case QualType::DK_none: {
2167 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2168 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2169 !LangOpts.ObjCAutoRefCount)
2170 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2171 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2172 // Otherwise, we have nothing to do.
2173 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2176 llvm_unreachable("after exhaustive DestructionKind switch");
2179 /// Generate the destroy-helper function for a block closure object:
2180 /// static void block_destroy_helper(block_t *theBlock);
2182 /// Note that this destroys a heap-allocated block closure object;
2183 /// it should not be confused with a 'byref destroy helper', which
2184 /// destroys the heap-allocated contents of an individual __block
2187 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2188 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
2189 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
2190 std::string FuncName =
2191 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
2192 CaptureStrKind::DisposeHelper, CGM);
2194 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2195 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2197 ASTContext &C = getContext();
2199 QualType ReturnTy = C.VoidTy;
2201 FunctionArgList args;
2202 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2203 args.push_back(&SrcDecl);
2205 const CGFunctionInfo &FI =
2206 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2208 // FIXME: We'd like to put these into a mergable by content, with
2209 // internal linkage.
2210 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2212 llvm::Function *Fn =
2213 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2214 FuncName, &CGM.getModule());
2215 if (CGM.supportsCOMDAT())
2216 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2218 IdentifierInfo *II = &C.Idents.get(FuncName);
2220 SmallVector<QualType, 1> ArgTys;
2221 ArgTys.push_back(C.VoidPtrTy);
2222 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2224 FunctionDecl *FD = FunctionDecl::Create(
2225 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2226 FunctionTy, nullptr, SC_Static, false, false);
2228 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2230 StartFunction(FD, ReturnTy, Fn, FI, args);
2231 markAsIgnoreThreadCheckingAtRuntime(Fn);
2233 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
2235 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
2237 Address src = GetAddrOfLocalVar(&SrcDecl);
2238 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
2239 src = Builder.CreateBitCast(src, structPtrTy, "block");
2241 CodeGenFunction::RunCleanupsScope cleanups(*this);
2243 for (const auto &DestroyedCapture : DestroyedCaptures) {
2244 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2245 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
2246 BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
2248 Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
2250 pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
2251 CI.getVariable()->getType(), flags,
2252 /*ForCopyHelper*/ false, CI.getVariable(), *this);
2255 cleanups.ForceCleanup();
2259 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2264 /// Emits the copy/dispose helper functions for a __block object of id type.
2265 class ObjectByrefHelpers final : public BlockByrefHelpers {
2266 BlockFieldFlags Flags;
2269 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2270 : BlockByrefHelpers(alignment), Flags(flags) {}
2272 void emitCopy(CodeGenFunction &CGF, Address destField,
2273 Address srcField) override {
2274 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2276 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2277 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2279 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2281 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2282 llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
2284 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
2285 CGF.EmitNounwindRuntimeCall(fn, args);
2288 void emitDispose(CodeGenFunction &CGF, Address field) override {
2289 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2290 llvm::Value *value = CGF.Builder.CreateLoad(field);
2292 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2295 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2296 id.AddInteger(Flags.getBitMask());
2300 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2301 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2303 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2305 void emitCopy(CodeGenFunction &CGF, Address destField,
2306 Address srcField) override {
2307 CGF.EmitARCMoveWeak(destField, srcField);
2310 void emitDispose(CodeGenFunction &CGF, Address field) override {
2311 CGF.EmitARCDestroyWeak(field);
2314 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2315 // 0 is distinguishable from all pointers and byref flags
2320 /// Emits the copy/dispose helpers for an ARC __block __strong variable
2321 /// that's not of block-pointer type.
2322 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2324 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2326 void emitCopy(CodeGenFunction &CGF, Address destField,
2327 Address srcField) override {
2328 // Do a "move" by copying the value and then zeroing out the old
2331 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2334 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2336 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2337 CGF.Builder.CreateStore(null, destField);
2338 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2339 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2342 CGF.Builder.CreateStore(value, destField);
2343 CGF.Builder.CreateStore(null, srcField);
2346 void emitDispose(CodeGenFunction &CGF, Address field) override {
2347 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2350 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2351 // 1 is distinguishable from all pointers and byref flags
2356 /// Emits the copy/dispose helpers for an ARC __block __strong
2357 /// variable that's of block-pointer type.
2358 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2360 ARCStrongBlockByrefHelpers(CharUnits alignment)
2361 : BlockByrefHelpers(alignment) {}
2363 void emitCopy(CodeGenFunction &CGF, Address destField,
2364 Address srcField) override {
2365 // Do the copy with objc_retainBlock; that's all that
2366 // _Block_object_assign would do anyway, and we'd have to pass the
2367 // right arguments to make sure it doesn't get no-op'ed.
2368 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2369 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2370 CGF.Builder.CreateStore(copy, destField);
2373 void emitDispose(CodeGenFunction &CGF, Address field) override {
2374 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2377 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2378 // 2 is distinguishable from all pointers and byref flags
2383 /// Emits the copy/dispose helpers for a __block variable with a
2384 /// nontrivial copy constructor or destructor.
2385 class CXXByrefHelpers final : public BlockByrefHelpers {
2387 const Expr *CopyExpr;
2390 CXXByrefHelpers(CharUnits alignment, QualType type,
2391 const Expr *copyExpr)
2392 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2394 bool needsCopy() const override { return CopyExpr != nullptr; }
2395 void emitCopy(CodeGenFunction &CGF, Address destField,
2396 Address srcField) override {
2397 if (!CopyExpr) return;
2398 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2401 void emitDispose(CodeGenFunction &CGF, Address field) override {
2402 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2403 CGF.PushDestructorCleanup(VarType, field);
2404 CGF.PopCleanupBlocks(cleanupDepth);
2407 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2408 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2412 /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2414 class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2418 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2419 : BlockByrefHelpers(alignment), VarType(type) {}
2421 void emitCopy(CodeGenFunction &CGF, Address destField,
2422 Address srcField) override {
2423 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2424 CGF.MakeAddrLValue(srcField, VarType));
2427 bool needsDispose() const override {
2428 return VarType.isDestructedType();
2431 void emitDispose(CodeGenFunction &CGF, Address field) override {
2432 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2433 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2434 CGF.PopCleanupBlocks(cleanupDepth);
2437 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2438 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2441 } // end anonymous namespace
2443 static llvm::Constant *
2444 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2445 BlockByrefHelpers &generator) {
2446 ASTContext &Context = CGF.getContext();
2448 QualType ReturnTy = Context.VoidTy;
2450 FunctionArgList args;
2451 ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2452 args.push_back(&Dst);
2454 ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2455 args.push_back(&Src);
2457 const CGFunctionInfo &FI =
2458 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2460 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2462 // FIXME: We'd like to put these into a mergable by content, with
2463 // internal linkage.
2464 llvm::Function *Fn =
2465 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2466 "__Block_byref_object_copy_", &CGF.CGM.getModule());
2469 = &Context.Idents.get("__Block_byref_object_copy_");
2471 SmallVector<QualType, 2> ArgTys;
2472 ArgTys.push_back(Context.VoidPtrTy);
2473 ArgTys.push_back(Context.VoidPtrTy);
2474 QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
2476 FunctionDecl *FD = FunctionDecl::Create(
2477 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2478 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2480 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2482 CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
2484 if (generator.needsCopy()) {
2485 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
2488 Address destField = CGF.GetAddrOfLocalVar(&Dst);
2489 destField = Address(CGF.Builder.CreateLoad(destField),
2490 byrefInfo.ByrefAlignment);
2491 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
2492 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2496 Address srcField = CGF.GetAddrOfLocalVar(&Src);
2497 srcField = Address(CGF.Builder.CreateLoad(srcField),
2498 byrefInfo.ByrefAlignment);
2499 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
2500 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2503 generator.emitCopy(CGF, destField, srcField);
2506 CGF.FinishFunction();
2508 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2511 /// Build the copy helper for a __block variable.
2512 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2513 const BlockByrefInfo &byrefInfo,
2514 BlockByrefHelpers &generator) {
2515 CodeGenFunction CGF(CGM);
2516 return generateByrefCopyHelper(CGF, byrefInfo, generator);
2519 /// Generate code for a __block variable's dispose helper.
2520 static llvm::Constant *
2521 generateByrefDisposeHelper(CodeGenFunction &CGF,
2522 const BlockByrefInfo &byrefInfo,
2523 BlockByrefHelpers &generator) {
2524 ASTContext &Context = CGF.getContext();
2525 QualType R = Context.VoidTy;
2527 FunctionArgList args;
2528 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2529 ImplicitParamDecl::Other);
2530 args.push_back(&Src);
2532 const CGFunctionInfo &FI =
2533 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2535 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2537 // FIXME: We'd like to put these into a mergable by content, with
2538 // internal linkage.
2539 llvm::Function *Fn =
2540 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2541 "__Block_byref_object_dispose_",
2542 &CGF.CGM.getModule());
2545 = &Context.Idents.get("__Block_byref_object_dispose_");
2547 SmallVector<QualType, 1> ArgTys;
2548 ArgTys.push_back(Context.VoidPtrTy);
2549 QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
2551 FunctionDecl *FD = FunctionDecl::Create(
2552 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2553 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2555 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2557 CGF.StartFunction(FD, R, Fn, FI, args);
2559 if (generator.needsDispose()) {
2560 Address addr = CGF.GetAddrOfLocalVar(&Src);
2561 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2562 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2563 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2564 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2566 generator.emitDispose(CGF, addr);
2569 CGF.FinishFunction();
2571 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2574 /// Build the dispose helper for a __block variable.
2575 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2576 const BlockByrefInfo &byrefInfo,
2577 BlockByrefHelpers &generator) {
2578 CodeGenFunction CGF(CGM);
2579 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2582 /// Lazily build the copy and dispose helpers for a __block variable
2583 /// with the given information.
2585 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2587 llvm::FoldingSetNodeID id;
2588 generator.Profile(id);
2591 BlockByrefHelpers *node
2592 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2593 if (node) return static_cast<T*>(node);
2595 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2596 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2598 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2599 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2603 /// Build the copy and dispose helpers for the given __block variable
2604 /// emission. Places the helpers in the global cache. Returns null
2605 /// if no helpers are required.
2607 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2608 const AutoVarEmission &emission) {
2609 const VarDecl &var = *emission.Variable;
2610 assert(var.isEscapingByref() &&
2611 "only escaping __block variables need byref helpers");
2613 QualType type = var.getType();
2615 auto &byrefInfo = getBlockByrefInfo(&var);
2617 // The alignment we care about for the purposes of uniquing byref
2618 // helpers is the alignment of the actual byref value field.
2619 CharUnits valueAlignment =
2620 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2622 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2623 const Expr *copyExpr =
2624 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2625 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2627 return ::buildByrefHelpers(
2628 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2631 // If type is a non-trivial C struct type that is non-trivial to
2632 // destructly move or destroy, build the copy and dispose helpers.
2633 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2634 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2635 return ::buildByrefHelpers(
2636 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2638 // Otherwise, if we don't have a retainable type, there's nothing to do.
2639 // that the runtime does extra copies.
2640 if (!type->isObjCRetainableType()) return nullptr;
2642 Qualifiers qs = type.getQualifiers();
2644 // If we have lifetime, that dominates.
2645 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2647 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2649 // These are just bits as far as the runtime is concerned.
2650 case Qualifiers::OCL_ExplicitNone:
2651 case Qualifiers::OCL_Autoreleasing:
2654 // Tell the runtime that this is ARC __weak, called by the
2656 case Qualifiers::OCL_Weak:
2657 return ::buildByrefHelpers(CGM, byrefInfo,
2658 ARCWeakByrefHelpers(valueAlignment));
2660 // ARC __strong __block variables need to be retained.
2661 case Qualifiers::OCL_Strong:
2662 // Block pointers need to be copied, and there's no direct
2663 // transfer possible.
2664 if (type->isBlockPointerType()) {
2665 return ::buildByrefHelpers(CGM, byrefInfo,
2666 ARCStrongBlockByrefHelpers(valueAlignment));
2668 // Otherwise, we transfer ownership of the retain from the stack
2671 return ::buildByrefHelpers(CGM, byrefInfo,
2672 ARCStrongByrefHelpers(valueAlignment));
2675 llvm_unreachable("fell out of lifetime switch!");
2678 BlockFieldFlags flags;
2679 if (type->isBlockPointerType()) {
2680 flags |= BLOCK_FIELD_IS_BLOCK;
2681 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2682 type->isObjCObjectPointerType()) {
2683 flags |= BLOCK_FIELD_IS_OBJECT;
2688 if (type.isObjCGCWeak())
2689 flags |= BLOCK_FIELD_IS_WEAK;
2691 return ::buildByrefHelpers(CGM, byrefInfo,
2692 ObjectByrefHelpers(valueAlignment, flags));
2695 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2697 bool followForward) {
2698 auto &info = getBlockByrefInfo(var);
2699 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2702 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2703 const BlockByrefInfo &info,
2705 const llvm::Twine &name) {
2706 // Chase the forwarding address if requested.
2707 if (followForward) {
2708 Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
2709 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2712 return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
2715 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2720 /// void *__forwarding;
2721 /// int32_t __flags;
2723 /// void *__copy_helper; // only if needed
2724 /// void *__destroy_helper; // only if needed
2725 /// void *__byref_variable_layout;// only if needed
2726 /// char padding[X]; // only if needed
2730 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2731 auto it = BlockByrefInfos.find(D);
2732 if (it != BlockByrefInfos.end())
2735 llvm::StructType *byrefType =
2736 llvm::StructType::create(getLLVMContext(),
2737 "struct.__block_byref_" + D->getNameAsString());
2739 QualType Ty = D->getType();
2742 SmallVector<llvm::Type *, 8> types;
2745 types.push_back(Int8PtrTy);
2746 size += getPointerSize();
2748 // void *__forwarding;
2749 types.push_back(llvm::PointerType::getUnqual(byrefType));
2750 size += getPointerSize();
2753 types.push_back(Int32Ty);
2754 size += CharUnits::fromQuantity(4);
2757 types.push_back(Int32Ty);
2758 size += CharUnits::fromQuantity(4);
2760 // Note that this must match *exactly* the logic in buildByrefHelpers.
2761 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2762 if (hasCopyAndDispose) {
2763 /// void *__copy_helper;
2764 types.push_back(Int8PtrTy);
2765 size += getPointerSize();
2767 /// void *__destroy_helper;
2768 types.push_back(Int8PtrTy);
2769 size += getPointerSize();
2772 bool HasByrefExtendedLayout = false;
2773 Qualifiers::ObjCLifetime Lifetime;
2774 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2775 HasByrefExtendedLayout) {
2776 /// void *__byref_variable_layout;
2777 types.push_back(Int8PtrTy);
2778 size += CharUnits::fromQuantity(PointerSizeInBytes);
2782 llvm::Type *varTy = ConvertTypeForMem(Ty);
2784 bool packed = false;
2785 CharUnits varAlign = getContext().getDeclAlign(D);
2786 CharUnits varOffset = size.alignTo(varAlign);
2788 // We may have to insert padding.
2789 if (varOffset != size) {
2790 llvm::Type *paddingTy =
2791 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2793 types.push_back(paddingTy);
2796 // Conversely, we might have to prevent LLVM from inserting padding.
2797 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2798 > varAlign.getQuantity()) {
2801 types.push_back(varTy);
2803 byrefType->setBody(types, packed);
2805 BlockByrefInfo info;
2806 info.Type = byrefType;
2807 info.FieldIndex = types.size() - 1;
2808 info.FieldOffset = varOffset;
2809 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2811 auto pair = BlockByrefInfos.insert({D, info});
2812 assert(pair.second && "info was inserted recursively?");
2813 return pair.first->second;
2816 /// Initialize the structural components of a __block variable, i.e.
2817 /// everything but the actual object.
2818 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2819 // Find the address of the local.
2820 Address addr = emission.Addr;
2822 // That's an alloca of the byref structure type.
2823 llvm::StructType *byrefType = cast<llvm::StructType>(
2824 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2826 unsigned nextHeaderIndex = 0;
2827 CharUnits nextHeaderOffset;
2828 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2829 const Twine &name) {
2830 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
2831 Builder.CreateStore(value, fieldAddr);
2834 nextHeaderOffset += fieldSize;
2837 // Build the byref helpers if necessary. This is null if we don't need any.
2838 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2840 const VarDecl &D = *emission.Variable;
2841 QualType type = D.getType();
2843 bool HasByrefExtendedLayout;
2844 Qualifiers::ObjCLifetime ByrefLifetime;
2845 bool ByRefHasLifetime =
2846 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2850 // Initialize the 'isa', which is just 0 or 1.
2852 if (type.isObjCGCWeak())
2854 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2855 storeHeaderField(V, getPointerSize(), "byref.isa");
2857 // Store the address of the variable into its own forwarding pointer.
2858 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2861 // c) the flags field is set to either 0 if no helper functions are
2862 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2864 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2865 if (ByRefHasLifetime) {
2866 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2867 else switch (ByrefLifetime) {
2868 case Qualifiers::OCL_Strong:
2869 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2871 case Qualifiers::OCL_Weak:
2872 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2874 case Qualifiers::OCL_ExplicitNone:
2875 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2877 case Qualifiers::OCL_None:
2878 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2879 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2884 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2885 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2886 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2887 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2888 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2889 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2890 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2891 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2892 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2893 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2894 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2895 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2896 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2897 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2898 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2899 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2904 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2905 getIntSize(), "byref.flags");
2907 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2908 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2909 storeHeaderField(V, getIntSize(), "byref.size");
2912 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2913 "byref.copyHelper");
2914 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2915 "byref.disposeHelper");
2918 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2919 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2920 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2924 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2926 llvm::FunctionCallee F = CGM.getBlockObjectDispose();
2927 llvm::Value *args[] = {
2928 Builder.CreateBitCast(V, Int8PtrTy),
2929 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2933 EmitRuntimeCallOrInvoke(F, args);
2935 EmitNounwindRuntimeCall(F, args);
2938 void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2939 BlockFieldFlags Flags,
2940 bool LoadBlockVarAddr, bool CanThrow) {
2941 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2945 /// Adjust the declaration of something from the blocks API.
2946 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2947 llvm::Constant *C) {
2948 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2950 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2951 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2952 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2953 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2955 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2956 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2957 "expected Function or GlobalVariable");
2959 const NamedDecl *ND = nullptr;
2960 for (const auto &Result : DC->lookup(&II))
2961 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2962 (ND = dyn_cast<VarDecl>(Result)))
2965 // TODO: support static blocks runtime
2966 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2967 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2968 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2970 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2971 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2975 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2976 GV->hasExternalLinkage())
2977 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2979 CGM.setDSOLocal(GV);
2982 llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
2983 if (BlockObjectDispose)
2984 return BlockObjectDispose;
2986 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2987 llvm::FunctionType *fty
2988 = llvm::FunctionType::get(VoidTy, args, false);
2989 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2990 configureBlocksRuntimeObject(
2991 *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
2992 return BlockObjectDispose;
2995 llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
2996 if (BlockObjectAssign)
2997 return BlockObjectAssign;
2999 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
3000 llvm::FunctionType *fty
3001 = llvm::FunctionType::get(VoidTy, args, false);
3002 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
3003 configureBlocksRuntimeObject(
3004 *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
3005 return BlockObjectAssign;
3008 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
3009 if (NSConcreteGlobalBlock)
3010 return NSConcreteGlobalBlock;
3012 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
3013 Int8PtrTy->getPointerTo(),
3015 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
3016 return NSConcreteGlobalBlock;
3019 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
3020 if (NSConcreteStackBlock)
3021 return NSConcreteStackBlock;
3023 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
3024 Int8PtrTy->getPointerTo(),
3026 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
3027 return NSConcreteStackBlock;