[RISCV][FMV] Support target_clones (#85786)
[llvm-project.git] / clang / lib / CodeGen / CGBlocks.cpp
blob684fda74407313bfd1f7b0cc4979059fb6aceb3c
1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit blocks.
11 //===----------------------------------------------------------------------===//
13 #include "CGBlocks.h"
14 #include "CGCXXABI.h"
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/Attr.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/CodeGen/ConstantInitBuilder.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ScopedPrinter.h"
29 #include <algorithm>
30 #include <cstdio>
32 using namespace clang;
33 using namespace CodeGen;
35 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
36 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
37 NoEscape(false), HasCXXObject(false), UsesStret(false),
38 HasCapturedVariableLayout(false), CapturesNonExternalType(false),
39 LocalAddress(RawAddress::invalid()), StructureType(nullptr),
40 Block(block) {
42 // Skip asm prefix, if any. 'name' is usually taken directly from
43 // the mangled name of the enclosing function.
44 if (!name.empty() && name[0] == '\01')
45 name = name.substr(1);
48 // Anchor the vtable to this translation unit.
49 BlockByrefHelpers::~BlockByrefHelpers() {}
51 /// Build the given block as a global block.
52 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo,
54 llvm::Constant *blockFn);
56 /// Build the helper function to copy a block.
57 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
62 /// Build the helper function to dispose of a block.
63 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
64 const CGBlockInfo &blockInfo) {
65 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
68 namespace {
70 enum class CaptureStrKind {
71 // String for the copy helper.
72 CopyHelper,
73 // String for the dispose helper.
74 DisposeHelper,
75 // Merge the strings for the copy helper and dispose helper.
76 Merged
79 } // end anonymous namespace
81 static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
82 CaptureStrKind StrKind,
83 CharUnits BlockAlignment,
84 CodeGenModule &CGM);
86 static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
87 CodeGenModule &CGM) {
88 std::string Name = "__block_descriptor_";
89 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
91 if (BlockInfo.NeedsCopyDispose) {
92 if (CGM.getLangOpts().Exceptions)
93 Name += "e";
94 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
95 Name += "a";
96 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
98 for (auto &Cap : BlockInfo.SortedCaptures) {
99 if (Cap.isConstantOrTrivial())
100 continue;
102 Name += llvm::to_string(Cap.getOffset().getQuantity());
104 if (Cap.CopyKind == Cap.DisposeKind) {
105 // If CopyKind and DisposeKind are the same, merge the capture
106 // information.
107 assert(Cap.CopyKind != BlockCaptureEntityKind::None &&
108 "shouldn't see BlockCaptureManagedEntity that is None");
109 Name += getBlockCaptureStr(Cap, CaptureStrKind::Merged,
110 BlockInfo.BlockAlign, CGM);
111 } else {
112 // If CopyKind and DisposeKind are not the same, which can happen when
113 // either Kind is None or the captured object is a __strong block,
114 // concatenate the copy and dispose strings.
115 Name += getBlockCaptureStr(Cap, CaptureStrKind::CopyHelper,
116 BlockInfo.BlockAlign, CGM);
117 Name += getBlockCaptureStr(Cap, CaptureStrKind::DisposeHelper,
118 BlockInfo.BlockAlign, CGM);
121 Name += "_";
124 std::string TypeAtEncoding;
126 if (!CGM.getCodeGenOpts().DisableBlockSignatureString) {
127 TypeAtEncoding =
128 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
129 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms
130 /// as a separator between symbol name and symbol version.
131 std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
133 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
134 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
135 return Name;
138 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
139 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
140 /// meta-data and contains stationary information about the block literal.
141 /// Its definition will have 4 (or optionally 6) words.
142 /// \code
143 /// struct Block_descriptor {
144 /// unsigned long reserved;
145 /// unsigned long size; // size of Block_literal metadata in bytes.
146 /// void *copy_func_helper_decl; // optional copy helper.
147 /// void *destroy_func_decl; // optional destructor helper.
148 /// void *block_method_encoding_address; // @encode for block literal signature.
149 /// void *block_layout_info; // encoding of captured block variables.
150 /// };
151 /// \endcode
152 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
153 const CGBlockInfo &blockInfo) {
154 ASTContext &C = CGM.getContext();
156 llvm::IntegerType *ulong =
157 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
158 llvm::PointerType *i8p = nullptr;
159 if (CGM.getLangOpts().OpenCL)
160 i8p = llvm::PointerType::get(
161 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
162 else
163 i8p = CGM.VoidPtrTy;
165 std::string descName;
167 // If an equivalent block descriptor global variable exists, return it.
168 if (C.getLangOpts().ObjC &&
169 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
170 descName = getBlockDescriptorName(blockInfo, CGM);
171 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
172 return desc;
175 // If there isn't an equivalent block descriptor global variable, create a new
176 // one.
177 ConstantInitBuilder builder(CGM);
178 auto elements = builder.beginStruct();
180 // reserved
181 elements.addInt(ulong, 0);
183 // Size
184 // FIXME: What is the right way to say this doesn't fit? We should give
185 // a user diagnostic in that case. Better fix would be to change the
186 // API to size_t.
187 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
189 // Optional copy/dispose helpers.
190 bool hasInternalHelper = false;
191 if (blockInfo.NeedsCopyDispose) {
192 // copy_func_helper_decl
193 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
194 elements.add(copyHelper);
196 // destroy_func_decl
197 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
198 elements.add(disposeHelper);
200 if (cast<llvm::Function>(copyHelper->stripPointerCasts())
201 ->hasInternalLinkage() ||
202 cast<llvm::Function>(disposeHelper->stripPointerCasts())
203 ->hasInternalLinkage())
204 hasInternalHelper = true;
207 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
208 if (CGM.getCodeGenOpts().DisableBlockSignatureString) {
209 elements.addNullPointer(i8p);
210 } else {
211 std::string typeAtEncoding =
212 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
213 elements.add(CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer());
216 // GC layout.
217 if (C.getLangOpts().ObjC) {
218 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
219 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
220 else
221 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
223 else
224 elements.addNullPointer(i8p);
226 unsigned AddrSpace = 0;
227 if (C.getLangOpts().OpenCL)
228 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
230 llvm::GlobalValue::LinkageTypes linkage;
231 if (descName.empty()) {
232 linkage = llvm::GlobalValue::InternalLinkage;
233 descName = "__block_descriptor_tmp";
234 } else if (hasInternalHelper) {
235 // If either the copy helper or the dispose helper has internal linkage,
236 // the block descriptor must have internal linkage too.
237 linkage = llvm::GlobalValue::InternalLinkage;
238 } else {
239 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
242 llvm::GlobalVariable *global =
243 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
244 /*constant*/ true, linkage, AddrSpace);
246 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
247 if (CGM.supportsCOMDAT())
248 global->setComdat(CGM.getModule().getOrInsertComdat(descName));
249 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
250 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
253 return global;
257 Purely notional variadic template describing the layout of a block.
259 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
260 struct Block_literal {
261 /// Initialized to one of:
262 /// extern void *_NSConcreteStackBlock[];
263 /// extern void *_NSConcreteGlobalBlock[];
265 /// In theory, we could start one off malloc'ed by setting
266 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
267 /// this isa:
268 /// extern void *_NSConcreteMallocBlock[];
269 struct objc_class *isa;
271 /// These are the flags (with corresponding bit number) that the
272 /// compiler is actually supposed to know about.
273 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
274 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
275 /// descriptor provides copy and dispose helper functions
276 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
277 /// object with a nontrivial destructor or copy constructor
278 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
279 /// as global memory
280 /// 29. BLOCK_USE_STRET - indicates that the block function
281 /// uses stret, which objc_msgSend needs to know about
282 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
283 /// @encoded signature string
284 /// And we're not supposed to manipulate these:
285 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
286 /// to malloc'ed memory
287 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
288 /// to GC-allocated memory
289 /// Additionally, the bottom 16 bits are a reference count which
290 /// should be zero on the stack.
291 int flags;
293 /// Reserved; should be zero-initialized.
294 int reserved;
296 /// Function pointer generated from block literal.
297 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
299 /// Block description metadata generated from block literal.
300 struct Block_descriptor *block_descriptor;
302 /// Captured values follow.
303 _CapturesTypes captures...;
307 namespace {
308 /// A chunk of data that we actually have to capture in the block.
309 struct BlockLayoutChunk {
310 CharUnits Alignment;
311 CharUnits Size;
312 const BlockDecl::Capture *Capture; // null for 'this'
313 llvm::Type *Type;
314 QualType FieldType;
315 BlockCaptureEntityKind CopyKind, DisposeKind;
316 BlockFieldFlags CopyFlags, DisposeFlags;
318 BlockLayoutChunk(CharUnits align, CharUnits size,
319 const BlockDecl::Capture *capture, llvm::Type *type,
320 QualType fieldType, BlockCaptureEntityKind CopyKind,
321 BlockFieldFlags CopyFlags,
322 BlockCaptureEntityKind DisposeKind,
323 BlockFieldFlags DisposeFlags)
324 : Alignment(align), Size(size), Capture(capture), Type(type),
325 FieldType(fieldType), CopyKind(CopyKind), DisposeKind(DisposeKind),
326 CopyFlags(CopyFlags), DisposeFlags(DisposeFlags) {}
328 /// Tell the block info that this chunk has the given field index.
329 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
330 if (!Capture) {
331 info.CXXThisIndex = index;
332 info.CXXThisOffset = offset;
333 } else {
334 info.SortedCaptures.push_back(CGBlockInfo::Capture::makeIndex(
335 index, offset, FieldType, CopyKind, CopyFlags, DisposeKind,
336 DisposeFlags, Capture));
340 bool isTrivial() const {
341 return CopyKind == BlockCaptureEntityKind::None &&
342 DisposeKind == BlockCaptureEntityKind::None;
346 /// Order by 1) all __strong together 2) next, all block together 3) next,
347 /// all byref together 4) next, all __weak together. Preserve descending
348 /// alignment in all situations.
349 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
350 if (left.Alignment != right.Alignment)
351 return left.Alignment > right.Alignment;
353 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
354 switch (chunk.CopyKind) {
355 case BlockCaptureEntityKind::ARCStrong:
356 return 0;
357 case BlockCaptureEntityKind::BlockObject:
358 switch (chunk.CopyFlags.getBitMask()) {
359 case BLOCK_FIELD_IS_OBJECT:
360 return 0;
361 case BLOCK_FIELD_IS_BLOCK:
362 return 1;
363 case BLOCK_FIELD_IS_BYREF:
364 return 2;
365 default:
366 break;
368 break;
369 case BlockCaptureEntityKind::ARCWeak:
370 return 3;
371 default:
372 break;
374 return 4;
377 return getPrefOrder(left) < getPrefOrder(right);
379 } // end anonymous namespace
381 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
382 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
383 const LangOptions &LangOpts);
385 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
386 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
387 const LangOptions &LangOpts);
389 static void addBlockLayout(CharUnits align, CharUnits size,
390 const BlockDecl::Capture *capture, llvm::Type *type,
391 QualType fieldType,
392 SmallVectorImpl<BlockLayoutChunk> &Layout,
393 CGBlockInfo &Info, CodeGenModule &CGM) {
394 if (!capture) {
395 // 'this' capture.
396 Layout.push_back(BlockLayoutChunk(
397 align, size, capture, type, fieldType, BlockCaptureEntityKind::None,
398 BlockFieldFlags(), BlockCaptureEntityKind::None, BlockFieldFlags()));
399 return;
402 const LangOptions &LangOpts = CGM.getLangOpts();
403 BlockCaptureEntityKind CopyKind, DisposeKind;
404 BlockFieldFlags CopyFlags, DisposeFlags;
406 std::tie(CopyKind, CopyFlags) =
407 computeCopyInfoForBlockCapture(*capture, fieldType, LangOpts);
408 std::tie(DisposeKind, DisposeFlags) =
409 computeDestroyInfoForBlockCapture(*capture, fieldType, LangOpts);
410 Layout.push_back(BlockLayoutChunk(align, size, capture, type, fieldType,
411 CopyKind, CopyFlags, DisposeKind,
412 DisposeFlags));
414 if (Info.NoEscape)
415 return;
417 if (!Layout.back().isTrivial())
418 Info.NeedsCopyDispose = true;
421 /// Determines if the given type is safe for constant capture in C++.
422 static bool isSafeForCXXConstantCapture(QualType type) {
423 const RecordType *recordType =
424 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
426 // Only records can be unsafe.
427 if (!recordType) return true;
429 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
431 // Maintain semantics for classes with non-trivial dtors or copy ctors.
432 if (!record->hasTrivialDestructor()) return false;
433 if (record->hasNonTrivialCopyConstructor()) return false;
435 // Otherwise, we just have to make sure there aren't any mutable
436 // fields that might have changed since initialization.
437 return !record->hasMutableFields();
440 /// It is illegal to modify a const object after initialization.
441 /// Therefore, if a const object has a constant initializer, we don't
442 /// actually need to keep storage for it in the block; we'll just
443 /// rematerialize it at the start of the block function. This is
444 /// acceptable because we make no promises about address stability of
445 /// captured variables.
446 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
447 CodeGenFunction *CGF,
448 const VarDecl *var) {
449 // Return if this is a function parameter. We shouldn't try to
450 // rematerialize default arguments of function parameters.
451 if (isa<ParmVarDecl>(var))
452 return nullptr;
454 QualType type = var->getType();
456 // We can only do this if the variable is const.
457 if (!type.isConstQualified()) return nullptr;
459 // Furthermore, in C++ we have to worry about mutable fields:
460 // C++ [dcl.type.cv]p4:
461 // Except that any class member declared mutable can be
462 // modified, any attempt to modify a const object during its
463 // lifetime results in undefined behavior.
464 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
465 return nullptr;
467 // If the variable doesn't have any initializer (shouldn't this be
468 // invalid?), it's not clear what we should do. Maybe capture as
469 // zero?
470 const Expr *init = var->getInit();
471 if (!init) return nullptr;
473 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
476 /// Get the low bit of a nonzero character count. This is the
477 /// alignment of the nth byte if the 0th byte is universally aligned.
478 static CharUnits getLowBit(CharUnits v) {
479 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
482 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
483 SmallVectorImpl<llvm::Type*> &elementTypes) {
485 assert(elementTypes.empty());
486 if (CGM.getLangOpts().OpenCL) {
487 // The header is basically 'struct { int; int; generic void *;
488 // custom_fields; }'. Assert that struct is packed.
489 auto GenPtrAlign = CharUnits::fromQuantity(
490 CGM.getTarget().getPointerAlign(LangAS::opencl_generic) / 8);
491 auto GenPtrSize = CharUnits::fromQuantity(
492 CGM.getTarget().getPointerWidth(LangAS::opencl_generic) / 8);
493 assert(CGM.getIntSize() <= GenPtrSize);
494 assert(CGM.getIntAlign() <= GenPtrAlign);
495 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
496 elementTypes.push_back(CGM.IntTy); /* total size */
497 elementTypes.push_back(CGM.IntTy); /* align */
498 elementTypes.push_back(
499 CGM.getOpenCLRuntime()
500 .getGenericVoidPointerType()); /* invoke function */
501 unsigned Offset =
502 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
503 unsigned BlockAlign = GenPtrAlign.getQuantity();
504 if (auto *Helper =
505 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
506 for (auto *I : Helper->getCustomFieldTypes()) /* custom fields */ {
507 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
508 // If necessary, add padding fields to the custom fields.
509 unsigned Align = CGM.getDataLayout().getABITypeAlign(I).value();
510 if (BlockAlign < Align)
511 BlockAlign = Align;
512 assert(Offset % Align == 0);
513 Offset += CGM.getDataLayout().getTypeAllocSize(I);
514 elementTypes.push_back(I);
517 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
518 info.BlockSize = CharUnits::fromQuantity(Offset);
519 } else {
520 // The header is basically 'struct { void *; int; int; void *; void *; }'.
521 // Assert that the struct is packed.
522 assert(CGM.getIntSize() <= CGM.getPointerSize());
523 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
524 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
525 info.BlockAlign = CGM.getPointerAlign();
526 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
527 elementTypes.push_back(CGM.VoidPtrTy);
528 elementTypes.push_back(CGM.IntTy);
529 elementTypes.push_back(CGM.IntTy);
530 elementTypes.push_back(CGM.VoidPtrTy);
531 elementTypes.push_back(CGM.getBlockDescriptorType());
535 static QualType getCaptureFieldType(const CodeGenFunction &CGF,
536 const BlockDecl::Capture &CI) {
537 const VarDecl *VD = CI.getVariable();
539 // If the variable is captured by an enclosing block or lambda expression,
540 // use the type of the capture field.
541 if (CGF.BlockInfo && CI.isNested())
542 return CGF.BlockInfo->getCapture(VD).fieldType();
543 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
544 return FD->getType();
545 // If the captured variable is a non-escaping __block variable, the field
546 // type is the reference type. If the variable is a __block variable that
547 // already has a reference type, the field type is the variable's type.
548 return VD->isNonEscapingByref() ?
549 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
552 /// Compute the layout of the given block. Attempts to lay the block
553 /// out with minimal space requirements.
554 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
555 CGBlockInfo &info) {
556 ASTContext &C = CGM.getContext();
557 const BlockDecl *block = info.getBlockDecl();
559 SmallVector<llvm::Type*, 8> elementTypes;
560 initializeForBlockHeader(CGM, info, elementTypes);
561 bool hasNonConstantCustomFields = false;
562 if (auto *OpenCLHelper =
563 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
564 hasNonConstantCustomFields =
565 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
566 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
567 info.StructureType =
568 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
569 info.CanBeGlobal = true;
570 return;
572 else if (C.getLangOpts().ObjC &&
573 CGM.getLangOpts().getGC() == LangOptions::NonGC)
574 info.HasCapturedVariableLayout = true;
576 if (block->doesNotEscape())
577 info.NoEscape = true;
579 // Collect the layout chunks.
580 SmallVector<BlockLayoutChunk, 16> layout;
581 layout.reserve(block->capturesCXXThis() +
582 (block->capture_end() - block->capture_begin()));
584 CharUnits maxFieldAlign;
586 // First, 'this'.
587 if (block->capturesCXXThis()) {
588 assert(CGF && isa_and_nonnull<CXXMethodDecl>(CGF->CurFuncDecl) &&
589 "Can't capture 'this' outside a method");
590 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
592 // Theoretically, this could be in a different address space, so
593 // don't assume standard pointer size/align.
594 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
595 auto TInfo = CGM.getContext().getTypeInfoInChars(thisType);
596 maxFieldAlign = std::max(maxFieldAlign, TInfo.Align);
598 addBlockLayout(TInfo.Align, TInfo.Width, nullptr, llvmType, thisType,
599 layout, info, CGM);
602 // Next, all the block captures.
603 for (const auto &CI : block->captures()) {
604 const VarDecl *variable = CI.getVariable();
606 if (CI.isEscapingByref()) {
607 // Just use void* instead of a pointer to the byref type.
608 CharUnits align = CGM.getPointerAlign();
609 maxFieldAlign = std::max(maxFieldAlign, align);
611 // Since a __block variable cannot be captured by lambdas, its type and
612 // the capture field type should always match.
613 assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() &&
614 "capture type differs from the variable type");
615 addBlockLayout(align, CGM.getPointerSize(), &CI, CGM.VoidPtrTy,
616 variable->getType(), layout, info, CGM);
617 continue;
620 // Otherwise, build a layout chunk with the size and alignment of
621 // the declaration.
622 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
623 info.SortedCaptures.push_back(
624 CGBlockInfo::Capture::makeConstant(constant, &CI));
625 continue;
628 QualType VT = getCaptureFieldType(*CGF, CI);
630 if (CGM.getLangOpts().CPlusPlus)
631 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl())
632 if (CI.hasCopyExpr() || !record->hasTrivialDestructor()) {
633 info.HasCXXObject = true;
634 if (!record->isExternallyVisible())
635 info.CapturesNonExternalType = true;
638 CharUnits size = C.getTypeSizeInChars(VT);
639 CharUnits align = C.getDeclAlign(variable);
641 maxFieldAlign = std::max(maxFieldAlign, align);
643 llvm::Type *llvmType =
644 CGM.getTypes().ConvertTypeForMem(VT);
646 addBlockLayout(align, size, &CI, llvmType, VT, layout, info, CGM);
649 // If that was everything, we're done here.
650 if (layout.empty()) {
651 info.StructureType =
652 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
653 info.CanBeGlobal = true;
654 info.buildCaptureMap();
655 return;
658 // Sort the layout by alignment. We have to use a stable sort here
659 // to get reproducible results. There should probably be an
660 // llvm::array_pod_stable_sort.
661 llvm::stable_sort(layout);
663 // Needed for blocks layout info.
664 info.BlockHeaderForcedGapOffset = info.BlockSize;
665 info.BlockHeaderForcedGapSize = CharUnits::Zero();
667 CharUnits &blockSize = info.BlockSize;
668 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
670 // Assuming that the first byte in the header is maximally aligned,
671 // get the alignment of the first byte following the header.
672 CharUnits endAlign = getLowBit(blockSize);
674 // If the end of the header isn't satisfactorily aligned for the
675 // maximum thing, look for things that are okay with the header-end
676 // alignment, and keep appending them until we get something that's
677 // aligned right. This algorithm is only guaranteed optimal if
678 // that condition is satisfied at some point; otherwise we can get
679 // things like:
680 // header // next byte has alignment 4
681 // something_with_size_5; // next byte has alignment 1
682 // something_with_alignment_8;
683 // which has 7 bytes of padding, as opposed to the naive solution
684 // which might have less (?).
685 if (endAlign < maxFieldAlign) {
686 SmallVectorImpl<BlockLayoutChunk>::iterator
687 li = layout.begin() + 1, le = layout.end();
689 // Look for something that the header end is already
690 // satisfactorily aligned for.
691 for (; li != le && endAlign < li->Alignment; ++li)
694 // If we found something that's naturally aligned for the end of
695 // the header, keep adding things...
696 if (li != le) {
697 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
698 for (; li != le; ++li) {
699 assert(endAlign >= li->Alignment);
701 li->setIndex(info, elementTypes.size(), blockSize);
702 elementTypes.push_back(li->Type);
703 blockSize += li->Size;
704 endAlign = getLowBit(blockSize);
706 // ...until we get to the alignment of the maximum field.
707 if (endAlign >= maxFieldAlign) {
708 ++li;
709 break;
712 // Don't re-append everything we just appended.
713 layout.erase(first, li);
717 assert(endAlign == getLowBit(blockSize));
719 // At this point, we just have to add padding if the end align still
720 // isn't aligned right.
721 if (endAlign < maxFieldAlign) {
722 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
723 CharUnits padding = newBlockSize - blockSize;
725 // If we haven't yet added any fields, remember that there was an
726 // initial gap; this need to go into the block layout bit map.
727 if (blockSize == info.BlockHeaderForcedGapOffset) {
728 info.BlockHeaderForcedGapSize = padding;
731 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
732 padding.getQuantity()));
733 blockSize = newBlockSize;
734 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
737 assert(endAlign >= maxFieldAlign);
738 assert(endAlign == getLowBit(blockSize));
739 // Slam everything else on now. This works because they have
740 // strictly decreasing alignment and we expect that size is always a
741 // multiple of alignment.
742 for (SmallVectorImpl<BlockLayoutChunk>::iterator
743 li = layout.begin(), le = layout.end(); li != le; ++li) {
744 if (endAlign < li->Alignment) {
745 // size may not be multiple of alignment. This can only happen with
746 // an over-aligned variable. We will be adding a padding field to
747 // make the size be multiple of alignment.
748 CharUnits padding = li->Alignment - endAlign;
749 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
750 padding.getQuantity()));
751 blockSize += padding;
752 endAlign = getLowBit(blockSize);
754 assert(endAlign >= li->Alignment);
755 li->setIndex(info, elementTypes.size(), blockSize);
756 elementTypes.push_back(li->Type);
757 blockSize += li->Size;
758 endAlign = getLowBit(blockSize);
761 info.buildCaptureMap();
762 info.StructureType =
763 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
766 /// Emit a block literal expression in the current function.
767 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
768 // If the block has no captures, we won't have a pre-computed
769 // layout for it.
770 if (!blockExpr->getBlockDecl()->hasCaptures())
771 // The block literal is emitted as a global variable, and the block invoke
772 // function has to be extracted from its initializer.
773 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
774 return Block;
776 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
777 computeBlockInfo(CGM, this, blockInfo);
778 blockInfo.BlockExpression = blockExpr;
779 if (!blockInfo.CanBeGlobal)
780 blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
781 blockInfo.BlockAlign, "block");
782 return EmitBlockLiteral(blockInfo);
785 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
786 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
787 auto GenVoidPtrTy =
788 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
789 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
790 auto GenVoidPtrSize = CharUnits::fromQuantity(
791 CGM.getTarget().getPointerWidth(GenVoidPtrAddr) / 8);
792 // Using the computed layout, generate the actual block function.
793 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
794 CodeGenFunction BlockCGF{CGM, true};
795 BlockCGF.SanOpts = SanOpts;
796 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
797 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
798 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
800 // If there is nothing to capture, we can emit this as a global block.
801 if (blockInfo.CanBeGlobal)
802 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
804 // Otherwise, we have to emit this as a local block.
806 RawAddress blockAddr = blockInfo.LocalAddress;
807 assert(blockAddr.isValid() && "block has no address!");
809 llvm::Constant *isa;
810 llvm::Constant *descriptor;
811 BlockFlags flags;
812 if (!IsOpenCL) {
813 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
814 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
815 // block just returns the original block and releasing it is a no-op.
816 llvm::Constant *blockISA = blockInfo.NoEscape
817 ? CGM.getNSConcreteGlobalBlock()
818 : CGM.getNSConcreteStackBlock();
819 isa = blockISA;
821 // Build the block descriptor.
822 descriptor = buildBlockDescriptor(CGM, blockInfo);
824 // Compute the initial on-stack block flags.
825 if (!CGM.getCodeGenOpts().DisableBlockSignatureString)
826 flags = BLOCK_HAS_SIGNATURE;
827 if (blockInfo.HasCapturedVariableLayout)
828 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
829 if (blockInfo.NeedsCopyDispose)
830 flags |= BLOCK_HAS_COPY_DISPOSE;
831 if (blockInfo.HasCXXObject)
832 flags |= BLOCK_HAS_CXX_OBJ;
833 if (blockInfo.UsesStret)
834 flags |= BLOCK_USE_STRET;
835 if (blockInfo.NoEscape)
836 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
839 auto projectField = [&](unsigned index, const Twine &name) -> Address {
840 return Builder.CreateStructGEP(blockAddr, index, name);
842 auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
843 Builder.CreateStore(value, projectField(index, name));
846 // Initialize the block header.
848 // We assume all the header fields are densely packed.
849 unsigned index = 0;
850 CharUnits offset;
851 auto addHeaderField = [&](llvm::Value *value, CharUnits size,
852 const Twine &name) {
853 storeField(value, index, name);
854 offset += size;
855 index++;
858 if (!IsOpenCL) {
859 addHeaderField(isa, getPointerSize(), "block.isa");
860 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
861 getIntSize(), "block.flags");
862 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
863 "block.reserved");
864 } else {
865 addHeaderField(
866 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
867 getIntSize(), "block.size");
868 addHeaderField(
869 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
870 getIntSize(), "block.align");
872 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
873 if (!IsOpenCL)
874 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
875 else if (auto *Helper =
876 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
877 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
878 addHeaderField(
879 I.first,
880 CharUnits::fromQuantity(
881 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
882 I.second);
887 // Finally, capture all the values into the block.
888 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
890 // First, 'this'.
891 if (blockDecl->capturesCXXThis()) {
892 Address addr =
893 projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
894 Builder.CreateStore(LoadCXXThis(), addr);
897 // Next, captured variables.
898 for (const auto &CI : blockDecl->captures()) {
899 const VarDecl *variable = CI.getVariable();
900 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
902 // Ignore constant captures.
903 if (capture.isConstant()) continue;
905 QualType type = capture.fieldType();
907 // This will be a [[type]]*, except that a byref entry will just be
908 // an i8**.
909 Address blockField = projectField(capture.getIndex(), "block.captured");
911 // Compute the address of the thing we're going to move into the
912 // block literal.
913 Address src = Address::invalid();
915 if (blockDecl->isConversionFromLambda()) {
916 // The lambda capture in a lambda's conversion-to-block-pointer is
917 // special; we'll simply emit it directly.
918 src = Address::invalid();
919 } else if (CI.isEscapingByref()) {
920 if (BlockInfo && CI.isNested()) {
921 // We need to use the capture from the enclosing block.
922 const CGBlockInfo::Capture &enclosingCapture =
923 BlockInfo->getCapture(variable);
925 // This is a [[type]]*, except that a byref entry will just be an i8**.
926 src = Builder.CreateStructGEP(LoadBlockStruct(),
927 enclosingCapture.getIndex(),
928 "block.capture.addr");
929 } else {
930 auto I = LocalDeclMap.find(variable);
931 assert(I != LocalDeclMap.end());
932 src = I->second;
934 } else {
935 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
936 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
937 type.getNonReferenceType(), VK_LValue,
938 SourceLocation());
939 src = EmitDeclRefLValue(&declRef).getAddress();
942 // For byrefs, we just write the pointer to the byref struct into
943 // the block field. There's no need to chase the forwarding
944 // pointer at this point, since we're building something that will
945 // live a shorter life than the stack byref anyway.
946 if (CI.isEscapingByref()) {
947 // Get a void* that points to the byref struct.
948 llvm::Value *byrefPointer;
949 if (CI.isNested())
950 byrefPointer = Builder.CreateLoad(src, "byref.capture");
951 else
952 byrefPointer = src.emitRawPointer(*this);
954 // Write that void* into the capture field.
955 Builder.CreateStore(byrefPointer, blockField);
957 // If we have a copy constructor, evaluate that into the block field.
958 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
959 if (blockDecl->isConversionFromLambda()) {
960 // If we have a lambda conversion, emit the expression
961 // directly into the block instead.
962 AggValueSlot Slot =
963 AggValueSlot::forAddr(blockField, Qualifiers(),
964 AggValueSlot::IsDestructed,
965 AggValueSlot::DoesNotNeedGCBarriers,
966 AggValueSlot::IsNotAliased,
967 AggValueSlot::DoesNotOverlap);
968 EmitAggExpr(copyExpr, Slot);
969 } else {
970 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
973 // If it's a reference variable, copy the reference into the block field.
974 } else if (type->getAs<ReferenceType>()) {
975 Builder.CreateStore(src.emitRawPointer(*this), blockField);
977 // If type is const-qualified, copy the value into the block field.
978 } else if (type.isConstQualified() &&
979 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
980 CGM.getCodeGenOpts().OptimizationLevel != 0) {
981 llvm::Value *value = Builder.CreateLoad(src, "captured");
982 Builder.CreateStore(value, blockField);
984 // If this is an ARC __strong block-pointer variable, don't do a
985 // block copy.
987 // TODO: this can be generalized into the normal initialization logic:
988 // we should never need to do a block-copy when initializing a local
989 // variable, because the local variable's lifetime should be strictly
990 // contained within the stack block's.
991 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
992 type->isBlockPointerType()) {
993 // Load the block and do a simple retain.
994 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
995 value = EmitARCRetainNonBlock(value);
997 // Do a primitive store to the block field.
998 Builder.CreateStore(value, blockField);
1000 // Otherwise, fake up a POD copy into the block field.
1001 } else {
1002 // Fake up a new variable so that EmitScalarInit doesn't think
1003 // we're referring to the variable in its own initializer.
1004 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1005 ImplicitParamKind::Other);
1007 // We use one of these or the other depending on whether the
1008 // reference is nested.
1009 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1010 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1011 type, VK_LValue, SourceLocation());
1013 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1014 &declRef, VK_PRValue, FPOptionsOverride());
1015 // FIXME: Pass a specific location for the expr init so that the store is
1016 // attributed to a reasonable location - otherwise it may be attributed to
1017 // locations of subexpressions in the initialization.
1018 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1019 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1020 /*captured by init*/ false);
1023 // Push a cleanup for the capture if necessary.
1024 if (!blockInfo.NoEscape && !blockInfo.NeedsCopyDispose)
1025 continue;
1027 // Ignore __block captures; there's nothing special in the on-stack block
1028 // that we need to do for them.
1029 if (CI.isByRef())
1030 continue;
1032 // Ignore objects that aren't destructed.
1033 QualType::DestructionKind dtorKind = type.isDestructedType();
1034 if (dtorKind == QualType::DK_none)
1035 continue;
1037 CodeGenFunction::Destroyer *destroyer;
1039 // Block captures count as local values and have imprecise semantics.
1040 // They also can't be arrays, so need to worry about that.
1042 // For const-qualified captures, emit clang.arc.use to ensure the captured
1043 // object doesn't get released while we are still depending on its validity
1044 // within the block.
1045 if (type.isConstQualified() &&
1046 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1047 CGM.getCodeGenOpts().OptimizationLevel != 0) {
1048 assert(CGM.getLangOpts().ObjCAutoRefCount &&
1049 "expected ObjC ARC to be enabled");
1050 destroyer = emitARCIntrinsicUse;
1051 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
1052 destroyer = destroyARCStrongImprecise;
1053 } else {
1054 destroyer = getDestroyer(dtorKind);
1057 CleanupKind cleanupKind = NormalCleanup;
1058 bool useArrayEHCleanup = needsEHCleanup(dtorKind);
1059 if (useArrayEHCleanup)
1060 cleanupKind = NormalAndEHCleanup;
1062 // Extend the lifetime of the capture to the end of the scope enclosing the
1063 // block expression except when the block decl is in the list of RetExpr's
1064 // cleanup objects, in which case its lifetime ends after the full
1065 // expression.
1066 auto IsBlockDeclInRetExpr = [&]() {
1067 auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
1068 if (EWC)
1069 for (auto &C : EWC->getObjects())
1070 if (auto *BD = C.dyn_cast<BlockDecl *>())
1071 if (BD == blockDecl)
1072 return true;
1073 return false;
1076 if (IsBlockDeclInRetExpr())
1077 pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
1078 else
1079 pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
1080 useArrayEHCleanup);
1083 // Cast to the converted block-pointer type, which happens (somewhat
1084 // unfortunately) to be a pointer to function type.
1085 llvm::Value *result = Builder.CreatePointerCast(
1086 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1088 if (IsOpenCL) {
1089 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1090 result, blockInfo.StructureType);
1093 return result;
1097 llvm::Type *CodeGenModule::getBlockDescriptorType() {
1098 if (BlockDescriptorType)
1099 return BlockDescriptorType;
1101 llvm::Type *UnsignedLongTy =
1102 getTypes().ConvertType(getContext().UnsignedLongTy);
1104 // struct __block_descriptor {
1105 // unsigned long reserved;
1106 // unsigned long block_size;
1108 // // later, the following will be added
1110 // struct {
1111 // void (*copyHelper)();
1112 // void (*copyHelper)();
1113 // } helpers; // !!! optional
1115 // const char *signature; // the block signature
1116 // const char *layout; // reserved
1117 // };
1118 BlockDescriptorType = llvm::StructType::create(
1119 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1121 // Now form a pointer to that.
1122 unsigned AddrSpace = 0;
1123 if (getLangOpts().OpenCL)
1124 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1125 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1126 return BlockDescriptorType;
1129 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1130 if (GenericBlockLiteralType)
1131 return GenericBlockLiteralType;
1133 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1135 if (getLangOpts().OpenCL) {
1136 // struct __opencl_block_literal_generic {
1137 // int __size;
1138 // int __align;
1139 // __generic void *__invoke;
1140 // /* custom fields */
1141 // };
1142 SmallVector<llvm::Type *, 8> StructFields(
1143 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1144 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1145 llvm::append_range(StructFields, Helper->getCustomFieldTypes());
1147 GenericBlockLiteralType = llvm::StructType::create(
1148 StructFields, "struct.__opencl_block_literal_generic");
1149 } else {
1150 // struct __block_literal_generic {
1151 // void *__isa;
1152 // int __flags;
1153 // int __reserved;
1154 // void (*__invoke)(void *);
1155 // struct __block_descriptor *__descriptor;
1156 // };
1157 GenericBlockLiteralType =
1158 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1159 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1162 return GenericBlockLiteralType;
1165 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1166 ReturnValueSlot ReturnValue,
1167 llvm::CallBase **CallOrInvoke) {
1168 const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
1169 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1170 llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1171 llvm::Value *Func = nullptr;
1172 QualType FnType = BPT->getPointeeType();
1173 ASTContext &Ctx = getContext();
1174 CallArgList Args;
1176 if (getLangOpts().OpenCL) {
1177 // For OpenCL, BlockPtr is already casted to generic block literal.
1179 // First argument of a block call is a generic block literal casted to
1180 // generic void pointer, i.e. i8 addrspace(4)*
1181 llvm::Type *GenericVoidPtrTy =
1182 CGM.getOpenCLRuntime().getGenericVoidPointerType();
1183 llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1184 BlockPtr, GenericVoidPtrTy);
1185 QualType VoidPtrQualTy = Ctx.getPointerType(
1186 Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1187 Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1188 // And the rest of the arguments.
1189 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1191 // We *can* call the block directly unless it is a function argument.
1192 if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1193 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1194 else {
1195 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1196 Func = Builder.CreateAlignedLoad(GenericVoidPtrTy, FuncPtr,
1197 getPointerAlign());
1199 } else {
1200 // Bitcast the block literal to a generic block literal.
1201 BlockPtr =
1202 Builder.CreatePointerCast(BlockPtr, UnqualPtrTy, "block.literal");
1203 // Get pointer to the block invoke function
1204 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1206 // First argument is a block literal casted to a void pointer
1207 BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1208 Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1209 // And the rest of the arguments.
1210 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1212 // Load the function.
1213 Func = Builder.CreateAlignedLoad(VoidPtrTy, FuncPtr, getPointerAlign());
1216 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1217 const CGFunctionInfo &FnInfo =
1218 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1220 // Prepare the callee.
1221 CGCallee Callee(CGCalleeInfo(), Func);
1223 // And call the block.
1224 return EmitCall(FnInfo, Callee, ReturnValue, Args, CallOrInvoke);
1227 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1228 assert(BlockInfo && "evaluating block ref without block information?");
1229 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1231 // Handle constant captures.
1232 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1234 Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1235 "block.capture.addr");
1237 if (variable->isEscapingByref()) {
1238 // addr should be a void** right now. Load, then cast the result
1239 // to byref*.
1241 auto &byrefInfo = getBlockByrefInfo(variable);
1242 addr = Address(Builder.CreateLoad(addr), byrefInfo.Type,
1243 byrefInfo.ByrefAlignment);
1245 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1246 variable->getName());
1249 assert((!variable->isNonEscapingByref() ||
1250 capture.fieldType()->isReferenceType()) &&
1251 "the capture field of a non-escaping variable should have a "
1252 "reference type");
1253 if (capture.fieldType()->isReferenceType())
1254 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1256 return addr;
1259 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1260 llvm::Constant *Addr) {
1261 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1262 (void)Ok;
1263 assert(Ok && "Trying to replace an already-existing global block!");
1266 llvm::Constant *
1267 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1268 StringRef Name) {
1269 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1270 return Block;
1272 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1273 blockInfo.BlockExpression = BE;
1275 // Compute information about the layout, etc., of this block.
1276 computeBlockInfo(*this, nullptr, blockInfo);
1278 // Using that metadata, generate the actual block function.
1280 CodeGenFunction::DeclMapTy LocalDeclMap;
1281 CodeGenFunction(*this).GenerateBlockFunction(
1282 GlobalDecl(), blockInfo, LocalDeclMap,
1283 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1286 return getAddrOfGlobalBlockIfEmitted(BE);
1289 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1290 const CGBlockInfo &blockInfo,
1291 llvm::Constant *blockFn) {
1292 assert(blockInfo.CanBeGlobal);
1293 // Callers should detect this case on their own: calling this function
1294 // generally requires computing layout information, which is a waste of time
1295 // if we've already emitted this block.
1296 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1297 "Refusing to re-emit a global block.");
1299 // Generate the constants for the block literal initializer.
1300 ConstantInitBuilder builder(CGM);
1301 auto fields = builder.beginStruct();
1303 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1304 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1305 if (!IsOpenCL) {
1306 // isa
1307 if (IsWindows)
1308 fields.addNullPointer(CGM.Int8PtrPtrTy);
1309 else
1310 fields.add(CGM.getNSConcreteGlobalBlock());
1312 // __flags
1313 BlockFlags flags = BLOCK_IS_GLOBAL;
1314 if (!CGM.getCodeGenOpts().DisableBlockSignatureString)
1315 flags |= BLOCK_HAS_SIGNATURE;
1316 if (blockInfo.UsesStret)
1317 flags |= BLOCK_USE_STRET;
1319 fields.addInt(CGM.IntTy, flags.getBitMask());
1321 // Reserved
1322 fields.addInt(CGM.IntTy, 0);
1323 } else {
1324 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1325 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1328 // Function
1329 fields.add(blockFn);
1331 if (!IsOpenCL) {
1332 // Descriptor
1333 fields.add(buildBlockDescriptor(CGM, blockInfo));
1334 } else if (auto *Helper =
1335 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1336 for (auto *I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1337 fields.add(I);
1341 unsigned AddrSpace = 0;
1342 if (CGM.getContext().getLangOpts().OpenCL)
1343 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1345 llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
1346 "__block_literal_global", blockInfo.BlockAlign,
1347 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1349 literal->addAttribute("objc_arc_inert");
1351 // Windows does not allow globals to be initialised to point to globals in
1352 // different DLLs. Any such variables must run code to initialise them.
1353 if (IsWindows) {
1354 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1355 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1356 &CGM.getModule());
1357 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1358 Init));
1359 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1360 b.CreateStructGEP(literal->getValueType(), literal, 0),
1361 CGM.getPointerAlign().getAsAlign());
1362 b.CreateRetVoid();
1363 // We can't use the normal LLVM global initialisation array, because we
1364 // need to specify that this runs early in library initialisation.
1365 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1366 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1367 Init, ".block_isa_init_ptr");
1368 InitVar->setSection(".CRT$XCLa");
1369 CGM.addUsedGlobal(InitVar);
1372 // Return a constant of the appropriately-casted type.
1373 llvm::Type *RequiredType =
1374 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1375 llvm::Constant *Result =
1376 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1377 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1378 if (CGM.getContext().getLangOpts().OpenCL)
1379 CGM.getOpenCLRuntime().recordBlockInfo(
1380 blockInfo.BlockExpression,
1381 cast<llvm::Function>(blockFn->stripPointerCasts()), Result,
1382 literal->getValueType());
1383 return Result;
1386 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1387 unsigned argNum,
1388 llvm::Value *arg) {
1389 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1391 // Allocate a stack slot like for any local variable to guarantee optimal
1392 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1393 RawAddress alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1394 Builder.CreateStore(arg, alloc);
1395 if (CGDebugInfo *DI = getDebugInfo()) {
1396 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1397 DI->setLocation(D->getLocation());
1398 DI->EmitDeclareOfBlockLiteralArgVariable(
1399 *BlockInfo, D->getName(), argNum,
1400 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1404 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1405 ApplyDebugLocation Scope(*this, StartLoc);
1407 // Instead of messing around with LocalDeclMap, just set the value
1408 // directly as BlockPointer.
1409 BlockPointer = Builder.CreatePointerCast(
1410 arg,
1411 llvm::PointerType::get(
1412 getLLVMContext(),
1413 getContext().getLangOpts().OpenCL
1414 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1415 : 0),
1416 "block");
1419 Address CodeGenFunction::LoadBlockStruct() {
1420 assert(BlockInfo && "not in a block invocation function!");
1421 assert(BlockPointer && "no block pointer set!");
1422 return Address(BlockPointer, BlockInfo->StructureType, BlockInfo->BlockAlign);
1425 llvm::Function *CodeGenFunction::GenerateBlockFunction(
1426 GlobalDecl GD, const CGBlockInfo &blockInfo, const DeclMapTy &ldm,
1427 bool IsLambdaConversionToBlock, bool BuildGlobalBlock) {
1428 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1430 CurGD = GD;
1432 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1434 BlockInfo = &blockInfo;
1436 // Arrange for local static and local extern declarations to appear
1437 // to be local to this function as well, in case they're directly
1438 // referenced in a block.
1439 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1440 const auto *var = dyn_cast<VarDecl>(i->first);
1441 if (var && !var->hasLocalStorage())
1442 setAddrOfLocalVar(var, i->second);
1445 // Begin building the function declaration.
1447 // Build the argument list.
1448 FunctionArgList args;
1450 // The first argument is the block pointer. Just take it as a void*
1451 // and cast it later.
1452 QualType selfTy = getContext().VoidPtrTy;
1454 // For OpenCL passed block pointer can be private AS local variable or
1455 // global AS program scope variable (for the case with and without captures).
1456 // Generic AS is used therefore to be able to accommodate both private and
1457 // generic AS in one implementation.
1458 if (getLangOpts().OpenCL)
1459 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1460 getContext().VoidTy, LangAS::opencl_generic));
1462 const IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1464 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1465 SourceLocation(), II, selfTy,
1466 ImplicitParamKind::ObjCSelf);
1467 args.push_back(&SelfDecl);
1469 // Now add the rest of the parameters.
1470 args.append(blockDecl->param_begin(), blockDecl->param_end());
1472 // Create the function declaration.
1473 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1474 const CGFunctionInfo &fnInfo =
1475 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1476 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1477 blockInfo.UsesStret = true;
1479 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1481 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1482 llvm::Function *fn = llvm::Function::Create(
1483 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1484 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1486 if (BuildGlobalBlock) {
1487 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1488 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1489 : VoidPtrTy;
1490 buildGlobalBlock(CGM, blockInfo,
1491 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1494 // Begin generating the function.
1495 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1496 blockDecl->getLocation(),
1497 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1499 // Okay. Undo some of what StartFunction did.
1501 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1502 // won't delete the dbg.declare intrinsics for captured variables.
1503 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1504 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1505 // Allocate a stack slot for it, so we can point the debugger to it
1506 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1507 getPointerAlign(),
1508 "block.addr");
1509 // Set the DebugLocation to empty, so the store is recognized as a
1510 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1511 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1512 Builder.CreateStore(BlockPointer, Alloca);
1513 BlockPointerDbgLoc = Alloca.emitRawPointer(*this);
1516 // If we have a C++ 'this' reference, go ahead and force it into
1517 // existence now.
1518 if (blockDecl->capturesCXXThis()) {
1519 Address addr = Builder.CreateStructGEP(
1520 LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
1521 CXXThisValue = Builder.CreateLoad(addr, "this");
1524 // Also force all the constant captures.
1525 for (const auto &CI : blockDecl->captures()) {
1526 const VarDecl *variable = CI.getVariable();
1527 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1528 if (!capture.isConstant()) continue;
1530 CharUnits align = getContext().getDeclAlign(variable);
1531 Address alloca =
1532 CreateMemTemp(variable->getType(), align, "block.captured-const");
1534 Builder.CreateStore(capture.getConstant(), alloca);
1536 setAddrOfLocalVar(variable, alloca);
1539 // Save a spot to insert the debug information for all the DeclRefExprs.
1540 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1541 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1542 --entry_ptr;
1544 if (IsLambdaConversionToBlock)
1545 EmitLambdaBlockInvokeBody();
1546 else {
1547 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1548 incrementProfileCounter(blockDecl->getBody());
1549 EmitStmt(blockDecl->getBody());
1552 // Remember where we were...
1553 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1555 // Go back to the entry.
1556 if (entry_ptr->getNextNonDebugInstruction())
1557 entry_ptr = entry_ptr->getNextNonDebugInstruction()->getIterator();
1558 else
1559 entry_ptr = entry->end();
1560 Builder.SetInsertPoint(entry, entry_ptr);
1562 // Emit debug information for all the DeclRefExprs.
1563 // FIXME: also for 'this'
1564 if (CGDebugInfo *DI = getDebugInfo()) {
1565 for (const auto &CI : blockDecl->captures()) {
1566 const VarDecl *variable = CI.getVariable();
1567 DI->EmitLocation(Builder, variable->getLocation());
1569 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1570 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1571 if (capture.isConstant()) {
1572 auto addr = LocalDeclMap.find(variable)->second;
1573 (void)DI->EmitDeclareOfAutoVariable(
1574 variable, addr.emitRawPointer(*this), Builder);
1575 continue;
1578 DI->EmitDeclareOfBlockDeclRefVariable(
1579 variable, BlockPointerDbgLoc, Builder, blockInfo,
1580 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1583 // Recover location if it was changed in the above loop.
1584 DI->EmitLocation(Builder,
1585 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1588 // And resume where we left off.
1589 if (resume == nullptr)
1590 Builder.ClearInsertionPoint();
1591 else
1592 Builder.SetInsertPoint(resume);
1594 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1596 return fn;
1599 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1600 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1601 const LangOptions &LangOpts) {
1602 if (CI.getCopyExpr()) {
1603 assert(!CI.isByRef());
1604 // don't bother computing flags
1605 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1607 BlockFieldFlags Flags;
1608 if (CI.isEscapingByref()) {
1609 Flags = BLOCK_FIELD_IS_BYREF;
1610 if (T.isObjCGCWeak())
1611 Flags |= BLOCK_FIELD_IS_WEAK;
1612 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1615 Flags = BLOCK_FIELD_IS_OBJECT;
1616 bool isBlockPointer = T->isBlockPointerType();
1617 if (isBlockPointer)
1618 Flags = BLOCK_FIELD_IS_BLOCK;
1620 switch (T.isNonTrivialToPrimitiveCopy()) {
1621 case QualType::PCK_Struct:
1622 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1623 BlockFieldFlags());
1624 case QualType::PCK_ARCWeak:
1625 // We need to register __weak direct captures with the runtime.
1626 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1627 case QualType::PCK_ARCStrong:
1628 // We need to retain the copied value for __strong direct captures.
1629 // If it's a block pointer, we have to copy the block and assign that to
1630 // the destination pointer, so we might as well use _Block_object_assign.
1631 // Otherwise we can avoid that.
1632 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1633 : BlockCaptureEntityKind::BlockObject,
1634 Flags);
1635 case QualType::PCK_Trivial:
1636 case QualType::PCK_VolatileTrivial: {
1637 if (!T->isObjCRetainableType())
1638 // For all other types, the memcpy is fine.
1639 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1641 // Honor the inert __unsafe_unretained qualifier, which doesn't actually
1642 // make it into the type system.
1643 if (T->isObjCInertUnsafeUnretainedType())
1644 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1646 // Special rules for ARC captures:
1647 Qualifiers QS = T.getQualifiers();
1649 // Non-ARC captures of retainable pointers are strong and
1650 // therefore require a call to _Block_object_assign.
1651 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1652 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1654 // Otherwise the memcpy is fine.
1655 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1658 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1661 namespace {
1662 /// Release a __block variable.
1663 struct CallBlockRelease final : EHScopeStack::Cleanup {
1664 Address Addr;
1665 BlockFieldFlags FieldFlags;
1666 bool LoadBlockVarAddr, CanThrow;
1668 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1669 bool CT)
1670 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1671 CanThrow(CT) {}
1673 void Emit(CodeGenFunction &CGF, Flags flags) override {
1674 llvm::Value *BlockVarAddr;
1675 if (LoadBlockVarAddr) {
1676 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1677 } else {
1678 BlockVarAddr = Addr.emitRawPointer(CGF);
1681 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1684 } // end anonymous namespace
1686 /// Check if \p T is a C++ class that has a destructor that can throw.
1687 bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1688 if (const auto *RD = T->getAsCXXRecordDecl())
1689 if (const CXXDestructorDecl *DD = RD->getDestructor())
1690 return DD->getType()->castAs<FunctionProtoType>()->canThrow();
1691 return false;
1694 // Return a string that has the information about a capture.
1695 static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
1696 CaptureStrKind StrKind,
1697 CharUnits BlockAlignment,
1698 CodeGenModule &CGM) {
1699 std::string Str;
1700 ASTContext &Ctx = CGM.getContext();
1701 const BlockDecl::Capture &CI = *Cap.Cap;
1702 QualType CaptureTy = CI.getVariable()->getType();
1704 BlockCaptureEntityKind Kind;
1705 BlockFieldFlags Flags;
1707 // CaptureStrKind::Merged should be passed only when the operations and the
1708 // flags are the same for copy and dispose.
1709 assert((StrKind != CaptureStrKind::Merged ||
1710 (Cap.CopyKind == Cap.DisposeKind &&
1711 Cap.CopyFlags == Cap.DisposeFlags)) &&
1712 "different operations and flags");
1714 if (StrKind == CaptureStrKind::DisposeHelper) {
1715 Kind = Cap.DisposeKind;
1716 Flags = Cap.DisposeFlags;
1717 } else {
1718 Kind = Cap.CopyKind;
1719 Flags = Cap.CopyFlags;
1722 switch (Kind) {
1723 case BlockCaptureEntityKind::CXXRecord: {
1724 Str += "c";
1725 SmallString<256> TyStr;
1726 llvm::raw_svector_ostream Out(TyStr);
1727 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(CaptureTy, Out);
1728 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1729 break;
1731 case BlockCaptureEntityKind::ARCWeak:
1732 Str += "w";
1733 break;
1734 case BlockCaptureEntityKind::ARCStrong:
1735 Str += "s";
1736 break;
1737 case BlockCaptureEntityKind::BlockObject: {
1738 const VarDecl *Var = CI.getVariable();
1739 unsigned F = Flags.getBitMask();
1740 if (F & BLOCK_FIELD_IS_BYREF) {
1741 Str += "r";
1742 if (F & BLOCK_FIELD_IS_WEAK)
1743 Str += "w";
1744 else {
1745 // If CaptureStrKind::Merged is passed, check both the copy expression
1746 // and the destructor.
1747 if (StrKind != CaptureStrKind::DisposeHelper) {
1748 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1749 Str += "c";
1751 if (StrKind != CaptureStrKind::CopyHelper) {
1752 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1753 Str += "d";
1756 } else {
1757 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1758 if (F == BLOCK_FIELD_IS_BLOCK)
1759 Str += "b";
1760 else
1761 Str += "o";
1763 break;
1765 case BlockCaptureEntityKind::NonTrivialCStruct: {
1766 bool IsVolatile = CaptureTy.isVolatileQualified();
1767 CharUnits Alignment = BlockAlignment.alignmentAtOffset(Cap.getOffset());
1769 Str += "n";
1770 std::string FuncStr;
1771 if (StrKind == CaptureStrKind::DisposeHelper)
1772 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1773 CaptureTy, Alignment, IsVolatile, Ctx);
1774 else
1775 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1776 // It has all the information that the destructor string has.
1777 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1778 CaptureTy, Alignment, IsVolatile, Ctx);
1779 // The underscore is necessary here because non-trivial copy constructor
1780 // and destructor strings can start with a number.
1781 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1782 break;
1784 case BlockCaptureEntityKind::None:
1785 break;
1788 return Str;
1791 static std::string getCopyDestroyHelperFuncName(
1792 const SmallVectorImpl<CGBlockInfo::Capture> &Captures,
1793 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1794 assert((StrKind == CaptureStrKind::CopyHelper ||
1795 StrKind == CaptureStrKind::DisposeHelper) &&
1796 "unexpected CaptureStrKind");
1797 std::string Name = StrKind == CaptureStrKind::CopyHelper
1798 ? "__copy_helper_block_"
1799 : "__destroy_helper_block_";
1800 if (CGM.getLangOpts().Exceptions)
1801 Name += "e";
1802 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1803 Name += "a";
1804 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1806 for (auto &Cap : Captures) {
1807 if (Cap.isConstantOrTrivial())
1808 continue;
1809 Name += llvm::to_string(Cap.getOffset().getQuantity());
1810 Name += getBlockCaptureStr(Cap, StrKind, BlockAlignment, CGM);
1813 return Name;
1816 static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1817 Address Field, QualType CaptureType,
1818 BlockFieldFlags Flags, bool ForCopyHelper,
1819 VarDecl *Var, CodeGenFunction &CGF) {
1820 bool EHOnly = ForCopyHelper;
1822 switch (CaptureKind) {
1823 case BlockCaptureEntityKind::CXXRecord:
1824 case BlockCaptureEntityKind::ARCWeak:
1825 case BlockCaptureEntityKind::NonTrivialCStruct:
1826 case BlockCaptureEntityKind::ARCStrong: {
1827 if (CaptureType.isDestructedType() &&
1828 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1829 CodeGenFunction::Destroyer *Destroyer =
1830 CaptureKind == BlockCaptureEntityKind::ARCStrong
1831 ? CodeGenFunction::destroyARCStrongImprecise
1832 : CGF.getDestroyer(CaptureType.isDestructedType());
1833 CleanupKind Kind =
1834 EHOnly ? EHCleanup
1835 : CGF.getCleanupKind(CaptureType.isDestructedType());
1836 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1838 break;
1840 case BlockCaptureEntityKind::BlockObject: {
1841 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1842 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1843 // Calls to _Block_object_dispose along the EH path in the copy helper
1844 // function don't throw as newly-copied __block variables always have a
1845 // reference count of 2.
1846 bool CanThrow =
1847 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1848 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1849 CanThrow);
1851 break;
1853 case BlockCaptureEntityKind::None:
1854 break;
1858 static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1859 llvm::Function *Fn,
1860 const CGFunctionInfo &FI,
1861 CodeGenModule &CGM) {
1862 if (CapturesNonExternalType) {
1863 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1864 } else {
1865 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1866 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1867 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
1868 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1871 /// Generate the copy-helper function for a block closure object:
1872 /// static void block_copy_helper(block_t *dst, block_t *src);
1873 /// The runtime will have previously initialized 'dst' by doing a
1874 /// bit-copy of 'src'.
1876 /// Note that this copies an entire block closure object to the heap;
1877 /// it should not be confused with a 'byref copy helper', which moves
1878 /// the contents of an individual __block variable to the heap.
1879 llvm::Constant *
1880 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1881 std::string FuncName = getCopyDestroyHelperFuncName(
1882 blockInfo.SortedCaptures, blockInfo.BlockAlign,
1883 CaptureStrKind::CopyHelper, CGM);
1885 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
1886 return Func;
1888 ASTContext &C = getContext();
1890 QualType ReturnTy = C.VoidTy;
1892 FunctionArgList args;
1893 ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
1894 args.push_back(&DstDecl);
1895 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
1896 args.push_back(&SrcDecl);
1898 const CGFunctionInfo &FI =
1899 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
1901 // FIXME: it would be nice if these were mergeable with things with
1902 // identical semantics.
1903 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1905 llvm::Function *Fn =
1906 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1907 FuncName, &CGM.getModule());
1908 if (CGM.supportsCOMDAT())
1909 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
1911 SmallVector<QualType, 2> ArgTys;
1912 ArgTys.push_back(C.VoidPtrTy);
1913 ArgTys.push_back(C.VoidPtrTy);
1915 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1916 CGM);
1917 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
1918 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1920 Address src = GetAddrOfLocalVar(&SrcDecl);
1921 src = Address(Builder.CreateLoad(src), blockInfo.StructureType,
1922 blockInfo.BlockAlign);
1924 Address dst = GetAddrOfLocalVar(&DstDecl);
1925 dst = Address(Builder.CreateLoad(dst), blockInfo.StructureType,
1926 blockInfo.BlockAlign);
1928 for (auto &capture : blockInfo.SortedCaptures) {
1929 if (capture.isConstantOrTrivial())
1930 continue;
1932 const BlockDecl::Capture &CI = *capture.Cap;
1933 QualType captureType = CI.getVariable()->getType();
1934 BlockFieldFlags flags = capture.CopyFlags;
1936 unsigned index = capture.getIndex();
1937 Address srcField = Builder.CreateStructGEP(src, index);
1938 Address dstField = Builder.CreateStructGEP(dst, index);
1940 switch (capture.CopyKind) {
1941 case BlockCaptureEntityKind::CXXRecord:
1942 // If there's an explicit copy expression, we do that.
1943 assert(CI.getCopyExpr() && "copy expression for variable is missing");
1944 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1945 break;
1946 case BlockCaptureEntityKind::ARCWeak:
1947 EmitARCCopyWeak(dstField, srcField);
1948 break;
1949 case BlockCaptureEntityKind::NonTrivialCStruct: {
1950 // If this is a C struct that requires non-trivial copy construction,
1951 // emit a call to its copy constructor.
1952 QualType varType = CI.getVariable()->getType();
1953 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
1954 MakeAddrLValue(srcField, varType));
1955 break;
1957 case BlockCaptureEntityKind::ARCStrong: {
1958 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1959 // At -O0, store null into the destination field (so that the
1960 // storeStrong doesn't over-release) and then call storeStrong.
1961 // This is a workaround to not having an initStrong call.
1962 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1963 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1964 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1965 Builder.CreateStore(null, dstField);
1966 EmitARCStoreStrongCall(dstField, srcValue, true);
1968 // With optimization enabled, take advantage of the fact that
1969 // the blocks runtime guarantees a memcpy of the block data, and
1970 // just emit a retain of the src field.
1971 } else {
1972 EmitARCRetainNonBlock(srcValue);
1974 // Unless EH cleanup is required, we don't need this anymore, so kill
1975 // it. It's not quite worth the annoyance to avoid creating it in the
1976 // first place.
1977 if (!needsEHCleanup(captureType.isDestructedType()))
1978 if (auto *I =
1979 cast_or_null<llvm::Instruction>(dstField.getBasePointer()))
1980 I->eraseFromParent();
1982 break;
1984 case BlockCaptureEntityKind::BlockObject: {
1985 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1986 llvm::Value *dstAddr = dstField.emitRawPointer(*this);
1987 llvm::Value *args[] = {
1988 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1991 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
1992 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1993 else
1994 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1995 break;
1997 case BlockCaptureEntityKind::None:
1998 continue;
2001 // Ensure that we destroy the copied object if an exception is thrown later
2002 // in the helper function.
2003 pushCaptureCleanup(capture.CopyKind, dstField, captureType, flags,
2004 /*ForCopyHelper*/ true, CI.getVariable(), *this);
2007 FinishFunction();
2009 return Fn;
2012 static BlockFieldFlags
2013 getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2014 QualType T) {
2015 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2016 if (T->isBlockPointerType())
2017 Flags = BLOCK_FIELD_IS_BLOCK;
2018 return Flags;
2021 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2022 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2023 const LangOptions &LangOpts) {
2024 if (CI.isEscapingByref()) {
2025 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2026 if (T.isObjCGCWeak())
2027 Flags |= BLOCK_FIELD_IS_WEAK;
2028 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2031 switch (T.isDestructedType()) {
2032 case QualType::DK_cxx_destructor:
2033 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2034 case QualType::DK_objc_strong_lifetime:
2035 // Use objc_storeStrong for __strong direct captures; the
2036 // dynamic tools really like it when we do this.
2037 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2038 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2039 case QualType::DK_objc_weak_lifetime:
2040 // Support __weak direct captures.
2041 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2042 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2043 case QualType::DK_nontrivial_c_struct:
2044 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2045 BlockFieldFlags());
2046 case QualType::DK_none: {
2047 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2048 // But honor the inert __unsafe_unretained qualifier, which doesn't actually
2049 // make it into the type system.
2050 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2051 !LangOpts.ObjCAutoRefCount && !T->isObjCInertUnsafeUnretainedType())
2052 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2053 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2054 // Otherwise, we have nothing to do.
2055 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2058 llvm_unreachable("after exhaustive DestructionKind switch");
2061 /// Generate the destroy-helper function for a block closure object:
2062 /// static void block_destroy_helper(block_t *theBlock);
2064 /// Note that this destroys a heap-allocated block closure object;
2065 /// it should not be confused with a 'byref destroy helper', which
2066 /// destroys the heap-allocated contents of an individual __block
2067 /// variable.
2068 llvm::Constant *
2069 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2070 std::string FuncName = getCopyDestroyHelperFuncName(
2071 blockInfo.SortedCaptures, blockInfo.BlockAlign,
2072 CaptureStrKind::DisposeHelper, CGM);
2074 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2075 return Func;
2077 ASTContext &C = getContext();
2079 QualType ReturnTy = C.VoidTy;
2081 FunctionArgList args;
2082 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
2083 args.push_back(&SrcDecl);
2085 const CGFunctionInfo &FI =
2086 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2088 // FIXME: We'd like to put these into a mergable by content, with
2089 // internal linkage.
2090 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2092 llvm::Function *Fn =
2093 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2094 FuncName, &CGM.getModule());
2095 if (CGM.supportsCOMDAT())
2096 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2098 SmallVector<QualType, 1> ArgTys;
2099 ArgTys.push_back(C.VoidPtrTy);
2101 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2102 CGM);
2103 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
2104 markAsIgnoreThreadCheckingAtRuntime(Fn);
2106 auto AL = ApplyDebugLocation::CreateArtificial(*this);
2108 Address src = GetAddrOfLocalVar(&SrcDecl);
2109 src = Address(Builder.CreateLoad(src), blockInfo.StructureType,
2110 blockInfo.BlockAlign);
2112 CodeGenFunction::RunCleanupsScope cleanups(*this);
2114 for (auto &capture : blockInfo.SortedCaptures) {
2115 if (capture.isConstantOrTrivial())
2116 continue;
2118 const BlockDecl::Capture &CI = *capture.Cap;
2119 BlockFieldFlags flags = capture.DisposeFlags;
2121 Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
2123 pushCaptureCleanup(capture.DisposeKind, srcField,
2124 CI.getVariable()->getType(), flags,
2125 /*ForCopyHelper*/ false, CI.getVariable(), *this);
2128 cleanups.ForceCleanup();
2130 FinishFunction();
2132 return Fn;
2135 namespace {
2137 /// Emits the copy/dispose helper functions for a __block object of id type.
2138 class ObjectByrefHelpers final : public BlockByrefHelpers {
2139 BlockFieldFlags Flags;
2141 public:
2142 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2143 : BlockByrefHelpers(alignment), Flags(flags) {}
2145 void emitCopy(CodeGenFunction &CGF, Address destField,
2146 Address srcField) override {
2147 destField = destField.withElementType(CGF.Int8Ty);
2149 srcField = srcField.withElementType(CGF.Int8PtrTy);
2150 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2152 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2154 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2155 llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
2157 llvm::Value *args[] = {destField.emitRawPointer(CGF), srcValue, flagsVal};
2158 CGF.EmitNounwindRuntimeCall(fn, args);
2161 void emitDispose(CodeGenFunction &CGF, Address field) override {
2162 field = field.withElementType(CGF.Int8PtrTy);
2163 llvm::Value *value = CGF.Builder.CreateLoad(field);
2165 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2168 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2169 id.AddInteger(Flags.getBitMask());
2173 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2174 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2175 public:
2176 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2178 void emitCopy(CodeGenFunction &CGF, Address destField,
2179 Address srcField) override {
2180 CGF.EmitARCMoveWeak(destField, srcField);
2183 void emitDispose(CodeGenFunction &CGF, Address field) override {
2184 CGF.EmitARCDestroyWeak(field);
2187 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2188 // 0 is distinguishable from all pointers and byref flags
2189 id.AddInteger(0);
2193 /// Emits the copy/dispose helpers for an ARC __block __strong variable
2194 /// that's not of block-pointer type.
2195 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2196 public:
2197 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2199 void emitCopy(CodeGenFunction &CGF, Address destField,
2200 Address srcField) override {
2201 // Do a "move" by copying the value and then zeroing out the old
2202 // variable.
2204 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2206 llvm::Value *null =
2207 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2209 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2210 CGF.Builder.CreateStore(null, destField);
2211 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2212 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2213 return;
2215 CGF.Builder.CreateStore(value, destField);
2216 CGF.Builder.CreateStore(null, srcField);
2219 void emitDispose(CodeGenFunction &CGF, Address field) override {
2220 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2223 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2224 // 1 is distinguishable from all pointers and byref flags
2225 id.AddInteger(1);
2229 /// Emits the copy/dispose helpers for an ARC __block __strong
2230 /// variable that's of block-pointer type.
2231 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2232 public:
2233 ARCStrongBlockByrefHelpers(CharUnits alignment)
2234 : BlockByrefHelpers(alignment) {}
2236 void emitCopy(CodeGenFunction &CGF, Address destField,
2237 Address srcField) override {
2238 // Do the copy with objc_retainBlock; that's all that
2239 // _Block_object_assign would do anyway, and we'd have to pass the
2240 // right arguments to make sure it doesn't get no-op'ed.
2241 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2242 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2243 CGF.Builder.CreateStore(copy, destField);
2246 void emitDispose(CodeGenFunction &CGF, Address field) override {
2247 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2250 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2251 // 2 is distinguishable from all pointers and byref flags
2252 id.AddInteger(2);
2256 /// Emits the copy/dispose helpers for a __block variable with a
2257 /// nontrivial copy constructor or destructor.
2258 class CXXByrefHelpers final : public BlockByrefHelpers {
2259 QualType VarType;
2260 const Expr *CopyExpr;
2262 public:
2263 CXXByrefHelpers(CharUnits alignment, QualType type,
2264 const Expr *copyExpr)
2265 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2267 bool needsCopy() const override { return CopyExpr != nullptr; }
2268 void emitCopy(CodeGenFunction &CGF, Address destField,
2269 Address srcField) override {
2270 if (!CopyExpr) return;
2271 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2274 void emitDispose(CodeGenFunction &CGF, Address field) override {
2275 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2276 CGF.PushDestructorCleanup(VarType, field);
2277 CGF.PopCleanupBlocks(cleanupDepth);
2280 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2281 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2285 /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2286 /// C struct.
2287 class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2288 QualType VarType;
2290 public:
2291 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2292 : BlockByrefHelpers(alignment), VarType(type) {}
2294 void emitCopy(CodeGenFunction &CGF, Address destField,
2295 Address srcField) override {
2296 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2297 CGF.MakeAddrLValue(srcField, VarType));
2300 bool needsDispose() const override {
2301 return VarType.isDestructedType();
2304 void emitDispose(CodeGenFunction &CGF, Address field) override {
2305 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2306 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2307 CGF.PopCleanupBlocks(cleanupDepth);
2310 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2311 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2314 } // end anonymous namespace
2316 static llvm::Constant *
2317 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2318 BlockByrefHelpers &generator) {
2319 ASTContext &Context = CGF.getContext();
2321 QualType ReturnTy = Context.VoidTy;
2323 FunctionArgList args;
2324 ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamKind::Other);
2325 args.push_back(&Dst);
2327 ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamKind::Other);
2328 args.push_back(&Src);
2330 const CGFunctionInfo &FI =
2331 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2333 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2335 // FIXME: We'd like to put these into a mergable by content, with
2336 // internal linkage.
2337 llvm::Function *Fn =
2338 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2339 "__Block_byref_object_copy_", &CGF.CGM.getModule());
2341 SmallVector<QualType, 2> ArgTys;
2342 ArgTys.push_back(Context.VoidPtrTy);
2343 ArgTys.push_back(Context.VoidPtrTy);
2345 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2347 CGF.StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
2348 // Create a scope with an artificial location for the body of this function.
2349 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
2351 if (generator.needsCopy()) {
2352 // dst->x
2353 Address destField = CGF.GetAddrOfLocalVar(&Dst);
2354 destField = Address(CGF.Builder.CreateLoad(destField), byrefInfo.Type,
2355 byrefInfo.ByrefAlignment);
2356 destField =
2357 CGF.emitBlockByrefAddress(destField, byrefInfo, false, "dest-object");
2359 // src->x
2360 Address srcField = CGF.GetAddrOfLocalVar(&Src);
2361 srcField = Address(CGF.Builder.CreateLoad(srcField), byrefInfo.Type,
2362 byrefInfo.ByrefAlignment);
2363 srcField =
2364 CGF.emitBlockByrefAddress(srcField, byrefInfo, false, "src-object");
2366 generator.emitCopy(CGF, destField, srcField);
2369 CGF.FinishFunction();
2371 return Fn;
2374 /// Build the copy helper for a __block variable.
2375 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2376 const BlockByrefInfo &byrefInfo,
2377 BlockByrefHelpers &generator) {
2378 CodeGenFunction CGF(CGM);
2379 return generateByrefCopyHelper(CGF, byrefInfo, generator);
2382 /// Generate code for a __block variable's dispose helper.
2383 static llvm::Constant *
2384 generateByrefDisposeHelper(CodeGenFunction &CGF,
2385 const BlockByrefInfo &byrefInfo,
2386 BlockByrefHelpers &generator) {
2387 ASTContext &Context = CGF.getContext();
2388 QualType R = Context.VoidTy;
2390 FunctionArgList args;
2391 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2392 ImplicitParamKind::Other);
2393 args.push_back(&Src);
2395 const CGFunctionInfo &FI =
2396 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2398 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2400 // FIXME: We'd like to put these into a mergable by content, with
2401 // internal linkage.
2402 llvm::Function *Fn =
2403 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2404 "__Block_byref_object_dispose_",
2405 &CGF.CGM.getModule());
2407 SmallVector<QualType, 1> ArgTys;
2408 ArgTys.push_back(Context.VoidPtrTy);
2410 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2412 CGF.StartFunction(GlobalDecl(), R, Fn, FI, args);
2413 // Create a scope with an artificial location for the body of this function.
2414 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
2416 if (generator.needsDispose()) {
2417 Address addr = CGF.GetAddrOfLocalVar(&Src);
2418 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.Type,
2419 byrefInfo.ByrefAlignment);
2420 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2422 generator.emitDispose(CGF, addr);
2425 CGF.FinishFunction();
2427 return Fn;
2430 /// Build the dispose helper for a __block variable.
2431 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2432 const BlockByrefInfo &byrefInfo,
2433 BlockByrefHelpers &generator) {
2434 CodeGenFunction CGF(CGM);
2435 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2438 /// Lazily build the copy and dispose helpers for a __block variable
2439 /// with the given information.
2440 template <class T>
2441 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2442 T &&generator) {
2443 llvm::FoldingSetNodeID id;
2444 generator.Profile(id);
2446 void *insertPos;
2447 BlockByrefHelpers *node
2448 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2449 if (node) return static_cast<T*>(node);
2451 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2452 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2454 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2455 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2456 return copy;
2459 /// Build the copy and dispose helpers for the given __block variable
2460 /// emission. Places the helpers in the global cache. Returns null
2461 /// if no helpers are required.
2462 BlockByrefHelpers *
2463 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2464 const AutoVarEmission &emission) {
2465 const VarDecl &var = *emission.Variable;
2466 assert(var.isEscapingByref() &&
2467 "only escaping __block variables need byref helpers");
2469 QualType type = var.getType();
2471 auto &byrefInfo = getBlockByrefInfo(&var);
2473 // The alignment we care about for the purposes of uniquing byref
2474 // helpers is the alignment of the actual byref value field.
2475 CharUnits valueAlignment =
2476 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2478 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2479 const Expr *copyExpr =
2480 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2481 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2483 return ::buildByrefHelpers(
2484 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2487 // If type is a non-trivial C struct type that is non-trivial to
2488 // destructly move or destroy, build the copy and dispose helpers.
2489 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2490 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2491 return ::buildByrefHelpers(
2492 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2494 // Otherwise, if we don't have a retainable type, there's nothing to do.
2495 // that the runtime does extra copies.
2496 if (!type->isObjCRetainableType()) return nullptr;
2498 Qualifiers qs = type.getQualifiers();
2500 // If we have lifetime, that dominates.
2501 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2502 switch (lifetime) {
2503 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2505 // These are just bits as far as the runtime is concerned.
2506 case Qualifiers::OCL_ExplicitNone:
2507 case Qualifiers::OCL_Autoreleasing:
2508 return nullptr;
2510 // Tell the runtime that this is ARC __weak, called by the
2511 // byref routines.
2512 case Qualifiers::OCL_Weak:
2513 return ::buildByrefHelpers(CGM, byrefInfo,
2514 ARCWeakByrefHelpers(valueAlignment));
2516 // ARC __strong __block variables need to be retained.
2517 case Qualifiers::OCL_Strong:
2518 // Block pointers need to be copied, and there's no direct
2519 // transfer possible.
2520 if (type->isBlockPointerType()) {
2521 return ::buildByrefHelpers(CGM, byrefInfo,
2522 ARCStrongBlockByrefHelpers(valueAlignment));
2524 // Otherwise, we transfer ownership of the retain from the stack
2525 // to the heap.
2526 } else {
2527 return ::buildByrefHelpers(CGM, byrefInfo,
2528 ARCStrongByrefHelpers(valueAlignment));
2531 llvm_unreachable("fell out of lifetime switch!");
2534 BlockFieldFlags flags;
2535 if (type->isBlockPointerType()) {
2536 flags |= BLOCK_FIELD_IS_BLOCK;
2537 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2538 type->isObjCObjectPointerType()) {
2539 flags |= BLOCK_FIELD_IS_OBJECT;
2540 } else {
2541 return nullptr;
2544 if (type.isObjCGCWeak())
2545 flags |= BLOCK_FIELD_IS_WEAK;
2547 return ::buildByrefHelpers(CGM, byrefInfo,
2548 ObjectByrefHelpers(valueAlignment, flags));
2551 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2552 const VarDecl *var,
2553 bool followForward) {
2554 auto &info = getBlockByrefInfo(var);
2555 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2558 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2559 const BlockByrefInfo &info,
2560 bool followForward,
2561 const llvm::Twine &name) {
2562 // Chase the forwarding address if requested.
2563 if (followForward) {
2564 Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
2565 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.Type,
2566 info.ByrefAlignment);
2569 return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
2572 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2573 /// into:
2575 /// struct {
2576 /// void *__isa;
2577 /// void *__forwarding;
2578 /// int32_t __flags;
2579 /// int32_t __size;
2580 /// void *__copy_helper; // only if needed
2581 /// void *__destroy_helper; // only if needed
2582 /// void *__byref_variable_layout;// only if needed
2583 /// char padding[X]; // only if needed
2584 /// T x;
2585 /// } x
2587 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2588 auto it = BlockByrefInfos.find(D);
2589 if (it != BlockByrefInfos.end())
2590 return it->second;
2592 llvm::StructType *byrefType =
2593 llvm::StructType::create(getLLVMContext(),
2594 "struct.__block_byref_" + D->getNameAsString());
2596 QualType Ty = D->getType();
2598 CharUnits size;
2599 SmallVector<llvm::Type *, 8> types;
2601 // void *__isa;
2602 types.push_back(VoidPtrTy);
2603 size += getPointerSize();
2605 // void *__forwarding;
2606 types.push_back(VoidPtrTy);
2607 size += getPointerSize();
2609 // int32_t __flags;
2610 types.push_back(Int32Ty);
2611 size += CharUnits::fromQuantity(4);
2613 // int32_t __size;
2614 types.push_back(Int32Ty);
2615 size += CharUnits::fromQuantity(4);
2617 // Note that this must match *exactly* the logic in buildByrefHelpers.
2618 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2619 if (hasCopyAndDispose) {
2620 /// void *__copy_helper;
2621 types.push_back(VoidPtrTy);
2622 size += getPointerSize();
2624 /// void *__destroy_helper;
2625 types.push_back(VoidPtrTy);
2626 size += getPointerSize();
2629 bool HasByrefExtendedLayout = false;
2630 Qualifiers::ObjCLifetime Lifetime = Qualifiers::OCL_None;
2631 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2632 HasByrefExtendedLayout) {
2633 /// void *__byref_variable_layout;
2634 types.push_back(VoidPtrTy);
2635 size += CharUnits::fromQuantity(PointerSizeInBytes);
2638 // T x;
2639 llvm::Type *varTy = ConvertTypeForMem(Ty);
2641 bool packed = false;
2642 CharUnits varAlign = getContext().getDeclAlign(D);
2643 CharUnits varOffset = size.alignTo(varAlign);
2645 // We may have to insert padding.
2646 if (varOffset != size) {
2647 llvm::Type *paddingTy =
2648 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2650 types.push_back(paddingTy);
2651 size = varOffset;
2653 // Conversely, we might have to prevent LLVM from inserting padding.
2654 } else if (CGM.getDataLayout().getABITypeAlign(varTy) >
2655 uint64_t(varAlign.getQuantity())) {
2656 packed = true;
2658 types.push_back(varTy);
2660 byrefType->setBody(types, packed);
2662 BlockByrefInfo info;
2663 info.Type = byrefType;
2664 info.FieldIndex = types.size() - 1;
2665 info.FieldOffset = varOffset;
2666 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2668 auto pair = BlockByrefInfos.insert({D, info});
2669 assert(pair.second && "info was inserted recursively?");
2670 return pair.first->second;
2673 /// Initialize the structural components of a __block variable, i.e.
2674 /// everything but the actual object.
2675 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2676 // Find the address of the local.
2677 Address addr = emission.Addr;
2679 // That's an alloca of the byref structure type.
2680 llvm::StructType *byrefType = cast<llvm::StructType>(addr.getElementType());
2682 unsigned nextHeaderIndex = 0;
2683 CharUnits nextHeaderOffset;
2684 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2685 const Twine &name) {
2686 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
2687 Builder.CreateStore(value, fieldAddr);
2689 nextHeaderIndex++;
2690 nextHeaderOffset += fieldSize;
2693 // Build the byref helpers if necessary. This is null if we don't need any.
2694 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2696 const VarDecl &D = *emission.Variable;
2697 QualType type = D.getType();
2699 bool HasByrefExtendedLayout = false;
2700 Qualifiers::ObjCLifetime ByrefLifetime = Qualifiers::OCL_None;
2701 bool ByRefHasLifetime =
2702 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2704 llvm::Value *V;
2706 // Initialize the 'isa', which is just 0 or 1.
2707 int isa = 0;
2708 if (type.isObjCGCWeak())
2709 isa = 1;
2710 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2711 storeHeaderField(V, getPointerSize(), "byref.isa");
2713 // Store the address of the variable into its own forwarding pointer.
2714 storeHeaderField(addr.emitRawPointer(*this), getPointerSize(),
2715 "byref.forwarding");
2717 // Blocks ABI:
2718 // c) the flags field is set to either 0 if no helper functions are
2719 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2720 BlockFlags flags;
2721 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2722 if (ByRefHasLifetime) {
2723 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2724 else switch (ByrefLifetime) {
2725 case Qualifiers::OCL_Strong:
2726 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2727 break;
2728 case Qualifiers::OCL_Weak:
2729 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2730 break;
2731 case Qualifiers::OCL_ExplicitNone:
2732 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2733 break;
2734 case Qualifiers::OCL_None:
2735 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2736 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2737 break;
2738 default:
2739 break;
2741 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2742 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2743 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2744 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2745 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2746 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2747 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2748 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2749 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2750 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2751 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2752 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2753 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2754 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2755 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2756 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2758 printf("\n");
2761 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2762 getIntSize(), "byref.flags");
2764 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2765 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2766 storeHeaderField(V, getIntSize(), "byref.size");
2768 if (helpers) {
2769 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2770 "byref.copyHelper");
2771 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2772 "byref.disposeHelper");
2775 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2776 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2777 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2781 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2782 bool CanThrow) {
2783 llvm::FunctionCallee F = CGM.getBlockObjectDispose();
2784 llvm::Value *args[] = {V,
2785 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())};
2787 if (CanThrow)
2788 EmitRuntimeCallOrInvoke(F, args);
2789 else
2790 EmitNounwindRuntimeCall(F, args);
2793 void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2794 BlockFieldFlags Flags,
2795 bool LoadBlockVarAddr, bool CanThrow) {
2796 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2797 CanThrow);
2800 /// Adjust the declaration of something from the blocks API.
2801 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2802 llvm::Constant *C) {
2803 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2805 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2806 const IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2807 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2808 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2810 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2811 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2812 "expected Function or GlobalVariable");
2814 const NamedDecl *ND = nullptr;
2815 for (const auto *Result : DC->lookup(&II))
2816 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2817 (ND = dyn_cast<VarDecl>(Result)))
2818 break;
2820 // TODO: support static blocks runtime
2821 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2822 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2823 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2824 } else {
2825 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2826 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2830 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2831 GV->hasExternalLinkage())
2832 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2834 CGM.setDSOLocal(GV);
2837 llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
2838 if (BlockObjectDispose)
2839 return BlockObjectDispose;
2841 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2842 llvm::FunctionType *fty
2843 = llvm::FunctionType::get(VoidTy, args, false);
2844 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2845 configureBlocksRuntimeObject(
2846 *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
2847 return BlockObjectDispose;
2850 llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
2851 if (BlockObjectAssign)
2852 return BlockObjectAssign;
2854 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2855 llvm::FunctionType *fty
2856 = llvm::FunctionType::get(VoidTy, args, false);
2857 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2858 configureBlocksRuntimeObject(
2859 *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
2860 return BlockObjectAssign;
2863 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2864 if (NSConcreteGlobalBlock)
2865 return NSConcreteGlobalBlock;
2867 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal(
2868 "_NSConcreteGlobalBlock", Int8PtrTy, LangAS::Default, nullptr);
2869 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2870 return NSConcreteGlobalBlock;
2873 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2874 if (NSConcreteStackBlock)
2875 return NSConcreteStackBlock;
2877 NSConcreteStackBlock = GetOrCreateLLVMGlobal(
2878 "_NSConcreteStackBlock", Int8PtrTy, LangAS::Default, nullptr);
2879 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2880 return NSConcreteStackBlock;