1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This contains code to emit blocks.
11 //===----------------------------------------------------------------------===//
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/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"
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(Address::invalid()), StructureType(nullptr), Block(block
) {
41 // Skip asm prefix, if any. 'name' is usually taken directly from
42 // the mangled name of the enclosing function.
43 if (!name
.empty() && name
[0] == '\01')
44 name
= name
.substr(1);
47 // Anchor the vtable to this translation unit.
48 BlockByrefHelpers::~BlockByrefHelpers() {}
50 /// Build the given block as a global block.
51 static llvm::Constant
*buildGlobalBlock(CodeGenModule
&CGM
,
52 const CGBlockInfo
&blockInfo
,
53 llvm::Constant
*blockFn
);
55 /// Build the helper function to copy a block.
56 static llvm::Constant
*buildCopyHelper(CodeGenModule
&CGM
,
57 const CGBlockInfo
&blockInfo
) {
58 return CodeGenFunction(CGM
).GenerateCopyHelperFunction(blockInfo
);
61 /// Build the helper function to dispose of a block.
62 static llvm::Constant
*buildDisposeHelper(CodeGenModule
&CGM
,
63 const CGBlockInfo
&blockInfo
) {
64 return CodeGenFunction(CGM
).GenerateDestroyHelperFunction(blockInfo
);
69 enum class CaptureStrKind
{
70 // String for the copy helper.
72 // String for the dispose helper.
74 // Merge the strings for the copy helper and dispose helper.
78 } // end anonymous namespace
80 static std::string
getBlockCaptureStr(const CGBlockInfo::Capture
&Cap
,
81 CaptureStrKind StrKind
,
82 CharUnits BlockAlignment
,
85 static std::string
getBlockDescriptorName(const CGBlockInfo
&BlockInfo
,
87 std::string Name
= "__block_descriptor_";
88 Name
+= llvm::to_string(BlockInfo
.BlockSize
.getQuantity()) + "_";
90 if (BlockInfo
.NeedsCopyDispose
) {
91 if (CGM
.getLangOpts().Exceptions
)
93 if (CGM
.getCodeGenOpts().ObjCAutoRefCountExceptions
)
95 Name
+= llvm::to_string(BlockInfo
.BlockAlign
.getQuantity()) + "_";
97 for (auto &Cap
: BlockInfo
.SortedCaptures
) {
98 if (Cap
.isConstantOrTrivial())
101 Name
+= llvm::to_string(Cap
.getOffset().getQuantity());
103 if (Cap
.CopyKind
== Cap
.DisposeKind
) {
104 // If CopyKind and DisposeKind are the same, merge the capture
106 assert(Cap
.CopyKind
!= BlockCaptureEntityKind::None
&&
107 "shouldn't see BlockCaptureManagedEntity that is None");
108 Name
+= getBlockCaptureStr(Cap
, CaptureStrKind::Merged
,
109 BlockInfo
.BlockAlign
, CGM
);
111 // If CopyKind and DisposeKind are not the same, which can happen when
112 // either Kind is None or the captured object is a __strong block,
113 // concatenate the copy and dispose strings.
114 Name
+= getBlockCaptureStr(Cap
, CaptureStrKind::CopyHelper
,
115 BlockInfo
.BlockAlign
, CGM
);
116 Name
+= getBlockCaptureStr(Cap
, CaptureStrKind::DisposeHelper
,
117 BlockInfo
.BlockAlign
, CGM
);
123 std::string TypeAtEncoding
=
124 CGM
.getContext().getObjCEncodingForBlock(BlockInfo
.getBlockExpr());
125 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
126 /// a separator between symbol name and symbol version.
127 std::replace(TypeAtEncoding
.begin(), TypeAtEncoding
.end(), '@', '\1');
128 Name
+= "e" + llvm::to_string(TypeAtEncoding
.size()) + "_" + TypeAtEncoding
;
129 Name
+= "l" + CGM
.getObjCRuntime().getRCBlockLayoutStr(CGM
, BlockInfo
);
133 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
134 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
135 /// meta-data and contains stationary information about the block literal.
136 /// Its definition will have 4 (or optionally 6) words.
138 /// struct Block_descriptor {
139 /// unsigned long reserved;
140 /// unsigned long size; // size of Block_literal metadata in bytes.
141 /// void *copy_func_helper_decl; // optional copy helper.
142 /// void *destroy_func_decl; // optional destructor helper.
143 /// void *block_method_encoding_address; // @encode for block literal signature.
144 /// void *block_layout_info; // encoding of captured block variables.
147 static llvm::Constant
*buildBlockDescriptor(CodeGenModule
&CGM
,
148 const CGBlockInfo
&blockInfo
) {
149 ASTContext
&C
= CGM
.getContext();
151 llvm::IntegerType
*ulong
=
152 cast
<llvm::IntegerType
>(CGM
.getTypes().ConvertType(C
.UnsignedLongTy
));
153 llvm::PointerType
*i8p
= nullptr;
154 if (CGM
.getLangOpts().OpenCL
)
155 i8p
= llvm::PointerType::get(
156 CGM
.getLLVMContext(), C
.getTargetAddressSpace(LangAS::opencl_constant
));
160 std::string descName
;
162 // If an equivalent block descriptor global variable exists, return it.
163 if (C
.getLangOpts().ObjC
&&
164 CGM
.getLangOpts().getGC() == LangOptions::NonGC
) {
165 descName
= getBlockDescriptorName(blockInfo
, CGM
);
166 if (llvm::GlobalValue
*desc
= CGM
.getModule().getNamedValue(descName
))
167 return llvm::ConstantExpr::getBitCast(desc
,
168 CGM
.getBlockDescriptorType());
171 // If there isn't an equivalent block descriptor global variable, create a new
173 ConstantInitBuilder
builder(CGM
);
174 auto elements
= builder
.beginStruct();
177 elements
.addInt(ulong
, 0);
180 // FIXME: What is the right way to say this doesn't fit? We should give
181 // a user diagnostic in that case. Better fix would be to change the
183 elements
.addInt(ulong
, blockInfo
.BlockSize
.getQuantity());
185 // Optional copy/dispose helpers.
186 bool hasInternalHelper
= false;
187 if (blockInfo
.NeedsCopyDispose
) {
188 // copy_func_helper_decl
189 llvm::Constant
*copyHelper
= buildCopyHelper(CGM
, blockInfo
);
190 elements
.add(copyHelper
);
193 llvm::Constant
*disposeHelper
= buildDisposeHelper(CGM
, blockInfo
);
194 elements
.add(disposeHelper
);
196 if (cast
<llvm::Function
>(copyHelper
->stripPointerCasts())
197 ->hasInternalLinkage() ||
198 cast
<llvm::Function
>(disposeHelper
->stripPointerCasts())
199 ->hasInternalLinkage())
200 hasInternalHelper
= true;
203 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
204 std::string typeAtEncoding
=
205 CGM
.getContext().getObjCEncodingForBlock(blockInfo
.getBlockExpr());
206 elements
.add(llvm::ConstantExpr::getBitCast(
207 CGM
.GetAddrOfConstantCString(typeAtEncoding
).getPointer(), i8p
));
210 if (C
.getLangOpts().ObjC
) {
211 if (CGM
.getLangOpts().getGC() != LangOptions::NonGC
)
212 elements
.add(CGM
.getObjCRuntime().BuildGCBlockLayout(CGM
, blockInfo
));
214 elements
.add(CGM
.getObjCRuntime().BuildRCBlockLayout(CGM
, blockInfo
));
217 elements
.addNullPointer(i8p
);
219 unsigned AddrSpace
= 0;
220 if (C
.getLangOpts().OpenCL
)
221 AddrSpace
= C
.getTargetAddressSpace(LangAS::opencl_constant
);
223 llvm::GlobalValue::LinkageTypes linkage
;
224 if (descName
.empty()) {
225 linkage
= llvm::GlobalValue::InternalLinkage
;
226 descName
= "__block_descriptor_tmp";
227 } else if (hasInternalHelper
) {
228 // If either the copy helper or the dispose helper has internal linkage,
229 // the block descriptor must have internal linkage too.
230 linkage
= llvm::GlobalValue::InternalLinkage
;
232 linkage
= llvm::GlobalValue::LinkOnceODRLinkage
;
235 llvm::GlobalVariable
*global
=
236 elements
.finishAndCreateGlobal(descName
, CGM
.getPointerAlign(),
237 /*constant*/ true, linkage
, AddrSpace
);
239 if (linkage
== llvm::GlobalValue::LinkOnceODRLinkage
) {
240 if (CGM
.supportsCOMDAT())
241 global
->setComdat(CGM
.getModule().getOrInsertComdat(descName
));
242 global
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
243 global
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
246 return llvm::ConstantExpr::getBitCast(global
, CGM
.getBlockDescriptorType());
250 Purely notional variadic template describing the layout of a block.
252 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
253 struct Block_literal {
254 /// Initialized to one of:
255 /// extern void *_NSConcreteStackBlock[];
256 /// extern void *_NSConcreteGlobalBlock[];
258 /// In theory, we could start one off malloc'ed by setting
259 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
261 /// extern void *_NSConcreteMallocBlock[];
262 struct objc_class *isa;
264 /// These are the flags (with corresponding bit number) that the
265 /// compiler is actually supposed to know about.
266 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
267 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
268 /// descriptor provides copy and dispose helper functions
269 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
270 /// object with a nontrivial destructor or copy constructor
271 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
273 /// 29. BLOCK_USE_STRET - indicates that the block function
274 /// uses stret, which objc_msgSend needs to know about
275 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
276 /// @encoded signature string
277 /// And we're not supposed to manipulate these:
278 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
279 /// to malloc'ed memory
280 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
281 /// to GC-allocated memory
282 /// Additionally, the bottom 16 bits are a reference count which
283 /// should be zero on the stack.
286 /// Reserved; should be zero-initialized.
289 /// Function pointer generated from block literal.
290 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
292 /// Block description metadata generated from block literal.
293 struct Block_descriptor *block_descriptor;
295 /// Captured values follow.
296 _CapturesTypes captures...;
301 /// A chunk of data that we actually have to capture in the block.
302 struct BlockLayoutChunk
{
305 const BlockDecl::Capture
*Capture
; // null for 'this'
308 BlockCaptureEntityKind CopyKind
, DisposeKind
;
309 BlockFieldFlags CopyFlags
, DisposeFlags
;
311 BlockLayoutChunk(CharUnits align
, CharUnits size
,
312 const BlockDecl::Capture
*capture
, llvm::Type
*type
,
313 QualType fieldType
, BlockCaptureEntityKind CopyKind
,
314 BlockFieldFlags CopyFlags
,
315 BlockCaptureEntityKind DisposeKind
,
316 BlockFieldFlags DisposeFlags
)
317 : Alignment(align
), Size(size
), Capture(capture
), Type(type
),
318 FieldType(fieldType
), CopyKind(CopyKind
), DisposeKind(DisposeKind
),
319 CopyFlags(CopyFlags
), DisposeFlags(DisposeFlags
) {}
321 /// Tell the block info that this chunk has the given field index.
322 void setIndex(CGBlockInfo
&info
, unsigned index
, CharUnits offset
) {
324 info
.CXXThisIndex
= index
;
325 info
.CXXThisOffset
= offset
;
327 info
.SortedCaptures
.push_back(CGBlockInfo::Capture::makeIndex(
328 index
, offset
, FieldType
, CopyKind
, CopyFlags
, DisposeKind
,
329 DisposeFlags
, Capture
));
333 bool isTrivial() const {
334 return CopyKind
== BlockCaptureEntityKind::None
&&
335 DisposeKind
== BlockCaptureEntityKind::None
;
339 /// Order by 1) all __strong together 2) next, all block together 3) next,
340 /// all byref together 4) next, all __weak together. Preserve descending
341 /// alignment in all situations.
342 bool operator<(const BlockLayoutChunk
&left
, const BlockLayoutChunk
&right
) {
343 if (left
.Alignment
!= right
.Alignment
)
344 return left
.Alignment
> right
.Alignment
;
346 auto getPrefOrder
= [](const BlockLayoutChunk
&chunk
) {
347 switch (chunk
.CopyKind
) {
348 case BlockCaptureEntityKind::ARCStrong
:
350 case BlockCaptureEntityKind::BlockObject
:
351 switch (chunk
.CopyFlags
.getBitMask()) {
352 case BLOCK_FIELD_IS_OBJECT
:
354 case BLOCK_FIELD_IS_BLOCK
:
356 case BLOCK_FIELD_IS_BYREF
:
362 case BlockCaptureEntityKind::ARCWeak
:
370 return getPrefOrder(left
) < getPrefOrder(right
);
372 } // end anonymous namespace
374 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
375 computeCopyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
376 const LangOptions
&LangOpts
);
378 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
379 computeDestroyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
380 const LangOptions
&LangOpts
);
382 static void addBlockLayout(CharUnits align
, CharUnits size
,
383 const BlockDecl::Capture
*capture
, llvm::Type
*type
,
385 SmallVectorImpl
<BlockLayoutChunk
> &Layout
,
386 CGBlockInfo
&Info
, CodeGenModule
&CGM
) {
389 Layout
.push_back(BlockLayoutChunk(
390 align
, size
, capture
, type
, fieldType
, BlockCaptureEntityKind::None
,
391 BlockFieldFlags(), BlockCaptureEntityKind::None
, BlockFieldFlags()));
395 const LangOptions
&LangOpts
= CGM
.getLangOpts();
396 BlockCaptureEntityKind CopyKind
, DisposeKind
;
397 BlockFieldFlags CopyFlags
, DisposeFlags
;
399 std::tie(CopyKind
, CopyFlags
) =
400 computeCopyInfoForBlockCapture(*capture
, fieldType
, LangOpts
);
401 std::tie(DisposeKind
, DisposeFlags
) =
402 computeDestroyInfoForBlockCapture(*capture
, fieldType
, LangOpts
);
403 Layout
.push_back(BlockLayoutChunk(align
, size
, capture
, type
, fieldType
,
404 CopyKind
, CopyFlags
, DisposeKind
,
410 if (!Layout
.back().isTrivial())
411 Info
.NeedsCopyDispose
= true;
414 /// Determines if the given type is safe for constant capture in C++.
415 static bool isSafeForCXXConstantCapture(QualType type
) {
416 const RecordType
*recordType
=
417 type
->getBaseElementTypeUnsafe()->getAs
<RecordType
>();
419 // Only records can be unsafe.
420 if (!recordType
) return true;
422 const auto *record
= cast
<CXXRecordDecl
>(recordType
->getDecl());
424 // Maintain semantics for classes with non-trivial dtors or copy ctors.
425 if (!record
->hasTrivialDestructor()) return false;
426 if (record
->hasNonTrivialCopyConstructor()) return false;
428 // Otherwise, we just have to make sure there aren't any mutable
429 // fields that might have changed since initialization.
430 return !record
->hasMutableFields();
433 /// It is illegal to modify a const object after initialization.
434 /// Therefore, if a const object has a constant initializer, we don't
435 /// actually need to keep storage for it in the block; we'll just
436 /// rematerialize it at the start of the block function. This is
437 /// acceptable because we make no promises about address stability of
438 /// captured variables.
439 static llvm::Constant
*tryCaptureAsConstant(CodeGenModule
&CGM
,
440 CodeGenFunction
*CGF
,
441 const VarDecl
*var
) {
442 // Return if this is a function parameter. We shouldn't try to
443 // rematerialize default arguments of function parameters.
444 if (isa
<ParmVarDecl
>(var
))
447 QualType type
= var
->getType();
449 // We can only do this if the variable is const.
450 if (!type
.isConstQualified()) return nullptr;
452 // Furthermore, in C++ we have to worry about mutable fields:
453 // C++ [dcl.type.cv]p4:
454 // Except that any class member declared mutable can be
455 // modified, any attempt to modify a const object during its
456 // lifetime results in undefined behavior.
457 if (CGM
.getLangOpts().CPlusPlus
&& !isSafeForCXXConstantCapture(type
))
460 // If the variable doesn't have any initializer (shouldn't this be
461 // invalid?), it's not clear what we should do. Maybe capture as
463 const Expr
*init
= var
->getInit();
464 if (!init
) return nullptr;
466 return ConstantEmitter(CGM
, CGF
).tryEmitAbstractForInitializer(*var
);
469 /// Get the low bit of a nonzero character count. This is the
470 /// alignment of the nth byte if the 0th byte is universally aligned.
471 static CharUnits
getLowBit(CharUnits v
) {
472 return CharUnits::fromQuantity(v
.getQuantity() & (~v
.getQuantity() + 1));
475 static void initializeForBlockHeader(CodeGenModule
&CGM
, CGBlockInfo
&info
,
476 SmallVectorImpl
<llvm::Type
*> &elementTypes
) {
478 assert(elementTypes
.empty());
479 if (CGM
.getLangOpts().OpenCL
) {
480 // The header is basically 'struct { int; int; generic void *;
481 // custom_fields; }'. Assert that struct is packed.
482 auto GenPtrAlign
= CharUnits::fromQuantity(
483 CGM
.getTarget().getPointerAlign(LangAS::opencl_generic
) / 8);
484 auto GenPtrSize
= CharUnits::fromQuantity(
485 CGM
.getTarget().getPointerWidth(LangAS::opencl_generic
) / 8);
486 assert(CGM
.getIntSize() <= GenPtrSize
);
487 assert(CGM
.getIntAlign() <= GenPtrAlign
);
488 assert((2 * CGM
.getIntSize()).isMultipleOf(GenPtrAlign
));
489 elementTypes
.push_back(CGM
.IntTy
); /* total size */
490 elementTypes
.push_back(CGM
.IntTy
); /* align */
491 elementTypes
.push_back(
492 CGM
.getOpenCLRuntime()
493 .getGenericVoidPointerType()); /* invoke function */
495 2 * CGM
.getIntSize().getQuantity() + GenPtrSize
.getQuantity();
496 unsigned BlockAlign
= GenPtrAlign
.getQuantity();
498 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
499 for (auto *I
: Helper
->getCustomFieldTypes()) /* custom fields */ {
500 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
501 // If necessary, add padding fields to the custom fields.
502 unsigned Align
= CGM
.getDataLayout().getABITypeAlign(I
).value();
503 if (BlockAlign
< Align
)
505 assert(Offset
% Align
== 0);
506 Offset
+= CGM
.getDataLayout().getTypeAllocSize(I
);
507 elementTypes
.push_back(I
);
510 info
.BlockAlign
= CharUnits::fromQuantity(BlockAlign
);
511 info
.BlockSize
= CharUnits::fromQuantity(Offset
);
513 // The header is basically 'struct { void *; int; int; void *; void *; }'.
514 // Assert that the struct is packed.
515 assert(CGM
.getIntSize() <= CGM
.getPointerSize());
516 assert(CGM
.getIntAlign() <= CGM
.getPointerAlign());
517 assert((2 * CGM
.getIntSize()).isMultipleOf(CGM
.getPointerAlign()));
518 info
.BlockAlign
= CGM
.getPointerAlign();
519 info
.BlockSize
= 3 * CGM
.getPointerSize() + 2 * CGM
.getIntSize();
520 elementTypes
.push_back(CGM
.VoidPtrTy
);
521 elementTypes
.push_back(CGM
.IntTy
);
522 elementTypes
.push_back(CGM
.IntTy
);
523 elementTypes
.push_back(CGM
.VoidPtrTy
);
524 elementTypes
.push_back(CGM
.getBlockDescriptorType());
528 static QualType
getCaptureFieldType(const CodeGenFunction
&CGF
,
529 const BlockDecl::Capture
&CI
) {
530 const VarDecl
*VD
= CI
.getVariable();
532 // If the variable is captured by an enclosing block or lambda expression,
533 // use the type of the capture field.
534 if (CGF
.BlockInfo
&& CI
.isNested())
535 return CGF
.BlockInfo
->getCapture(VD
).fieldType();
536 if (auto *FD
= CGF
.LambdaCaptureFields
.lookup(VD
))
537 return FD
->getType();
538 // If the captured variable is a non-escaping __block variable, the field
539 // type is the reference type. If the variable is a __block variable that
540 // already has a reference type, the field type is the variable's type.
541 return VD
->isNonEscapingByref() ?
542 CGF
.getContext().getLValueReferenceType(VD
->getType()) : VD
->getType();
545 /// Compute the layout of the given block. Attempts to lay the block
546 /// out with minimal space requirements.
547 static void computeBlockInfo(CodeGenModule
&CGM
, CodeGenFunction
*CGF
,
549 ASTContext
&C
= CGM
.getContext();
550 const BlockDecl
*block
= info
.getBlockDecl();
552 SmallVector
<llvm::Type
*, 8> elementTypes
;
553 initializeForBlockHeader(CGM
, info
, elementTypes
);
554 bool hasNonConstantCustomFields
= false;
555 if (auto *OpenCLHelper
=
556 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
557 hasNonConstantCustomFields
=
558 !OpenCLHelper
->areAllCustomFieldValuesConstant(info
);
559 if (!block
->hasCaptures() && !hasNonConstantCustomFields
) {
561 llvm::StructType::get(CGM
.getLLVMContext(), elementTypes
, true);
562 info
.CanBeGlobal
= true;
565 else if (C
.getLangOpts().ObjC
&&
566 CGM
.getLangOpts().getGC() == LangOptions::NonGC
)
567 info
.HasCapturedVariableLayout
= true;
569 if (block
->doesNotEscape())
570 info
.NoEscape
= true;
572 // Collect the layout chunks.
573 SmallVector
<BlockLayoutChunk
, 16> layout
;
574 layout
.reserve(block
->capturesCXXThis() +
575 (block
->capture_end() - block
->capture_begin()));
577 CharUnits maxFieldAlign
;
580 if (block
->capturesCXXThis()) {
581 assert(CGF
&& CGF
->CurFuncDecl
&& isa
<CXXMethodDecl
>(CGF
->CurFuncDecl
) &&
582 "Can't capture 'this' outside a method");
583 QualType thisType
= cast
<CXXMethodDecl
>(CGF
->CurFuncDecl
)->getThisType();
585 // Theoretically, this could be in a different address space, so
586 // don't assume standard pointer size/align.
587 llvm::Type
*llvmType
= CGM
.getTypes().ConvertType(thisType
);
588 auto TInfo
= CGM
.getContext().getTypeInfoInChars(thisType
);
589 maxFieldAlign
= std::max(maxFieldAlign
, TInfo
.Align
);
591 addBlockLayout(TInfo
.Align
, TInfo
.Width
, nullptr, llvmType
, thisType
,
595 // Next, all the block captures.
596 for (const auto &CI
: block
->captures()) {
597 const VarDecl
*variable
= CI
.getVariable();
599 if (CI
.isEscapingByref()) {
600 // Just use void* instead of a pointer to the byref type.
601 CharUnits align
= CGM
.getPointerAlign();
602 maxFieldAlign
= std::max(maxFieldAlign
, align
);
604 // Since a __block variable cannot be captured by lambdas, its type and
605 // the capture field type should always match.
606 assert(CGF
&& getCaptureFieldType(*CGF
, CI
) == variable
->getType() &&
607 "capture type differs from the variable type");
608 addBlockLayout(align
, CGM
.getPointerSize(), &CI
, CGM
.VoidPtrTy
,
609 variable
->getType(), layout
, info
, CGM
);
613 // Otherwise, build a layout chunk with the size and alignment of
615 if (llvm::Constant
*constant
= tryCaptureAsConstant(CGM
, CGF
, variable
)) {
616 info
.SortedCaptures
.push_back(
617 CGBlockInfo::Capture::makeConstant(constant
, &CI
));
621 QualType VT
= getCaptureFieldType(*CGF
, CI
);
623 if (CGM
.getLangOpts().CPlusPlus
)
624 if (const CXXRecordDecl
*record
= VT
->getAsCXXRecordDecl())
625 if (CI
.hasCopyExpr() || !record
->hasTrivialDestructor()) {
626 info
.HasCXXObject
= true;
627 if (!record
->isExternallyVisible())
628 info
.CapturesNonExternalType
= true;
631 CharUnits size
= C
.getTypeSizeInChars(VT
);
632 CharUnits align
= C
.getDeclAlign(variable
);
634 maxFieldAlign
= std::max(maxFieldAlign
, align
);
636 llvm::Type
*llvmType
=
637 CGM
.getTypes().ConvertTypeForMem(VT
);
639 addBlockLayout(align
, size
, &CI
, llvmType
, VT
, layout
, info
, CGM
);
642 // If that was everything, we're done here.
643 if (layout
.empty()) {
645 llvm::StructType::get(CGM
.getLLVMContext(), elementTypes
, true);
646 info
.CanBeGlobal
= true;
647 info
.buildCaptureMap();
651 // Sort the layout by alignment. We have to use a stable sort here
652 // to get reproducible results. There should probably be an
653 // llvm::array_pod_stable_sort.
654 llvm::stable_sort(layout
);
656 // Needed for blocks layout info.
657 info
.BlockHeaderForcedGapOffset
= info
.BlockSize
;
658 info
.BlockHeaderForcedGapSize
= CharUnits::Zero();
660 CharUnits
&blockSize
= info
.BlockSize
;
661 info
.BlockAlign
= std::max(maxFieldAlign
, info
.BlockAlign
);
663 // Assuming that the first byte in the header is maximally aligned,
664 // get the alignment of the first byte following the header.
665 CharUnits endAlign
= getLowBit(blockSize
);
667 // If the end of the header isn't satisfactorily aligned for the
668 // maximum thing, look for things that are okay with the header-end
669 // alignment, and keep appending them until we get something that's
670 // aligned right. This algorithm is only guaranteed optimal if
671 // that condition is satisfied at some point; otherwise we can get
673 // header // next byte has alignment 4
674 // something_with_size_5; // next byte has alignment 1
675 // something_with_alignment_8;
676 // which has 7 bytes of padding, as opposed to the naive solution
677 // which might have less (?).
678 if (endAlign
< maxFieldAlign
) {
679 SmallVectorImpl
<BlockLayoutChunk
>::iterator
680 li
= layout
.begin() + 1, le
= layout
.end();
682 // Look for something that the header end is already
683 // satisfactorily aligned for.
684 for (; li
!= le
&& endAlign
< li
->Alignment
; ++li
)
687 // If we found something that's naturally aligned for the end of
688 // the header, keep adding things...
690 SmallVectorImpl
<BlockLayoutChunk
>::iterator first
= li
;
691 for (; li
!= le
; ++li
) {
692 assert(endAlign
>= li
->Alignment
);
694 li
->setIndex(info
, elementTypes
.size(), blockSize
);
695 elementTypes
.push_back(li
->Type
);
696 blockSize
+= li
->Size
;
697 endAlign
= getLowBit(blockSize
);
699 // ...until we get to the alignment of the maximum field.
700 if (endAlign
>= maxFieldAlign
) {
705 // Don't re-append everything we just appended.
706 layout
.erase(first
, li
);
710 assert(endAlign
== getLowBit(blockSize
));
712 // At this point, we just have to add padding if the end align still
713 // isn't aligned right.
714 if (endAlign
< maxFieldAlign
) {
715 CharUnits newBlockSize
= blockSize
.alignTo(maxFieldAlign
);
716 CharUnits padding
= newBlockSize
- blockSize
;
718 // If we haven't yet added any fields, remember that there was an
719 // initial gap; this need to go into the block layout bit map.
720 if (blockSize
== info
.BlockHeaderForcedGapOffset
) {
721 info
.BlockHeaderForcedGapSize
= padding
;
724 elementTypes
.push_back(llvm::ArrayType::get(CGM
.Int8Ty
,
725 padding
.getQuantity()));
726 blockSize
= newBlockSize
;
727 endAlign
= getLowBit(blockSize
); // might be > maxFieldAlign
730 assert(endAlign
>= maxFieldAlign
);
731 assert(endAlign
== getLowBit(blockSize
));
732 // Slam everything else on now. This works because they have
733 // strictly decreasing alignment and we expect that size is always a
734 // multiple of alignment.
735 for (SmallVectorImpl
<BlockLayoutChunk
>::iterator
736 li
= layout
.begin(), le
= layout
.end(); li
!= le
; ++li
) {
737 if (endAlign
< li
->Alignment
) {
738 // size may not be multiple of alignment. This can only happen with
739 // an over-aligned variable. We will be adding a padding field to
740 // make the size be multiple of alignment.
741 CharUnits padding
= li
->Alignment
- endAlign
;
742 elementTypes
.push_back(llvm::ArrayType::get(CGM
.Int8Ty
,
743 padding
.getQuantity()));
744 blockSize
+= padding
;
745 endAlign
= getLowBit(blockSize
);
747 assert(endAlign
>= li
->Alignment
);
748 li
->setIndex(info
, elementTypes
.size(), blockSize
);
749 elementTypes
.push_back(li
->Type
);
750 blockSize
+= li
->Size
;
751 endAlign
= getLowBit(blockSize
);
754 info
.buildCaptureMap();
756 llvm::StructType::get(CGM
.getLLVMContext(), elementTypes
, true);
759 /// Emit a block literal expression in the current function.
760 llvm::Value
*CodeGenFunction::EmitBlockLiteral(const BlockExpr
*blockExpr
) {
761 // If the block has no captures, we won't have a pre-computed
763 if (!blockExpr
->getBlockDecl()->hasCaptures())
764 // The block literal is emitted as a global variable, and the block invoke
765 // function has to be extracted from its initializer.
766 if (llvm::Constant
*Block
= CGM
.getAddrOfGlobalBlockIfEmitted(blockExpr
))
769 CGBlockInfo
blockInfo(blockExpr
->getBlockDecl(), CurFn
->getName());
770 computeBlockInfo(CGM
, this, blockInfo
);
771 blockInfo
.BlockExpression
= blockExpr
;
772 if (!blockInfo
.CanBeGlobal
)
773 blockInfo
.LocalAddress
= CreateTempAlloca(blockInfo
.StructureType
,
774 blockInfo
.BlockAlign
, "block");
775 return EmitBlockLiteral(blockInfo
);
778 llvm::Value
*CodeGenFunction::EmitBlockLiteral(const CGBlockInfo
&blockInfo
) {
779 bool IsOpenCL
= CGM
.getContext().getLangOpts().OpenCL
;
781 IsOpenCL
? CGM
.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy
;
782 LangAS GenVoidPtrAddr
= IsOpenCL
? LangAS::opencl_generic
: LangAS::Default
;
783 auto GenVoidPtrSize
= CharUnits::fromQuantity(
784 CGM
.getTarget().getPointerWidth(GenVoidPtrAddr
) / 8);
785 // Using the computed layout, generate the actual block function.
786 bool isLambdaConv
= blockInfo
.getBlockDecl()->isConversionFromLambda();
787 CodeGenFunction BlockCGF
{CGM
, true};
788 BlockCGF
.SanOpts
= SanOpts
;
789 auto *InvokeFn
= BlockCGF
.GenerateBlockFunction(
790 CurGD
, blockInfo
, LocalDeclMap
, isLambdaConv
, blockInfo
.CanBeGlobal
);
791 auto *blockFn
= llvm::ConstantExpr::getPointerCast(InvokeFn
, GenVoidPtrTy
);
793 // If there is nothing to capture, we can emit this as a global block.
794 if (blockInfo
.CanBeGlobal
)
795 return CGM
.getAddrOfGlobalBlockIfEmitted(blockInfo
.BlockExpression
);
797 // Otherwise, we have to emit this as a local block.
799 Address blockAddr
= blockInfo
.LocalAddress
;
800 assert(blockAddr
.isValid() && "block has no address!");
803 llvm::Constant
*descriptor
;
806 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
807 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
808 // block just returns the original block and releasing it is a no-op.
809 llvm::Constant
*blockISA
= blockInfo
.NoEscape
810 ? CGM
.getNSConcreteGlobalBlock()
811 : CGM
.getNSConcreteStackBlock();
812 isa
= llvm::ConstantExpr::getBitCast(blockISA
, VoidPtrTy
);
814 // Build the block descriptor.
815 descriptor
= buildBlockDescriptor(CGM
, blockInfo
);
817 // Compute the initial on-stack block flags.
818 flags
= BLOCK_HAS_SIGNATURE
;
819 if (blockInfo
.HasCapturedVariableLayout
)
820 flags
|= BLOCK_HAS_EXTENDED_LAYOUT
;
821 if (blockInfo
.NeedsCopyDispose
)
822 flags
|= BLOCK_HAS_COPY_DISPOSE
;
823 if (blockInfo
.HasCXXObject
)
824 flags
|= BLOCK_HAS_CXX_OBJ
;
825 if (blockInfo
.UsesStret
)
826 flags
|= BLOCK_USE_STRET
;
827 if (blockInfo
.NoEscape
)
828 flags
|= BLOCK_IS_NOESCAPE
| BLOCK_IS_GLOBAL
;
831 auto projectField
= [&](unsigned index
, const Twine
&name
) -> Address
{
832 return Builder
.CreateStructGEP(blockAddr
, index
, name
);
834 auto storeField
= [&](llvm::Value
*value
, unsigned index
, const Twine
&name
) {
835 Builder
.CreateStore(value
, projectField(index
, name
));
838 // Initialize the block header.
840 // We assume all the header fields are densely packed.
843 auto addHeaderField
= [&](llvm::Value
*value
, CharUnits size
,
845 storeField(value
, index
, name
);
851 addHeaderField(isa
, getPointerSize(), "block.isa");
852 addHeaderField(llvm::ConstantInt::get(IntTy
, flags
.getBitMask()),
853 getIntSize(), "block.flags");
854 addHeaderField(llvm::ConstantInt::get(IntTy
, 0), getIntSize(),
858 llvm::ConstantInt::get(IntTy
, blockInfo
.BlockSize
.getQuantity()),
859 getIntSize(), "block.size");
861 llvm::ConstantInt::get(IntTy
, blockInfo
.BlockAlign
.getQuantity()),
862 getIntSize(), "block.align");
864 addHeaderField(blockFn
, GenVoidPtrSize
, "block.invoke");
866 addHeaderField(descriptor
, getPointerSize(), "block.descriptor");
867 else if (auto *Helper
=
868 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
869 for (auto I
: Helper
->getCustomFieldValues(*this, blockInfo
)) {
872 CharUnits::fromQuantity(
873 CGM
.getDataLayout().getTypeAllocSize(I
.first
->getType())),
879 // Finally, capture all the values into the block.
880 const BlockDecl
*blockDecl
= blockInfo
.getBlockDecl();
883 if (blockDecl
->capturesCXXThis()) {
885 projectField(blockInfo
.CXXThisIndex
, "block.captured-this.addr");
886 Builder
.CreateStore(LoadCXXThis(), addr
);
889 // Next, captured variables.
890 for (const auto &CI
: blockDecl
->captures()) {
891 const VarDecl
*variable
= CI
.getVariable();
892 const CGBlockInfo::Capture
&capture
= blockInfo
.getCapture(variable
);
894 // Ignore constant captures.
895 if (capture
.isConstant()) continue;
897 QualType type
= capture
.fieldType();
899 // This will be a [[type]]*, except that a byref entry will just be
901 Address blockField
= projectField(capture
.getIndex(), "block.captured");
903 // Compute the address of the thing we're going to move into the
905 Address src
= Address::invalid();
907 if (blockDecl
->isConversionFromLambda()) {
908 // The lambda capture in a lambda's conversion-to-block-pointer is
909 // special; we'll simply emit it directly.
910 src
= Address::invalid();
911 } else if (CI
.isEscapingByref()) {
912 if (BlockInfo
&& CI
.isNested()) {
913 // We need to use the capture from the enclosing block.
914 const CGBlockInfo::Capture
&enclosingCapture
=
915 BlockInfo
->getCapture(variable
);
917 // This is a [[type]]*, except that a byref entry will just be an i8**.
918 src
= Builder
.CreateStructGEP(LoadBlockStruct(),
919 enclosingCapture
.getIndex(),
920 "block.capture.addr");
922 auto I
= LocalDeclMap
.find(variable
);
923 assert(I
!= LocalDeclMap
.end());
927 DeclRefExpr
declRef(getContext(), const_cast<VarDecl
*>(variable
),
928 /*RefersToEnclosingVariableOrCapture*/ CI
.isNested(),
929 type
.getNonReferenceType(), VK_LValue
,
931 src
= EmitDeclRefLValue(&declRef
).getAddress(*this);
934 // For byrefs, we just write the pointer to the byref struct into
935 // the block field. There's no need to chase the forwarding
936 // pointer at this point, since we're building something that will
937 // live a shorter life than the stack byref anyway.
938 if (CI
.isEscapingByref()) {
939 // Get a void* that points to the byref struct.
940 llvm::Value
*byrefPointer
;
942 byrefPointer
= Builder
.CreateLoad(src
, "byref.capture");
944 byrefPointer
= src
.getPointer();
946 // Write that void* into the capture field.
947 Builder
.CreateStore(byrefPointer
, blockField
);
949 // If we have a copy constructor, evaluate that into the block field.
950 } else if (const Expr
*copyExpr
= CI
.getCopyExpr()) {
951 if (blockDecl
->isConversionFromLambda()) {
952 // If we have a lambda conversion, emit the expression
953 // directly into the block instead.
955 AggValueSlot::forAddr(blockField
, Qualifiers(),
956 AggValueSlot::IsDestructed
,
957 AggValueSlot::DoesNotNeedGCBarriers
,
958 AggValueSlot::IsNotAliased
,
959 AggValueSlot::DoesNotOverlap
);
960 EmitAggExpr(copyExpr
, Slot
);
962 EmitSynthesizedCXXCopyCtor(blockField
, src
, copyExpr
);
965 // If it's a reference variable, copy the reference into the block field.
966 } else if (type
->isReferenceType()) {
967 Builder
.CreateStore(src
.getPointer(), blockField
);
969 // If type is const-qualified, copy the value into the block field.
970 } else if (type
.isConstQualified() &&
971 type
.getObjCLifetime() == Qualifiers::OCL_Strong
&&
972 CGM
.getCodeGenOpts().OptimizationLevel
!= 0) {
973 llvm::Value
*value
= Builder
.CreateLoad(src
, "captured");
974 Builder
.CreateStore(value
, blockField
);
976 // If this is an ARC __strong block-pointer variable, don't do a
979 // TODO: this can be generalized into the normal initialization logic:
980 // we should never need to do a block-copy when initializing a local
981 // variable, because the local variable's lifetime should be strictly
982 // contained within the stack block's.
983 } else if (type
.getObjCLifetime() == Qualifiers::OCL_Strong
&&
984 type
->isBlockPointerType()) {
985 // Load the block and do a simple retain.
986 llvm::Value
*value
= Builder
.CreateLoad(src
, "block.captured_block");
987 value
= EmitARCRetainNonBlock(value
);
989 // Do a primitive store to the block field.
990 Builder
.CreateStore(value
, blockField
);
992 // Otherwise, fake up a POD copy into the block field.
994 // Fake up a new variable so that EmitScalarInit doesn't think
995 // we're referring to the variable in its own initializer.
996 ImplicitParamDecl
BlockFieldPseudoVar(getContext(), type
,
997 ImplicitParamDecl::Other
);
999 // We use one of these or the other depending on whether the
1000 // reference is nested.
1001 DeclRefExpr
declRef(getContext(), const_cast<VarDecl
*>(variable
),
1002 /*RefersToEnclosingVariableOrCapture*/ CI
.isNested(),
1003 type
, VK_LValue
, SourceLocation());
1005 ImplicitCastExpr
l2r(ImplicitCastExpr::OnStack
, type
, CK_LValueToRValue
,
1006 &declRef
, VK_PRValue
, FPOptionsOverride());
1007 // FIXME: Pass a specific location for the expr init so that the store is
1008 // attributed to a reasonable location - otherwise it may be attributed to
1009 // locations of subexpressions in the initialization.
1010 EmitExprAsInit(&l2r
, &BlockFieldPseudoVar
,
1011 MakeAddrLValue(blockField
, type
, AlignmentSource::Decl
),
1012 /*captured by init*/ false);
1015 // Push a cleanup for the capture if necessary.
1016 if (!blockInfo
.NoEscape
&& !blockInfo
.NeedsCopyDispose
)
1019 // Ignore __block captures; there's nothing special in the on-stack block
1020 // that we need to do for them.
1024 // Ignore objects that aren't destructed.
1025 QualType::DestructionKind dtorKind
= type
.isDestructedType();
1026 if (dtorKind
== QualType::DK_none
)
1029 CodeGenFunction::Destroyer
*destroyer
;
1031 // Block captures count as local values and have imprecise semantics.
1032 // They also can't be arrays, so need to worry about that.
1034 // For const-qualified captures, emit clang.arc.use to ensure the captured
1035 // object doesn't get released while we are still depending on its validity
1036 // within the block.
1037 if (type
.isConstQualified() &&
1038 type
.getObjCLifetime() == Qualifiers::OCL_Strong
&&
1039 CGM
.getCodeGenOpts().OptimizationLevel
!= 0) {
1040 assert(CGM
.getLangOpts().ObjCAutoRefCount
&&
1041 "expected ObjC ARC to be enabled");
1042 destroyer
= emitARCIntrinsicUse
;
1043 } else if (dtorKind
== QualType::DK_objc_strong_lifetime
) {
1044 destroyer
= destroyARCStrongImprecise
;
1046 destroyer
= getDestroyer(dtorKind
);
1049 CleanupKind cleanupKind
= NormalCleanup
;
1050 bool useArrayEHCleanup
= needsEHCleanup(dtorKind
);
1051 if (useArrayEHCleanup
)
1052 cleanupKind
= NormalAndEHCleanup
;
1054 // Extend the lifetime of the capture to the end of the scope enclosing the
1055 // block expression except when the block decl is in the list of RetExpr's
1056 // cleanup objects, in which case its lifetime ends after the full
1058 auto IsBlockDeclInRetExpr
= [&]() {
1059 auto *EWC
= llvm::dyn_cast_or_null
<ExprWithCleanups
>(RetExpr
);
1061 for (auto &C
: EWC
->getObjects())
1062 if (auto *BD
= C
.dyn_cast
<BlockDecl
*>())
1063 if (BD
== blockDecl
)
1068 if (IsBlockDeclInRetExpr())
1069 pushDestroy(cleanupKind
, blockField
, type
, destroyer
, useArrayEHCleanup
);
1071 pushLifetimeExtendedDestroy(cleanupKind
, blockField
, type
, destroyer
,
1075 // Cast to the converted block-pointer type, which happens (somewhat
1076 // unfortunately) to be a pointer to function type.
1077 llvm::Value
*result
= Builder
.CreatePointerCast(
1078 blockAddr
.getPointer(), ConvertType(blockInfo
.getBlockExpr()->getType()));
1081 CGM
.getOpenCLRuntime().recordBlockInfo(blockInfo
.BlockExpression
, InvokeFn
,
1082 result
, blockInfo
.StructureType
);
1089 llvm::Type
*CodeGenModule::getBlockDescriptorType() {
1090 if (BlockDescriptorType
)
1091 return BlockDescriptorType
;
1093 llvm::Type
*UnsignedLongTy
=
1094 getTypes().ConvertType(getContext().UnsignedLongTy
);
1096 // struct __block_descriptor {
1097 // unsigned long reserved;
1098 // unsigned long block_size;
1100 // // later, the following will be added
1103 // void (*copyHelper)();
1104 // void (*copyHelper)();
1105 // } helpers; // !!! optional
1107 // const char *signature; // the block signature
1108 // const char *layout; // reserved
1110 BlockDescriptorType
= llvm::StructType::create(
1111 "struct.__block_descriptor", UnsignedLongTy
, UnsignedLongTy
);
1113 // Now form a pointer to that.
1114 unsigned AddrSpace
= 0;
1115 if (getLangOpts().OpenCL
)
1116 AddrSpace
= getContext().getTargetAddressSpace(LangAS::opencl_constant
);
1117 BlockDescriptorType
= llvm::PointerType::get(BlockDescriptorType
, AddrSpace
);
1118 return BlockDescriptorType
;
1121 llvm::Type
*CodeGenModule::getGenericBlockLiteralType() {
1122 if (GenericBlockLiteralType
)
1123 return GenericBlockLiteralType
;
1125 llvm::Type
*BlockDescPtrTy
= getBlockDescriptorType();
1127 if (getLangOpts().OpenCL
) {
1128 // struct __opencl_block_literal_generic {
1131 // __generic void *__invoke;
1132 // /* custom fields */
1134 SmallVector
<llvm::Type
*, 8> StructFields(
1135 {IntTy
, IntTy
, getOpenCLRuntime().getGenericVoidPointerType()});
1136 if (auto *Helper
= getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1137 llvm::append_range(StructFields
, Helper
->getCustomFieldTypes());
1139 GenericBlockLiteralType
= llvm::StructType::create(
1140 StructFields
, "struct.__opencl_block_literal_generic");
1142 // struct __block_literal_generic {
1146 // void (*__invoke)(void *);
1147 // struct __block_descriptor *__descriptor;
1149 GenericBlockLiteralType
=
1150 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy
,
1151 IntTy
, IntTy
, VoidPtrTy
, BlockDescPtrTy
);
1154 return GenericBlockLiteralType
;
1157 RValue
CodeGenFunction::EmitBlockCallExpr(const CallExpr
*E
,
1158 ReturnValueSlot ReturnValue
) {
1159 const auto *BPT
= E
->getCallee()->getType()->castAs
<BlockPointerType
>();
1160 llvm::Value
*BlockPtr
= EmitScalarExpr(E
->getCallee());
1161 llvm::Type
*GenBlockTy
= CGM
.getGenericBlockLiteralType();
1162 llvm::Value
*Func
= nullptr;
1163 QualType FnType
= BPT
->getPointeeType();
1164 ASTContext
&Ctx
= getContext();
1167 if (getLangOpts().OpenCL
) {
1168 // For OpenCL, BlockPtr is already casted to generic block literal.
1170 // First argument of a block call is a generic block literal casted to
1171 // generic void pointer, i.e. i8 addrspace(4)*
1172 llvm::Type
*GenericVoidPtrTy
=
1173 CGM
.getOpenCLRuntime().getGenericVoidPointerType();
1174 llvm::Value
*BlockDescriptor
= Builder
.CreatePointerCast(
1175 BlockPtr
, GenericVoidPtrTy
);
1176 QualType VoidPtrQualTy
= Ctx
.getPointerType(
1177 Ctx
.getAddrSpaceQualType(Ctx
.VoidTy
, LangAS::opencl_generic
));
1178 Args
.add(RValue::get(BlockDescriptor
), VoidPtrQualTy
);
1179 // And the rest of the arguments.
1180 EmitCallArgs(Args
, FnType
->getAs
<FunctionProtoType
>(), E
->arguments());
1182 // We *can* call the block directly unless it is a function argument.
1183 if (!isa
<ParmVarDecl
>(E
->getCalleeDecl()))
1184 Func
= CGM
.getOpenCLRuntime().getInvokeFunction(E
->getCallee());
1186 llvm::Value
*FuncPtr
= Builder
.CreateStructGEP(GenBlockTy
, BlockPtr
, 2);
1187 Func
= Builder
.CreateAlignedLoad(GenericVoidPtrTy
, FuncPtr
,
1191 // Bitcast the block literal to a generic block literal.
1193 Builder
.CreatePointerCast(BlockPtr
, UnqualPtrTy
, "block.literal");
1194 // Get pointer to the block invoke function
1195 llvm::Value
*FuncPtr
= Builder
.CreateStructGEP(GenBlockTy
, BlockPtr
, 3);
1197 // First argument is a block literal casted to a void pointer
1198 BlockPtr
= Builder
.CreatePointerCast(BlockPtr
, VoidPtrTy
);
1199 Args
.add(RValue::get(BlockPtr
), Ctx
.VoidPtrTy
);
1200 // And the rest of the arguments.
1201 EmitCallArgs(Args
, FnType
->getAs
<FunctionProtoType
>(), E
->arguments());
1203 // Load the function.
1204 Func
= Builder
.CreateAlignedLoad(VoidPtrTy
, FuncPtr
, getPointerAlign());
1207 const FunctionType
*FuncTy
= FnType
->castAs
<FunctionType
>();
1208 const CGFunctionInfo
&FnInfo
=
1209 CGM
.getTypes().arrangeBlockFunctionCall(Args
, FuncTy
);
1211 // Prepare the callee.
1212 CGCallee
Callee(CGCalleeInfo(), Func
);
1214 // And call the block.
1215 return EmitCall(FnInfo
, Callee
, ReturnValue
, Args
);
1218 Address
CodeGenFunction::GetAddrOfBlockDecl(const VarDecl
*variable
) {
1219 assert(BlockInfo
&& "evaluating block ref without block information?");
1220 const CGBlockInfo::Capture
&capture
= BlockInfo
->getCapture(variable
);
1222 // Handle constant captures.
1223 if (capture
.isConstant()) return LocalDeclMap
.find(variable
)->second
;
1225 Address addr
= Builder
.CreateStructGEP(LoadBlockStruct(), capture
.getIndex(),
1226 "block.capture.addr");
1228 if (variable
->isEscapingByref()) {
1229 // addr should be a void** right now. Load, then cast the result
1232 auto &byrefInfo
= getBlockByrefInfo(variable
);
1233 addr
= Address(Builder
.CreateLoad(addr
), byrefInfo
.Type
,
1234 byrefInfo
.ByrefAlignment
);
1236 addr
= emitBlockByrefAddress(addr
, byrefInfo
, /*follow*/ true,
1237 variable
->getName());
1240 assert((!variable
->isNonEscapingByref() ||
1241 capture
.fieldType()->isReferenceType()) &&
1242 "the capture field of a non-escaping variable should have a "
1244 if (capture
.fieldType()->isReferenceType())
1245 addr
= EmitLoadOfReference(MakeAddrLValue(addr
, capture
.fieldType()));
1250 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr
*BE
,
1251 llvm::Constant
*Addr
) {
1252 bool Ok
= EmittedGlobalBlocks
.insert(std::make_pair(BE
, Addr
)).second
;
1254 assert(Ok
&& "Trying to replace an already-existing global block!");
1258 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr
*BE
,
1260 if (llvm::Constant
*Block
= getAddrOfGlobalBlockIfEmitted(BE
))
1263 CGBlockInfo
blockInfo(BE
->getBlockDecl(), Name
);
1264 blockInfo
.BlockExpression
= BE
;
1266 // Compute information about the layout, etc., of this block.
1267 computeBlockInfo(*this, nullptr, blockInfo
);
1269 // Using that metadata, generate the actual block function.
1271 CodeGenFunction::DeclMapTy LocalDeclMap
;
1272 CodeGenFunction(*this).GenerateBlockFunction(
1273 GlobalDecl(), blockInfo
, LocalDeclMap
,
1274 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1277 return getAddrOfGlobalBlockIfEmitted(BE
);
1280 static llvm::Constant
*buildGlobalBlock(CodeGenModule
&CGM
,
1281 const CGBlockInfo
&blockInfo
,
1282 llvm::Constant
*blockFn
) {
1283 assert(blockInfo
.CanBeGlobal
);
1284 // Callers should detect this case on their own: calling this function
1285 // generally requires computing layout information, which is a waste of time
1286 // if we've already emitted this block.
1287 assert(!CGM
.getAddrOfGlobalBlockIfEmitted(blockInfo
.BlockExpression
) &&
1288 "Refusing to re-emit a global block.");
1290 // Generate the constants for the block literal initializer.
1291 ConstantInitBuilder
builder(CGM
);
1292 auto fields
= builder
.beginStruct();
1294 bool IsOpenCL
= CGM
.getLangOpts().OpenCL
;
1295 bool IsWindows
= CGM
.getTarget().getTriple().isOSWindows();
1299 fields
.addNullPointer(CGM
.Int8PtrPtrTy
);
1301 fields
.add(CGM
.getNSConcreteGlobalBlock());
1304 BlockFlags flags
= BLOCK_IS_GLOBAL
| BLOCK_HAS_SIGNATURE
;
1305 if (blockInfo
.UsesStret
)
1306 flags
|= BLOCK_USE_STRET
;
1308 fields
.addInt(CGM
.IntTy
, flags
.getBitMask());
1311 fields
.addInt(CGM
.IntTy
, 0);
1313 fields
.addInt(CGM
.IntTy
, blockInfo
.BlockSize
.getQuantity());
1314 fields
.addInt(CGM
.IntTy
, blockInfo
.BlockAlign
.getQuantity());
1318 fields
.add(blockFn
);
1322 fields
.add(buildBlockDescriptor(CGM
, blockInfo
));
1323 } else if (auto *Helper
=
1324 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1325 for (auto *I
: Helper
->getCustomFieldValues(CGM
, blockInfo
)) {
1330 unsigned AddrSpace
= 0;
1331 if (CGM
.getContext().getLangOpts().OpenCL
)
1332 AddrSpace
= CGM
.getContext().getTargetAddressSpace(LangAS::opencl_global
);
1334 llvm::GlobalVariable
*literal
= fields
.finishAndCreateGlobal(
1335 "__block_literal_global", blockInfo
.BlockAlign
,
1336 /*constant*/ !IsWindows
, llvm::GlobalVariable::InternalLinkage
, AddrSpace
);
1338 literal
->addAttribute("objc_arc_inert");
1340 // Windows does not allow globals to be initialised to point to globals in
1341 // different DLLs. Any such variables must run code to initialise them.
1343 auto *Init
= llvm::Function::Create(llvm::FunctionType::get(CGM
.VoidTy
,
1344 {}), llvm::GlobalValue::InternalLinkage
, ".block_isa_init",
1346 llvm::IRBuilder
<> b(llvm::BasicBlock::Create(CGM
.getLLVMContext(), "entry",
1348 b
.CreateAlignedStore(CGM
.getNSConcreteGlobalBlock(),
1349 b
.CreateStructGEP(literal
->getValueType(), literal
, 0),
1350 CGM
.getPointerAlign().getAsAlign());
1352 // We can't use the normal LLVM global initialisation array, because we
1353 // need to specify that this runs early in library initialisation.
1354 auto *InitVar
= new llvm::GlobalVariable(CGM
.getModule(), Init
->getType(),
1355 /*isConstant*/true, llvm::GlobalValue::InternalLinkage
,
1356 Init
, ".block_isa_init_ptr");
1357 InitVar
->setSection(".CRT$XCLa");
1358 CGM
.addUsedGlobal(InitVar
);
1361 // Return a constant of the appropriately-casted type.
1362 llvm::Type
*RequiredType
=
1363 CGM
.getTypes().ConvertType(blockInfo
.getBlockExpr()->getType());
1364 llvm::Constant
*Result
=
1365 llvm::ConstantExpr::getPointerCast(literal
, RequiredType
);
1366 CGM
.setAddrOfGlobalBlock(blockInfo
.BlockExpression
, Result
);
1367 if (CGM
.getContext().getLangOpts().OpenCL
)
1368 CGM
.getOpenCLRuntime().recordBlockInfo(
1369 blockInfo
.BlockExpression
,
1370 cast
<llvm::Function
>(blockFn
->stripPointerCasts()), Result
,
1371 literal
->getValueType());
1375 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl
*D
,
1378 assert(BlockInfo
&& "not emitting prologue of block invocation function?!");
1380 // Allocate a stack slot like for any local variable to guarantee optimal
1381 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1382 Address alloc
= CreateMemTemp(D
->getType(), D
->getName() + ".addr");
1383 Builder
.CreateStore(arg
, alloc
);
1384 if (CGDebugInfo
*DI
= getDebugInfo()) {
1385 if (CGM
.getCodeGenOpts().hasReducedDebugInfo()) {
1386 DI
->setLocation(D
->getLocation());
1387 DI
->EmitDeclareOfBlockLiteralArgVariable(
1388 *BlockInfo
, D
->getName(), argNum
,
1389 cast
<llvm::AllocaInst
>(alloc
.getPointer()), Builder
);
1393 SourceLocation StartLoc
= BlockInfo
->getBlockExpr()->getBody()->getBeginLoc();
1394 ApplyDebugLocation
Scope(*this, StartLoc
);
1396 // Instead of messing around with LocalDeclMap, just set the value
1397 // directly as BlockPointer.
1398 BlockPointer
= Builder
.CreatePointerCast(
1400 llvm::PointerType::get(
1402 getContext().getLangOpts().OpenCL
1403 ? getContext().getTargetAddressSpace(LangAS::opencl_generic
)
1408 Address
CodeGenFunction::LoadBlockStruct() {
1409 assert(BlockInfo
&& "not in a block invocation function!");
1410 assert(BlockPointer
&& "no block pointer set!");
1411 return Address(BlockPointer
, BlockInfo
->StructureType
, BlockInfo
->BlockAlign
);
1414 llvm::Function
*CodeGenFunction::GenerateBlockFunction(
1415 GlobalDecl GD
, const CGBlockInfo
&blockInfo
, const DeclMapTy
&ldm
,
1416 bool IsLambdaConversionToBlock
, bool BuildGlobalBlock
) {
1417 const BlockDecl
*blockDecl
= blockInfo
.getBlockDecl();
1421 CurEHLocation
= blockInfo
.getBlockExpr()->getEndLoc();
1423 BlockInfo
= &blockInfo
;
1425 // Arrange for local static and local extern declarations to appear
1426 // to be local to this function as well, in case they're directly
1427 // referenced in a block.
1428 for (DeclMapTy::const_iterator i
= ldm
.begin(), e
= ldm
.end(); i
!= e
; ++i
) {
1429 const auto *var
= dyn_cast
<VarDecl
>(i
->first
);
1430 if (var
&& !var
->hasLocalStorage())
1431 setAddrOfLocalVar(var
, i
->second
);
1434 // Begin building the function declaration.
1436 // Build the argument list.
1437 FunctionArgList args
;
1439 // The first argument is the block pointer. Just take it as a void*
1440 // and cast it later.
1441 QualType selfTy
= getContext().VoidPtrTy
;
1443 // For OpenCL passed block pointer can be private AS local variable or
1444 // global AS program scope variable (for the case with and without captures).
1445 // Generic AS is used therefore to be able to accommodate both private and
1446 // generic AS in one implementation.
1447 if (getLangOpts().OpenCL
)
1448 selfTy
= getContext().getPointerType(getContext().getAddrSpaceQualType(
1449 getContext().VoidTy
, LangAS::opencl_generic
));
1451 IdentifierInfo
*II
= &CGM
.getContext().Idents
.get(".block_descriptor");
1453 ImplicitParamDecl
SelfDecl(getContext(), const_cast<BlockDecl
*>(blockDecl
),
1454 SourceLocation(), II
, selfTy
,
1455 ImplicitParamDecl::ObjCSelf
);
1456 args
.push_back(&SelfDecl
);
1458 // Now add the rest of the parameters.
1459 args
.append(blockDecl
->param_begin(), blockDecl
->param_end());
1461 // Create the function declaration.
1462 const FunctionProtoType
*fnType
= blockInfo
.getBlockExpr()->getFunctionType();
1463 const CGFunctionInfo
&fnInfo
=
1464 CGM
.getTypes().arrangeBlockFunctionDeclaration(fnType
, args
);
1465 if (CGM
.ReturnSlotInterferesWithArgs(fnInfo
))
1466 blockInfo
.UsesStret
= true;
1468 llvm::FunctionType
*fnLLVMType
= CGM
.getTypes().GetFunctionType(fnInfo
);
1470 StringRef name
= CGM
.getBlockMangledName(GD
, blockDecl
);
1471 llvm::Function
*fn
= llvm::Function::Create(
1472 fnLLVMType
, llvm::GlobalValue::InternalLinkage
, name
, &CGM
.getModule());
1473 CGM
.SetInternalFunctionAttributes(blockDecl
, fn
, fnInfo
);
1475 if (BuildGlobalBlock
) {
1476 auto GenVoidPtrTy
= getContext().getLangOpts().OpenCL
1477 ? CGM
.getOpenCLRuntime().getGenericVoidPointerType()
1479 buildGlobalBlock(CGM
, blockInfo
,
1480 llvm::ConstantExpr::getPointerCast(fn
, GenVoidPtrTy
));
1483 // Begin generating the function.
1484 StartFunction(blockDecl
, fnType
->getReturnType(), fn
, fnInfo
, args
,
1485 blockDecl
->getLocation(),
1486 blockInfo
.getBlockExpr()->getBody()->getBeginLoc());
1488 // Okay. Undo some of what StartFunction did.
1490 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1491 // won't delete the dbg.declare intrinsics for captured variables.
1492 llvm::Value
*BlockPointerDbgLoc
= BlockPointer
;
1493 if (CGM
.getCodeGenOpts().OptimizationLevel
== 0) {
1494 // Allocate a stack slot for it, so we can point the debugger to it
1495 Address Alloca
= CreateTempAlloca(BlockPointer
->getType(),
1498 // Set the DebugLocation to empty, so the store is recognized as a
1499 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1500 auto NL
= ApplyDebugLocation::CreateEmpty(*this);
1501 Builder
.CreateStore(BlockPointer
, Alloca
);
1502 BlockPointerDbgLoc
= Alloca
.getPointer();
1505 // If we have a C++ 'this' reference, go ahead and force it into
1507 if (blockDecl
->capturesCXXThis()) {
1508 Address addr
= Builder
.CreateStructGEP(
1509 LoadBlockStruct(), blockInfo
.CXXThisIndex
, "block.captured-this");
1510 CXXThisValue
= Builder
.CreateLoad(addr
, "this");
1513 // Also force all the constant captures.
1514 for (const auto &CI
: blockDecl
->captures()) {
1515 const VarDecl
*variable
= CI
.getVariable();
1516 const CGBlockInfo::Capture
&capture
= blockInfo
.getCapture(variable
);
1517 if (!capture
.isConstant()) continue;
1519 CharUnits align
= getContext().getDeclAlign(variable
);
1521 CreateMemTemp(variable
->getType(), align
, "block.captured-const");
1523 Builder
.CreateStore(capture
.getConstant(), alloca
);
1525 setAddrOfLocalVar(variable
, alloca
);
1528 // Save a spot to insert the debug information for all the DeclRefExprs.
1529 llvm::BasicBlock
*entry
= Builder
.GetInsertBlock();
1530 llvm::BasicBlock::iterator entry_ptr
= Builder
.GetInsertPoint();
1533 if (IsLambdaConversionToBlock
)
1534 EmitLambdaBlockInvokeBody();
1536 PGO
.assignRegionCounters(GlobalDecl(blockDecl
), fn
);
1537 incrementProfileCounter(blockDecl
->getBody());
1538 EmitStmt(blockDecl
->getBody());
1541 // Remember where we were...
1542 llvm::BasicBlock
*resume
= Builder
.GetInsertBlock();
1544 // Go back to the entry.
1546 Builder
.SetInsertPoint(entry
, entry_ptr
);
1548 // Emit debug information for all the DeclRefExprs.
1549 // FIXME: also for 'this'
1550 if (CGDebugInfo
*DI
= getDebugInfo()) {
1551 for (const auto &CI
: blockDecl
->captures()) {
1552 const VarDecl
*variable
= CI
.getVariable();
1553 DI
->EmitLocation(Builder
, variable
->getLocation());
1555 if (CGM
.getCodeGenOpts().hasReducedDebugInfo()) {
1556 const CGBlockInfo::Capture
&capture
= blockInfo
.getCapture(variable
);
1557 if (capture
.isConstant()) {
1558 auto addr
= LocalDeclMap
.find(variable
)->second
;
1559 (void)DI
->EmitDeclareOfAutoVariable(variable
, addr
.getPointer(),
1564 DI
->EmitDeclareOfBlockDeclRefVariable(
1565 variable
, BlockPointerDbgLoc
, Builder
, blockInfo
,
1566 entry_ptr
== entry
->end() ? nullptr : &*entry_ptr
);
1569 // Recover location if it was changed in the above loop.
1570 DI
->EmitLocation(Builder
,
1571 cast
<CompoundStmt
>(blockDecl
->getBody())->getRBracLoc());
1574 // And resume where we left off.
1575 if (resume
== nullptr)
1576 Builder
.ClearInsertionPoint();
1578 Builder
.SetInsertPoint(resume
);
1580 FinishFunction(cast
<CompoundStmt
>(blockDecl
->getBody())->getRBracLoc());
1585 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
1586 computeCopyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
1587 const LangOptions
&LangOpts
) {
1588 if (CI
.getCopyExpr()) {
1589 assert(!CI
.isByRef());
1590 // don't bother computing flags
1591 return std::make_pair(BlockCaptureEntityKind::CXXRecord
, BlockFieldFlags());
1593 BlockFieldFlags Flags
;
1594 if (CI
.isEscapingByref()) {
1595 Flags
= BLOCK_FIELD_IS_BYREF
;
1596 if (T
.isObjCGCWeak())
1597 Flags
|= BLOCK_FIELD_IS_WEAK
;
1598 return std::make_pair(BlockCaptureEntityKind::BlockObject
, Flags
);
1601 Flags
= BLOCK_FIELD_IS_OBJECT
;
1602 bool isBlockPointer
= T
->isBlockPointerType();
1604 Flags
= BLOCK_FIELD_IS_BLOCK
;
1606 switch (T
.isNonTrivialToPrimitiveCopy()) {
1607 case QualType::PCK_Struct
:
1608 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct
,
1610 case QualType::PCK_ARCWeak
:
1611 // We need to register __weak direct captures with the runtime.
1612 return std::make_pair(BlockCaptureEntityKind::ARCWeak
, Flags
);
1613 case QualType::PCK_ARCStrong
:
1614 // We need to retain the copied value for __strong direct captures.
1615 // If it's a block pointer, we have to copy the block and assign that to
1616 // the destination pointer, so we might as well use _Block_object_assign.
1617 // Otherwise we can avoid that.
1618 return std::make_pair(!isBlockPointer
? BlockCaptureEntityKind::ARCStrong
1619 : BlockCaptureEntityKind::BlockObject
,
1621 case QualType::PCK_Trivial
:
1622 case QualType::PCK_VolatileTrivial
: {
1623 if (!T
->isObjCRetainableType())
1624 // For all other types, the memcpy is fine.
1625 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
1627 // Honor the inert __unsafe_unretained qualifier, which doesn't actually
1628 // make it into the type system.
1629 if (T
->isObjCInertUnsafeUnretainedType())
1630 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
1632 // Special rules for ARC captures:
1633 Qualifiers QS
= T
.getQualifiers();
1635 // Non-ARC captures of retainable pointers are strong and
1636 // therefore require a call to _Block_object_assign.
1637 if (!QS
.getObjCLifetime() && !LangOpts
.ObjCAutoRefCount
)
1638 return std::make_pair(BlockCaptureEntityKind::BlockObject
, Flags
);
1640 // Otherwise the memcpy is fine.
1641 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
1644 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1648 /// Release a __block variable.
1649 struct CallBlockRelease final
: EHScopeStack::Cleanup
{
1651 BlockFieldFlags FieldFlags
;
1652 bool LoadBlockVarAddr
, CanThrow
;
1654 CallBlockRelease(Address Addr
, BlockFieldFlags Flags
, bool LoadValue
,
1656 : Addr(Addr
), FieldFlags(Flags
), LoadBlockVarAddr(LoadValue
),
1659 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1660 llvm::Value
*BlockVarAddr
;
1661 if (LoadBlockVarAddr
) {
1662 BlockVarAddr
= CGF
.Builder
.CreateLoad(Addr
);
1664 BlockVarAddr
= Addr
.getPointer();
1667 CGF
.BuildBlockRelease(BlockVarAddr
, FieldFlags
, CanThrow
);
1670 } // end anonymous namespace
1672 /// Check if \p T is a C++ class that has a destructor that can throw.
1673 bool CodeGenFunction::cxxDestructorCanThrow(QualType T
) {
1674 if (const auto *RD
= T
->getAsCXXRecordDecl())
1675 if (const CXXDestructorDecl
*DD
= RD
->getDestructor())
1676 return DD
->getType()->castAs
<FunctionProtoType
>()->canThrow();
1680 // Return a string that has the information about a capture.
1681 static std::string
getBlockCaptureStr(const CGBlockInfo::Capture
&Cap
,
1682 CaptureStrKind StrKind
,
1683 CharUnits BlockAlignment
,
1684 CodeGenModule
&CGM
) {
1686 ASTContext
&Ctx
= CGM
.getContext();
1687 const BlockDecl::Capture
&CI
= *Cap
.Cap
;
1688 QualType CaptureTy
= CI
.getVariable()->getType();
1690 BlockCaptureEntityKind Kind
;
1691 BlockFieldFlags Flags
;
1693 // CaptureStrKind::Merged should be passed only when the operations and the
1694 // flags are the same for copy and dispose.
1695 assert((StrKind
!= CaptureStrKind::Merged
||
1696 (Cap
.CopyKind
== Cap
.DisposeKind
&&
1697 Cap
.CopyFlags
== Cap
.DisposeFlags
)) &&
1698 "different operations and flags");
1700 if (StrKind
== CaptureStrKind::DisposeHelper
) {
1701 Kind
= Cap
.DisposeKind
;
1702 Flags
= Cap
.DisposeFlags
;
1704 Kind
= Cap
.CopyKind
;
1705 Flags
= Cap
.CopyFlags
;
1709 case BlockCaptureEntityKind::CXXRecord
: {
1711 SmallString
<256> TyStr
;
1712 llvm::raw_svector_ostream
Out(TyStr
);
1713 CGM
.getCXXABI().getMangleContext().mangleCanonicalTypeName(CaptureTy
, Out
);
1714 Str
+= llvm::to_string(TyStr
.size()) + TyStr
.c_str();
1717 case BlockCaptureEntityKind::ARCWeak
:
1720 case BlockCaptureEntityKind::ARCStrong
:
1723 case BlockCaptureEntityKind::BlockObject
: {
1724 const VarDecl
*Var
= CI
.getVariable();
1725 unsigned F
= Flags
.getBitMask();
1726 if (F
& BLOCK_FIELD_IS_BYREF
) {
1728 if (F
& BLOCK_FIELD_IS_WEAK
)
1731 // If CaptureStrKind::Merged is passed, check both the copy expression
1732 // and the destructor.
1733 if (StrKind
!= CaptureStrKind::DisposeHelper
) {
1734 if (Ctx
.getBlockVarCopyInit(Var
).canThrow())
1737 if (StrKind
!= CaptureStrKind::CopyHelper
) {
1738 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy
))
1743 assert((F
& BLOCK_FIELD_IS_OBJECT
) && "unexpected flag value");
1744 if (F
== BLOCK_FIELD_IS_BLOCK
)
1751 case BlockCaptureEntityKind::NonTrivialCStruct
: {
1752 bool IsVolatile
= CaptureTy
.isVolatileQualified();
1753 CharUnits Alignment
= BlockAlignment
.alignmentAtOffset(Cap
.getOffset());
1756 std::string FuncStr
;
1757 if (StrKind
== CaptureStrKind::DisposeHelper
)
1758 FuncStr
= CodeGenFunction::getNonTrivialDestructorStr(
1759 CaptureTy
, Alignment
, IsVolatile
, Ctx
);
1761 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1762 // It has all the information that the destructor string has.
1763 FuncStr
= CodeGenFunction::getNonTrivialCopyConstructorStr(
1764 CaptureTy
, Alignment
, IsVolatile
, Ctx
);
1765 // The underscore is necessary here because non-trivial copy constructor
1766 // and destructor strings can start with a number.
1767 Str
+= llvm::to_string(FuncStr
.size()) + "_" + FuncStr
;
1770 case BlockCaptureEntityKind::None
:
1777 static std::string
getCopyDestroyHelperFuncName(
1778 const SmallVectorImpl
<CGBlockInfo::Capture
> &Captures
,
1779 CharUnits BlockAlignment
, CaptureStrKind StrKind
, CodeGenModule
&CGM
) {
1780 assert((StrKind
== CaptureStrKind::CopyHelper
||
1781 StrKind
== CaptureStrKind::DisposeHelper
) &&
1782 "unexpected CaptureStrKind");
1783 std::string Name
= StrKind
== CaptureStrKind::CopyHelper
1784 ? "__copy_helper_block_"
1785 : "__destroy_helper_block_";
1786 if (CGM
.getLangOpts().Exceptions
)
1788 if (CGM
.getCodeGenOpts().ObjCAutoRefCountExceptions
)
1790 Name
+= llvm::to_string(BlockAlignment
.getQuantity()) + "_";
1792 for (auto &Cap
: Captures
) {
1793 if (Cap
.isConstantOrTrivial())
1795 Name
+= llvm::to_string(Cap
.getOffset().getQuantity());
1796 Name
+= getBlockCaptureStr(Cap
, StrKind
, BlockAlignment
, CGM
);
1802 static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind
,
1803 Address Field
, QualType CaptureType
,
1804 BlockFieldFlags Flags
, bool ForCopyHelper
,
1805 VarDecl
*Var
, CodeGenFunction
&CGF
) {
1806 bool EHOnly
= ForCopyHelper
;
1808 switch (CaptureKind
) {
1809 case BlockCaptureEntityKind::CXXRecord
:
1810 case BlockCaptureEntityKind::ARCWeak
:
1811 case BlockCaptureEntityKind::NonTrivialCStruct
:
1812 case BlockCaptureEntityKind::ARCStrong
: {
1813 if (CaptureType
.isDestructedType() &&
1814 (!EHOnly
|| CGF
.needsEHCleanup(CaptureType
.isDestructedType()))) {
1815 CodeGenFunction::Destroyer
*Destroyer
=
1816 CaptureKind
== BlockCaptureEntityKind::ARCStrong
1817 ? CodeGenFunction::destroyARCStrongImprecise
1818 : CGF
.getDestroyer(CaptureType
.isDestructedType());
1821 : CGF
.getCleanupKind(CaptureType
.isDestructedType());
1822 CGF
.pushDestroy(Kind
, Field
, CaptureType
, Destroyer
, Kind
& EHCleanup
);
1826 case BlockCaptureEntityKind::BlockObject
: {
1827 if (!EHOnly
|| CGF
.getLangOpts().Exceptions
) {
1828 CleanupKind Kind
= EHOnly
? EHCleanup
: NormalAndEHCleanup
;
1829 // Calls to _Block_object_dispose along the EH path in the copy helper
1830 // function don't throw as newly-copied __block variables always have a
1831 // reference count of 2.
1833 !ForCopyHelper
&& CGF
.cxxDestructorCanThrow(CaptureType
);
1834 CGF
.enterByrefCleanup(Kind
, Field
, Flags
, /*LoadBlockVarAddr*/ true,
1839 case BlockCaptureEntityKind::None
:
1844 static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType
,
1846 const CGFunctionInfo
&FI
,
1847 CodeGenModule
&CGM
) {
1848 if (CapturesNonExternalType
) {
1849 CGM
.SetInternalFunctionAttributes(GlobalDecl(), Fn
, FI
);
1851 Fn
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1852 Fn
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
1853 CGM
.SetLLVMFunctionAttributes(GlobalDecl(), FI
, Fn
, /*IsThunk=*/false);
1854 CGM
.SetLLVMFunctionAttributesForDefinition(nullptr, Fn
);
1857 /// Generate the copy-helper function for a block closure object:
1858 /// static void block_copy_helper(block_t *dst, block_t *src);
1859 /// The runtime will have previously initialized 'dst' by doing a
1860 /// bit-copy of 'src'.
1862 /// Note that this copies an entire block closure object to the heap;
1863 /// it should not be confused with a 'byref copy helper', which moves
1864 /// the contents of an individual __block variable to the heap.
1866 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo
&blockInfo
) {
1867 std::string FuncName
= getCopyDestroyHelperFuncName(
1868 blockInfo
.SortedCaptures
, blockInfo
.BlockAlign
,
1869 CaptureStrKind::CopyHelper
, CGM
);
1871 if (llvm::GlobalValue
*Func
= CGM
.getModule().getNamedValue(FuncName
))
1872 return llvm::ConstantExpr::getBitCast(Func
, VoidPtrTy
);
1874 ASTContext
&C
= getContext();
1876 QualType ReturnTy
= C
.VoidTy
;
1878 FunctionArgList args
;
1879 ImplicitParamDecl
DstDecl(C
, C
.VoidPtrTy
, ImplicitParamDecl::Other
);
1880 args
.push_back(&DstDecl
);
1881 ImplicitParamDecl
SrcDecl(C
, C
.VoidPtrTy
, ImplicitParamDecl::Other
);
1882 args
.push_back(&SrcDecl
);
1884 const CGFunctionInfo
&FI
=
1885 CGM
.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy
, args
);
1887 // FIXME: it would be nice if these were mergeable with things with
1888 // identical semantics.
1889 llvm::FunctionType
*LTy
= CGM
.getTypes().GetFunctionType(FI
);
1891 llvm::Function
*Fn
=
1892 llvm::Function::Create(LTy
, llvm::GlobalValue::LinkOnceODRLinkage
,
1893 FuncName
, &CGM
.getModule());
1894 if (CGM
.supportsCOMDAT())
1895 Fn
->setComdat(CGM
.getModule().getOrInsertComdat(FuncName
));
1897 SmallVector
<QualType
, 2> ArgTys
;
1898 ArgTys
.push_back(C
.VoidPtrTy
);
1899 ArgTys
.push_back(C
.VoidPtrTy
);
1901 setBlockHelperAttributesVisibility(blockInfo
.CapturesNonExternalType
, Fn
, FI
,
1903 StartFunction(GlobalDecl(), ReturnTy
, Fn
, FI
, args
);
1904 auto AL
= ApplyDebugLocation::CreateArtificial(*this);
1906 Address src
= GetAddrOfLocalVar(&SrcDecl
);
1907 src
= Address(Builder
.CreateLoad(src
), blockInfo
.StructureType
,
1908 blockInfo
.BlockAlign
);
1910 Address dst
= GetAddrOfLocalVar(&DstDecl
);
1911 dst
= Address(Builder
.CreateLoad(dst
), blockInfo
.StructureType
,
1912 blockInfo
.BlockAlign
);
1914 for (auto &capture
: blockInfo
.SortedCaptures
) {
1915 if (capture
.isConstantOrTrivial())
1918 const BlockDecl::Capture
&CI
= *capture
.Cap
;
1919 QualType captureType
= CI
.getVariable()->getType();
1920 BlockFieldFlags flags
= capture
.CopyFlags
;
1922 unsigned index
= capture
.getIndex();
1923 Address srcField
= Builder
.CreateStructGEP(src
, index
);
1924 Address dstField
= Builder
.CreateStructGEP(dst
, index
);
1926 switch (capture
.CopyKind
) {
1927 case BlockCaptureEntityKind::CXXRecord
:
1928 // If there's an explicit copy expression, we do that.
1929 assert(CI
.getCopyExpr() && "copy expression for variable is missing");
1930 EmitSynthesizedCXXCopyCtor(dstField
, srcField
, CI
.getCopyExpr());
1932 case BlockCaptureEntityKind::ARCWeak
:
1933 EmitARCCopyWeak(dstField
, srcField
);
1935 case BlockCaptureEntityKind::NonTrivialCStruct
: {
1936 // If this is a C struct that requires non-trivial copy construction,
1937 // emit a call to its copy constructor.
1938 QualType varType
= CI
.getVariable()->getType();
1939 callCStructCopyConstructor(MakeAddrLValue(dstField
, varType
),
1940 MakeAddrLValue(srcField
, varType
));
1943 case BlockCaptureEntityKind::ARCStrong
: {
1944 llvm::Value
*srcValue
= Builder
.CreateLoad(srcField
, "blockcopy.src");
1945 // At -O0, store null into the destination field (so that the
1946 // storeStrong doesn't over-release) and then call storeStrong.
1947 // This is a workaround to not having an initStrong call.
1948 if (CGM
.getCodeGenOpts().OptimizationLevel
== 0) {
1949 auto *ty
= cast
<llvm::PointerType
>(srcValue
->getType());
1950 llvm::Value
*null
= llvm::ConstantPointerNull::get(ty
);
1951 Builder
.CreateStore(null
, dstField
);
1952 EmitARCStoreStrongCall(dstField
, srcValue
, true);
1954 // With optimization enabled, take advantage of the fact that
1955 // the blocks runtime guarantees a memcpy of the block data, and
1956 // just emit a retain of the src field.
1958 EmitARCRetainNonBlock(srcValue
);
1960 // Unless EH cleanup is required, we don't need this anymore, so kill
1961 // it. It's not quite worth the annoyance to avoid creating it in the
1963 if (!needsEHCleanup(captureType
.isDestructedType()))
1964 cast
<llvm::Instruction
>(dstField
.getPointer())->eraseFromParent();
1968 case BlockCaptureEntityKind::BlockObject
: {
1969 llvm::Value
*srcValue
= Builder
.CreateLoad(srcField
, "blockcopy.src");
1970 llvm::Value
*dstAddr
= dstField
.getPointer();
1971 llvm::Value
*args
[] = {
1972 dstAddr
, srcValue
, llvm::ConstantInt::get(Int32Ty
, flags
.getBitMask())
1975 if (CI
.isByRef() && C
.getBlockVarCopyInit(CI
.getVariable()).canThrow())
1976 EmitRuntimeCallOrInvoke(CGM
.getBlockObjectAssign(), args
);
1978 EmitNounwindRuntimeCall(CGM
.getBlockObjectAssign(), args
);
1981 case BlockCaptureEntityKind::None
:
1985 // Ensure that we destroy the copied object if an exception is thrown later
1986 // in the helper function.
1987 pushCaptureCleanup(capture
.CopyKind
, dstField
, captureType
, flags
,
1988 /*ForCopyHelper*/ true, CI
.getVariable(), *this);
1993 return llvm::ConstantExpr::getBitCast(Fn
, VoidPtrTy
);
1996 static BlockFieldFlags
1997 getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture
&CI
,
1999 BlockFieldFlags Flags
= BLOCK_FIELD_IS_OBJECT
;
2000 if (T
->isBlockPointerType())
2001 Flags
= BLOCK_FIELD_IS_BLOCK
;
2005 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
2006 computeDestroyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
2007 const LangOptions
&LangOpts
) {
2008 if (CI
.isEscapingByref()) {
2009 BlockFieldFlags Flags
= BLOCK_FIELD_IS_BYREF
;
2010 if (T
.isObjCGCWeak())
2011 Flags
|= BLOCK_FIELD_IS_WEAK
;
2012 return std::make_pair(BlockCaptureEntityKind::BlockObject
, Flags
);
2015 switch (T
.isDestructedType()) {
2016 case QualType::DK_cxx_destructor
:
2017 return std::make_pair(BlockCaptureEntityKind::CXXRecord
, BlockFieldFlags());
2018 case QualType::DK_objc_strong_lifetime
:
2019 // Use objc_storeStrong for __strong direct captures; the
2020 // dynamic tools really like it when we do this.
2021 return std::make_pair(BlockCaptureEntityKind::ARCStrong
,
2022 getBlockFieldFlagsForObjCObjectPointer(CI
, T
));
2023 case QualType::DK_objc_weak_lifetime
:
2024 // Support __weak direct captures.
2025 return std::make_pair(BlockCaptureEntityKind::ARCWeak
,
2026 getBlockFieldFlagsForObjCObjectPointer(CI
, T
));
2027 case QualType::DK_nontrivial_c_struct
:
2028 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct
,
2030 case QualType::DK_none
: {
2031 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2032 // But honor the inert __unsafe_unretained qualifier, which doesn't actually
2033 // make it into the type system.
2034 if (T
->isObjCRetainableType() && !T
.getQualifiers().hasObjCLifetime() &&
2035 !LangOpts
.ObjCAutoRefCount
&& !T
->isObjCInertUnsafeUnretainedType())
2036 return std::make_pair(BlockCaptureEntityKind::BlockObject
,
2037 getBlockFieldFlagsForObjCObjectPointer(CI
, T
));
2038 // Otherwise, we have nothing to do.
2039 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
2042 llvm_unreachable("after exhaustive DestructionKind switch");
2045 /// Generate the destroy-helper function for a block closure object:
2046 /// static void block_destroy_helper(block_t *theBlock);
2048 /// Note that this destroys a heap-allocated block closure object;
2049 /// it should not be confused with a 'byref destroy helper', which
2050 /// destroys the heap-allocated contents of an individual __block
2053 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo
&blockInfo
) {
2054 std::string FuncName
= getCopyDestroyHelperFuncName(
2055 blockInfo
.SortedCaptures
, blockInfo
.BlockAlign
,
2056 CaptureStrKind::DisposeHelper
, CGM
);
2058 if (llvm::GlobalValue
*Func
= CGM
.getModule().getNamedValue(FuncName
))
2059 return llvm::ConstantExpr::getBitCast(Func
, VoidPtrTy
);
2061 ASTContext
&C
= getContext();
2063 QualType ReturnTy
= C
.VoidTy
;
2065 FunctionArgList args
;
2066 ImplicitParamDecl
SrcDecl(C
, C
.VoidPtrTy
, ImplicitParamDecl::Other
);
2067 args
.push_back(&SrcDecl
);
2069 const CGFunctionInfo
&FI
=
2070 CGM
.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy
, args
);
2072 // FIXME: We'd like to put these into a mergable by content, with
2073 // internal linkage.
2074 llvm::FunctionType
*LTy
= CGM
.getTypes().GetFunctionType(FI
);
2076 llvm::Function
*Fn
=
2077 llvm::Function::Create(LTy
, llvm::GlobalValue::LinkOnceODRLinkage
,
2078 FuncName
, &CGM
.getModule());
2079 if (CGM
.supportsCOMDAT())
2080 Fn
->setComdat(CGM
.getModule().getOrInsertComdat(FuncName
));
2082 SmallVector
<QualType
, 1> ArgTys
;
2083 ArgTys
.push_back(C
.VoidPtrTy
);
2085 setBlockHelperAttributesVisibility(blockInfo
.CapturesNonExternalType
, Fn
, FI
,
2087 StartFunction(GlobalDecl(), ReturnTy
, Fn
, FI
, args
);
2088 markAsIgnoreThreadCheckingAtRuntime(Fn
);
2090 auto AL
= ApplyDebugLocation::CreateArtificial(*this);
2092 Address src
= GetAddrOfLocalVar(&SrcDecl
);
2093 src
= Address(Builder
.CreateLoad(src
), blockInfo
.StructureType
,
2094 blockInfo
.BlockAlign
);
2096 CodeGenFunction::RunCleanupsScope
cleanups(*this);
2098 for (auto &capture
: blockInfo
.SortedCaptures
) {
2099 if (capture
.isConstantOrTrivial())
2102 const BlockDecl::Capture
&CI
= *capture
.Cap
;
2103 BlockFieldFlags flags
= capture
.DisposeFlags
;
2105 Address srcField
= Builder
.CreateStructGEP(src
, capture
.getIndex());
2107 pushCaptureCleanup(capture
.DisposeKind
, srcField
,
2108 CI
.getVariable()->getType(), flags
,
2109 /*ForCopyHelper*/ false, CI
.getVariable(), *this);
2112 cleanups
.ForceCleanup();
2116 return llvm::ConstantExpr::getBitCast(Fn
, VoidPtrTy
);
2121 /// Emits the copy/dispose helper functions for a __block object of id type.
2122 class ObjectByrefHelpers final
: public BlockByrefHelpers
{
2123 BlockFieldFlags Flags
;
2126 ObjectByrefHelpers(CharUnits alignment
, BlockFieldFlags flags
)
2127 : BlockByrefHelpers(alignment
), Flags(flags
) {}
2129 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2130 Address srcField
) override
{
2131 destField
= destField
.withElementType(CGF
.Int8Ty
);
2133 srcField
= srcField
.withElementType(CGF
.Int8PtrTy
);
2134 llvm::Value
*srcValue
= CGF
.Builder
.CreateLoad(srcField
);
2136 unsigned flags
= (Flags
| BLOCK_BYREF_CALLER
).getBitMask();
2138 llvm::Value
*flagsVal
= llvm::ConstantInt::get(CGF
.Int32Ty
, flags
);
2139 llvm::FunctionCallee fn
= CGF
.CGM
.getBlockObjectAssign();
2141 llvm::Value
*args
[] = { destField
.getPointer(), srcValue
, flagsVal
};
2142 CGF
.EmitNounwindRuntimeCall(fn
, args
);
2145 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2146 field
= field
.withElementType(CGF
.Int8PtrTy
);
2147 llvm::Value
*value
= CGF
.Builder
.CreateLoad(field
);
2149 CGF
.BuildBlockRelease(value
, Flags
| BLOCK_BYREF_CALLER
, false);
2152 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2153 id
.AddInteger(Flags
.getBitMask());
2157 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2158 class ARCWeakByrefHelpers final
: public BlockByrefHelpers
{
2160 ARCWeakByrefHelpers(CharUnits alignment
) : BlockByrefHelpers(alignment
) {}
2162 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2163 Address srcField
) override
{
2164 CGF
.EmitARCMoveWeak(destField
, srcField
);
2167 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2168 CGF
.EmitARCDestroyWeak(field
);
2171 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2172 // 0 is distinguishable from all pointers and byref flags
2177 /// Emits the copy/dispose helpers for an ARC __block __strong variable
2178 /// that's not of block-pointer type.
2179 class ARCStrongByrefHelpers final
: public BlockByrefHelpers
{
2181 ARCStrongByrefHelpers(CharUnits alignment
) : BlockByrefHelpers(alignment
) {}
2183 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2184 Address srcField
) override
{
2185 // Do a "move" by copying the value and then zeroing out the old
2188 llvm::Value
*value
= CGF
.Builder
.CreateLoad(srcField
);
2191 llvm::ConstantPointerNull::get(cast
<llvm::PointerType
>(value
->getType()));
2193 if (CGF
.CGM
.getCodeGenOpts().OptimizationLevel
== 0) {
2194 CGF
.Builder
.CreateStore(null
, destField
);
2195 CGF
.EmitARCStoreStrongCall(destField
, value
, /*ignored*/ true);
2196 CGF
.EmitARCStoreStrongCall(srcField
, null
, /*ignored*/ true);
2199 CGF
.Builder
.CreateStore(value
, destField
);
2200 CGF
.Builder
.CreateStore(null
, srcField
);
2203 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2204 CGF
.EmitARCDestroyStrong(field
, ARCImpreciseLifetime
);
2207 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2208 // 1 is distinguishable from all pointers and byref flags
2213 /// Emits the copy/dispose helpers for an ARC __block __strong
2214 /// variable that's of block-pointer type.
2215 class ARCStrongBlockByrefHelpers final
: public BlockByrefHelpers
{
2217 ARCStrongBlockByrefHelpers(CharUnits alignment
)
2218 : BlockByrefHelpers(alignment
) {}
2220 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2221 Address srcField
) override
{
2222 // Do the copy with objc_retainBlock; that's all that
2223 // _Block_object_assign would do anyway, and we'd have to pass the
2224 // right arguments to make sure it doesn't get no-op'ed.
2225 llvm::Value
*oldValue
= CGF
.Builder
.CreateLoad(srcField
);
2226 llvm::Value
*copy
= CGF
.EmitARCRetainBlock(oldValue
, /*mandatory*/ true);
2227 CGF
.Builder
.CreateStore(copy
, destField
);
2230 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2231 CGF
.EmitARCDestroyStrong(field
, ARCImpreciseLifetime
);
2234 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2235 // 2 is distinguishable from all pointers and byref flags
2240 /// Emits the copy/dispose helpers for a __block variable with a
2241 /// nontrivial copy constructor or destructor.
2242 class CXXByrefHelpers final
: public BlockByrefHelpers
{
2244 const Expr
*CopyExpr
;
2247 CXXByrefHelpers(CharUnits alignment
, QualType type
,
2248 const Expr
*copyExpr
)
2249 : BlockByrefHelpers(alignment
), VarType(type
), CopyExpr(copyExpr
) {}
2251 bool needsCopy() const override
{ return CopyExpr
!= nullptr; }
2252 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2253 Address srcField
) override
{
2254 if (!CopyExpr
) return;
2255 CGF
.EmitSynthesizedCXXCopyCtor(destField
, srcField
, CopyExpr
);
2258 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2259 EHScopeStack::stable_iterator cleanupDepth
= CGF
.EHStack
.stable_begin();
2260 CGF
.PushDestructorCleanup(VarType
, field
);
2261 CGF
.PopCleanupBlocks(cleanupDepth
);
2264 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2265 id
.AddPointer(VarType
.getCanonicalType().getAsOpaquePtr());
2269 /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2271 class NonTrivialCStructByrefHelpers final
: public BlockByrefHelpers
{
2275 NonTrivialCStructByrefHelpers(CharUnits alignment
, QualType type
)
2276 : BlockByrefHelpers(alignment
), VarType(type
) {}
2278 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2279 Address srcField
) override
{
2280 CGF
.callCStructMoveConstructor(CGF
.MakeAddrLValue(destField
, VarType
),
2281 CGF
.MakeAddrLValue(srcField
, VarType
));
2284 bool needsDispose() const override
{
2285 return VarType
.isDestructedType();
2288 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2289 EHScopeStack::stable_iterator cleanupDepth
= CGF
.EHStack
.stable_begin();
2290 CGF
.pushDestroy(VarType
.isDestructedType(), field
, VarType
);
2291 CGF
.PopCleanupBlocks(cleanupDepth
);
2294 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2295 id
.AddPointer(VarType
.getCanonicalType().getAsOpaquePtr());
2298 } // end anonymous namespace
2300 static llvm::Constant
*
2301 generateByrefCopyHelper(CodeGenFunction
&CGF
, const BlockByrefInfo
&byrefInfo
,
2302 BlockByrefHelpers
&generator
) {
2303 ASTContext
&Context
= CGF
.getContext();
2305 QualType ReturnTy
= Context
.VoidTy
;
2307 FunctionArgList args
;
2308 ImplicitParamDecl
Dst(Context
, Context
.VoidPtrTy
, ImplicitParamDecl::Other
);
2309 args
.push_back(&Dst
);
2311 ImplicitParamDecl
Src(Context
, Context
.VoidPtrTy
, ImplicitParamDecl::Other
);
2312 args
.push_back(&Src
);
2314 const CGFunctionInfo
&FI
=
2315 CGF
.CGM
.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy
, args
);
2317 llvm::FunctionType
*LTy
= CGF
.CGM
.getTypes().GetFunctionType(FI
);
2319 // FIXME: We'd like to put these into a mergable by content, with
2320 // internal linkage.
2321 llvm::Function
*Fn
=
2322 llvm::Function::Create(LTy
, llvm::GlobalValue::InternalLinkage
,
2323 "__Block_byref_object_copy_", &CGF
.CGM
.getModule());
2325 SmallVector
<QualType
, 2> ArgTys
;
2326 ArgTys
.push_back(Context
.VoidPtrTy
);
2327 ArgTys
.push_back(Context
.VoidPtrTy
);
2329 CGF
.CGM
.SetInternalFunctionAttributes(GlobalDecl(), Fn
, FI
);
2331 CGF
.StartFunction(GlobalDecl(), ReturnTy
, Fn
, FI
, args
);
2332 // Create a scope with an artificial location for the body of this function.
2333 auto AL
= ApplyDebugLocation::CreateArtificial(CGF
);
2335 if (generator
.needsCopy()) {
2337 Address destField
= CGF
.GetAddrOfLocalVar(&Dst
);
2338 destField
= Address(CGF
.Builder
.CreateLoad(destField
), byrefInfo
.Type
,
2339 byrefInfo
.ByrefAlignment
);
2341 CGF
.emitBlockByrefAddress(destField
, byrefInfo
, false, "dest-object");
2344 Address srcField
= CGF
.GetAddrOfLocalVar(&Src
);
2345 srcField
= Address(CGF
.Builder
.CreateLoad(srcField
), byrefInfo
.Type
,
2346 byrefInfo
.ByrefAlignment
);
2348 CGF
.emitBlockByrefAddress(srcField
, byrefInfo
, false, "src-object");
2350 generator
.emitCopy(CGF
, destField
, srcField
);
2353 CGF
.FinishFunction();
2355 return llvm::ConstantExpr::getBitCast(Fn
, CGF
.Int8PtrTy
);
2358 /// Build the copy helper for a __block variable.
2359 static llvm::Constant
*buildByrefCopyHelper(CodeGenModule
&CGM
,
2360 const BlockByrefInfo
&byrefInfo
,
2361 BlockByrefHelpers
&generator
) {
2362 CodeGenFunction
CGF(CGM
);
2363 return generateByrefCopyHelper(CGF
, byrefInfo
, generator
);
2366 /// Generate code for a __block variable's dispose helper.
2367 static llvm::Constant
*
2368 generateByrefDisposeHelper(CodeGenFunction
&CGF
,
2369 const BlockByrefInfo
&byrefInfo
,
2370 BlockByrefHelpers
&generator
) {
2371 ASTContext
&Context
= CGF
.getContext();
2372 QualType R
= Context
.VoidTy
;
2374 FunctionArgList args
;
2375 ImplicitParamDecl
Src(CGF
.getContext(), Context
.VoidPtrTy
,
2376 ImplicitParamDecl::Other
);
2377 args
.push_back(&Src
);
2379 const CGFunctionInfo
&FI
=
2380 CGF
.CGM
.getTypes().arrangeBuiltinFunctionDeclaration(R
, args
);
2382 llvm::FunctionType
*LTy
= CGF
.CGM
.getTypes().GetFunctionType(FI
);
2384 // FIXME: We'd like to put these into a mergable by content, with
2385 // internal linkage.
2386 llvm::Function
*Fn
=
2387 llvm::Function::Create(LTy
, llvm::GlobalValue::InternalLinkage
,
2388 "__Block_byref_object_dispose_",
2389 &CGF
.CGM
.getModule());
2391 SmallVector
<QualType
, 1> ArgTys
;
2392 ArgTys
.push_back(Context
.VoidPtrTy
);
2394 CGF
.CGM
.SetInternalFunctionAttributes(GlobalDecl(), Fn
, FI
);
2396 CGF
.StartFunction(GlobalDecl(), R
, Fn
, FI
, args
);
2397 // Create a scope with an artificial location for the body of this function.
2398 auto AL
= ApplyDebugLocation::CreateArtificial(CGF
);
2400 if (generator
.needsDispose()) {
2401 Address addr
= CGF
.GetAddrOfLocalVar(&Src
);
2402 addr
= Address(CGF
.Builder
.CreateLoad(addr
), byrefInfo
.Type
,
2403 byrefInfo
.ByrefAlignment
);
2404 addr
= CGF
.emitBlockByrefAddress(addr
, byrefInfo
, false, "object");
2406 generator
.emitDispose(CGF
, addr
);
2409 CGF
.FinishFunction();
2411 return llvm::ConstantExpr::getBitCast(Fn
, CGF
.Int8PtrTy
);
2414 /// Build the dispose helper for a __block variable.
2415 static llvm::Constant
*buildByrefDisposeHelper(CodeGenModule
&CGM
,
2416 const BlockByrefInfo
&byrefInfo
,
2417 BlockByrefHelpers
&generator
) {
2418 CodeGenFunction
CGF(CGM
);
2419 return generateByrefDisposeHelper(CGF
, byrefInfo
, generator
);
2422 /// Lazily build the copy and dispose helpers for a __block variable
2423 /// with the given information.
2425 static T
*buildByrefHelpers(CodeGenModule
&CGM
, const BlockByrefInfo
&byrefInfo
,
2427 llvm::FoldingSetNodeID id
;
2428 generator
.Profile(id
);
2431 BlockByrefHelpers
*node
2432 = CGM
.ByrefHelpersCache
.FindNodeOrInsertPos(id
, insertPos
);
2433 if (node
) return static_cast<T
*>(node
);
2435 generator
.CopyHelper
= buildByrefCopyHelper(CGM
, byrefInfo
, generator
);
2436 generator
.DisposeHelper
= buildByrefDisposeHelper(CGM
, byrefInfo
, generator
);
2438 T
*copy
= new (CGM
.getContext()) T(std::forward
<T
>(generator
));
2439 CGM
.ByrefHelpersCache
.InsertNode(copy
, insertPos
);
2443 /// Build the copy and dispose helpers for the given __block variable
2444 /// emission. Places the helpers in the global cache. Returns null
2445 /// if no helpers are required.
2447 CodeGenFunction::buildByrefHelpers(llvm::StructType
&byrefType
,
2448 const AutoVarEmission
&emission
) {
2449 const VarDecl
&var
= *emission
.Variable
;
2450 assert(var
.isEscapingByref() &&
2451 "only escaping __block variables need byref helpers");
2453 QualType type
= var
.getType();
2455 auto &byrefInfo
= getBlockByrefInfo(&var
);
2457 // The alignment we care about for the purposes of uniquing byref
2458 // helpers is the alignment of the actual byref value field.
2459 CharUnits valueAlignment
=
2460 byrefInfo
.ByrefAlignment
.alignmentAtOffset(byrefInfo
.FieldOffset
);
2462 if (const CXXRecordDecl
*record
= type
->getAsCXXRecordDecl()) {
2463 const Expr
*copyExpr
=
2464 CGM
.getContext().getBlockVarCopyInit(&var
).getCopyExpr();
2465 if (!copyExpr
&& record
->hasTrivialDestructor()) return nullptr;
2467 return ::buildByrefHelpers(
2468 CGM
, byrefInfo
, CXXByrefHelpers(valueAlignment
, type
, copyExpr
));
2471 // If type is a non-trivial C struct type that is non-trivial to
2472 // destructly move or destroy, build the copy and dispose helpers.
2473 if (type
.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct
||
2474 type
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
2475 return ::buildByrefHelpers(
2476 CGM
, byrefInfo
, NonTrivialCStructByrefHelpers(valueAlignment
, type
));
2478 // Otherwise, if we don't have a retainable type, there's nothing to do.
2479 // that the runtime does extra copies.
2480 if (!type
->isObjCRetainableType()) return nullptr;
2482 Qualifiers qs
= type
.getQualifiers();
2484 // If we have lifetime, that dominates.
2485 if (Qualifiers::ObjCLifetime lifetime
= qs
.getObjCLifetime()) {
2487 case Qualifiers::OCL_None
: llvm_unreachable("impossible");
2489 // These are just bits as far as the runtime is concerned.
2490 case Qualifiers::OCL_ExplicitNone
:
2491 case Qualifiers::OCL_Autoreleasing
:
2494 // Tell the runtime that this is ARC __weak, called by the
2496 case Qualifiers::OCL_Weak
:
2497 return ::buildByrefHelpers(CGM
, byrefInfo
,
2498 ARCWeakByrefHelpers(valueAlignment
));
2500 // ARC __strong __block variables need to be retained.
2501 case Qualifiers::OCL_Strong
:
2502 // Block pointers need to be copied, and there's no direct
2503 // transfer possible.
2504 if (type
->isBlockPointerType()) {
2505 return ::buildByrefHelpers(CGM
, byrefInfo
,
2506 ARCStrongBlockByrefHelpers(valueAlignment
));
2508 // Otherwise, we transfer ownership of the retain from the stack
2511 return ::buildByrefHelpers(CGM
, byrefInfo
,
2512 ARCStrongByrefHelpers(valueAlignment
));
2515 llvm_unreachable("fell out of lifetime switch!");
2518 BlockFieldFlags flags
;
2519 if (type
->isBlockPointerType()) {
2520 flags
|= BLOCK_FIELD_IS_BLOCK
;
2521 } else if (CGM
.getContext().isObjCNSObjectType(type
) ||
2522 type
->isObjCObjectPointerType()) {
2523 flags
|= BLOCK_FIELD_IS_OBJECT
;
2528 if (type
.isObjCGCWeak())
2529 flags
|= BLOCK_FIELD_IS_WEAK
;
2531 return ::buildByrefHelpers(CGM
, byrefInfo
,
2532 ObjectByrefHelpers(valueAlignment
, flags
));
2535 Address
CodeGenFunction::emitBlockByrefAddress(Address baseAddr
,
2537 bool followForward
) {
2538 auto &info
= getBlockByrefInfo(var
);
2539 return emitBlockByrefAddress(baseAddr
, info
, followForward
, var
->getName());
2542 Address
CodeGenFunction::emitBlockByrefAddress(Address baseAddr
,
2543 const BlockByrefInfo
&info
,
2545 const llvm::Twine
&name
) {
2546 // Chase the forwarding address if requested.
2547 if (followForward
) {
2548 Address forwardingAddr
= Builder
.CreateStructGEP(baseAddr
, 1, "forwarding");
2549 baseAddr
= Address(Builder
.CreateLoad(forwardingAddr
), info
.Type
,
2550 info
.ByrefAlignment
);
2553 return Builder
.CreateStructGEP(baseAddr
, info
.FieldIndex
, name
);
2556 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2561 /// void *__forwarding;
2562 /// int32_t __flags;
2564 /// void *__copy_helper; // only if needed
2565 /// void *__destroy_helper; // only if needed
2566 /// void *__byref_variable_layout;// only if needed
2567 /// char padding[X]; // only if needed
2571 const BlockByrefInfo
&CodeGenFunction::getBlockByrefInfo(const VarDecl
*D
) {
2572 auto it
= BlockByrefInfos
.find(D
);
2573 if (it
!= BlockByrefInfos
.end())
2576 llvm::StructType
*byrefType
=
2577 llvm::StructType::create(getLLVMContext(),
2578 "struct.__block_byref_" + D
->getNameAsString());
2580 QualType Ty
= D
->getType();
2583 SmallVector
<llvm::Type
*, 8> types
;
2586 types
.push_back(VoidPtrTy
);
2587 size
+= getPointerSize();
2589 // void *__forwarding;
2590 types
.push_back(VoidPtrTy
);
2591 size
+= getPointerSize();
2594 types
.push_back(Int32Ty
);
2595 size
+= CharUnits::fromQuantity(4);
2598 types
.push_back(Int32Ty
);
2599 size
+= CharUnits::fromQuantity(4);
2601 // Note that this must match *exactly* the logic in buildByrefHelpers.
2602 bool hasCopyAndDispose
= getContext().BlockRequiresCopying(Ty
, D
);
2603 if (hasCopyAndDispose
) {
2604 /// void *__copy_helper;
2605 types
.push_back(VoidPtrTy
);
2606 size
+= getPointerSize();
2608 /// void *__destroy_helper;
2609 types
.push_back(VoidPtrTy
);
2610 size
+= getPointerSize();
2613 bool HasByrefExtendedLayout
= false;
2614 Qualifiers::ObjCLifetime Lifetime
= Qualifiers::OCL_None
;
2615 if (getContext().getByrefLifetime(Ty
, Lifetime
, HasByrefExtendedLayout
) &&
2616 HasByrefExtendedLayout
) {
2617 /// void *__byref_variable_layout;
2618 types
.push_back(VoidPtrTy
);
2619 size
+= CharUnits::fromQuantity(PointerSizeInBytes
);
2623 llvm::Type
*varTy
= ConvertTypeForMem(Ty
);
2625 bool packed
= false;
2626 CharUnits varAlign
= getContext().getDeclAlign(D
);
2627 CharUnits varOffset
= size
.alignTo(varAlign
);
2629 // We may have to insert padding.
2630 if (varOffset
!= size
) {
2631 llvm::Type
*paddingTy
=
2632 llvm::ArrayType::get(Int8Ty
, (varOffset
- size
).getQuantity());
2634 types
.push_back(paddingTy
);
2637 // Conversely, we might have to prevent LLVM from inserting padding.
2638 } else if (CGM
.getDataLayout().getABITypeAlign(varTy
) >
2639 uint64_t(varAlign
.getQuantity())) {
2642 types
.push_back(varTy
);
2644 byrefType
->setBody(types
, packed
);
2646 BlockByrefInfo info
;
2647 info
.Type
= byrefType
;
2648 info
.FieldIndex
= types
.size() - 1;
2649 info
.FieldOffset
= varOffset
;
2650 info
.ByrefAlignment
= std::max(varAlign
, getPointerAlign());
2652 auto pair
= BlockByrefInfos
.insert({D
, info
});
2653 assert(pair
.second
&& "info was inserted recursively?");
2654 return pair
.first
->second
;
2657 /// Initialize the structural components of a __block variable, i.e.
2658 /// everything but the actual object.
2659 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission
&emission
) {
2660 // Find the address of the local.
2661 Address addr
= emission
.Addr
;
2663 // That's an alloca of the byref structure type.
2664 llvm::StructType
*byrefType
= cast
<llvm::StructType
>(addr
.getElementType());
2666 unsigned nextHeaderIndex
= 0;
2667 CharUnits nextHeaderOffset
;
2668 auto storeHeaderField
= [&](llvm::Value
*value
, CharUnits fieldSize
,
2669 const Twine
&name
) {
2670 auto fieldAddr
= Builder
.CreateStructGEP(addr
, nextHeaderIndex
, name
);
2671 Builder
.CreateStore(value
, fieldAddr
);
2674 nextHeaderOffset
+= fieldSize
;
2677 // Build the byref helpers if necessary. This is null if we don't need any.
2678 BlockByrefHelpers
*helpers
= buildByrefHelpers(*byrefType
, emission
);
2680 const VarDecl
&D
= *emission
.Variable
;
2681 QualType type
= D
.getType();
2683 bool HasByrefExtendedLayout
= false;
2684 Qualifiers::ObjCLifetime ByrefLifetime
= Qualifiers::OCL_None
;
2685 bool ByRefHasLifetime
=
2686 getContext().getByrefLifetime(type
, ByrefLifetime
, HasByrefExtendedLayout
);
2690 // Initialize the 'isa', which is just 0 or 1.
2692 if (type
.isObjCGCWeak())
2694 V
= Builder
.CreateIntToPtr(Builder
.getInt32(isa
), Int8PtrTy
, "isa");
2695 storeHeaderField(V
, getPointerSize(), "byref.isa");
2697 // Store the address of the variable into its own forwarding pointer.
2698 storeHeaderField(addr
.getPointer(), getPointerSize(), "byref.forwarding");
2701 // c) the flags field is set to either 0 if no helper functions are
2702 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2704 if (helpers
) flags
|= BLOCK_BYREF_HAS_COPY_DISPOSE
;
2705 if (ByRefHasLifetime
) {
2706 if (HasByrefExtendedLayout
) flags
|= BLOCK_BYREF_LAYOUT_EXTENDED
;
2707 else switch (ByrefLifetime
) {
2708 case Qualifiers::OCL_Strong
:
2709 flags
|= BLOCK_BYREF_LAYOUT_STRONG
;
2711 case Qualifiers::OCL_Weak
:
2712 flags
|= BLOCK_BYREF_LAYOUT_WEAK
;
2714 case Qualifiers::OCL_ExplicitNone
:
2715 flags
|= BLOCK_BYREF_LAYOUT_UNRETAINED
;
2717 case Qualifiers::OCL_None
:
2718 if (!type
->isObjCObjectPointerType() && !type
->isBlockPointerType())
2719 flags
|= BLOCK_BYREF_LAYOUT_NON_OBJECT
;
2724 if (CGM
.getLangOpts().ObjCGCBitmapPrint
) {
2725 printf("\n Inline flag for BYREF variable layout (%d):", flags
.getBitMask());
2726 if (flags
& BLOCK_BYREF_HAS_COPY_DISPOSE
)
2727 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2728 if (flags
& BLOCK_BYREF_LAYOUT_MASK
) {
2729 BlockFlags
ThisFlag(flags
.getBitMask() & BLOCK_BYREF_LAYOUT_MASK
);
2730 if (ThisFlag
== BLOCK_BYREF_LAYOUT_EXTENDED
)
2731 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2732 if (ThisFlag
== BLOCK_BYREF_LAYOUT_STRONG
)
2733 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2734 if (ThisFlag
== BLOCK_BYREF_LAYOUT_WEAK
)
2735 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2736 if (ThisFlag
== BLOCK_BYREF_LAYOUT_UNRETAINED
)
2737 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2738 if (ThisFlag
== BLOCK_BYREF_LAYOUT_NON_OBJECT
)
2739 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2744 storeHeaderField(llvm::ConstantInt::get(IntTy
, flags
.getBitMask()),
2745 getIntSize(), "byref.flags");
2747 CharUnits byrefSize
= CGM
.GetTargetTypeStoreSize(byrefType
);
2748 V
= llvm::ConstantInt::get(IntTy
, byrefSize
.getQuantity());
2749 storeHeaderField(V
, getIntSize(), "byref.size");
2752 storeHeaderField(helpers
->CopyHelper
, getPointerSize(),
2753 "byref.copyHelper");
2754 storeHeaderField(helpers
->DisposeHelper
, getPointerSize(),
2755 "byref.disposeHelper");
2758 if (ByRefHasLifetime
&& HasByrefExtendedLayout
) {
2759 auto layoutInfo
= CGM
.getObjCRuntime().BuildByrefLayout(CGM
, type
);
2760 storeHeaderField(layoutInfo
, getPointerSize(), "byref.layout");
2764 void CodeGenFunction::BuildBlockRelease(llvm::Value
*V
, BlockFieldFlags flags
,
2766 llvm::FunctionCallee F
= CGM
.getBlockObjectDispose();
2767 llvm::Value
*args
[] = {V
,
2768 llvm::ConstantInt::get(Int32Ty
, flags
.getBitMask())};
2771 EmitRuntimeCallOrInvoke(F
, args
);
2773 EmitNounwindRuntimeCall(F
, args
);
2776 void CodeGenFunction::enterByrefCleanup(CleanupKind Kind
, Address Addr
,
2777 BlockFieldFlags Flags
,
2778 bool LoadBlockVarAddr
, bool CanThrow
) {
2779 EHStack
.pushCleanup
<CallBlockRelease
>(Kind
, Addr
, Flags
, LoadBlockVarAddr
,
2783 /// Adjust the declaration of something from the blocks API.
2784 static void configureBlocksRuntimeObject(CodeGenModule
&CGM
,
2785 llvm::Constant
*C
) {
2786 auto *GV
= cast
<llvm::GlobalValue
>(C
->stripPointerCasts());
2788 if (CGM
.getTarget().getTriple().isOSBinFormatCOFF()) {
2789 IdentifierInfo
&II
= CGM
.getContext().Idents
.get(C
->getName());
2790 TranslationUnitDecl
*TUDecl
= CGM
.getContext().getTranslationUnitDecl();
2791 DeclContext
*DC
= TranslationUnitDecl::castToDeclContext(TUDecl
);
2793 assert((isa
<llvm::Function
>(C
->stripPointerCasts()) ||
2794 isa
<llvm::GlobalVariable
>(C
->stripPointerCasts())) &&
2795 "expected Function or GlobalVariable");
2797 const NamedDecl
*ND
= nullptr;
2798 for (const auto *Result
: DC
->lookup(&II
))
2799 if ((ND
= dyn_cast
<FunctionDecl
>(Result
)) ||
2800 (ND
= dyn_cast
<VarDecl
>(Result
)))
2803 // TODO: support static blocks runtime
2804 if (GV
->isDeclaration() && (!ND
|| !ND
->hasAttr
<DLLExportAttr
>())) {
2805 GV
->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass
);
2806 GV
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
2808 GV
->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
2809 GV
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
2813 if (CGM
.getLangOpts().BlocksRuntimeOptional
&& GV
->isDeclaration() &&
2814 GV
->hasExternalLinkage())
2815 GV
->setLinkage(llvm::GlobalValue::ExternalWeakLinkage
);
2817 CGM
.setDSOLocal(GV
);
2820 llvm::FunctionCallee
CodeGenModule::getBlockObjectDispose() {
2821 if (BlockObjectDispose
)
2822 return BlockObjectDispose
;
2824 llvm::Type
*args
[] = { Int8PtrTy
, Int32Ty
};
2825 llvm::FunctionType
*fty
2826 = llvm::FunctionType::get(VoidTy
, args
, false);
2827 BlockObjectDispose
= CreateRuntimeFunction(fty
, "_Block_object_dispose");
2828 configureBlocksRuntimeObject(
2829 *this, cast
<llvm::Constant
>(BlockObjectDispose
.getCallee()));
2830 return BlockObjectDispose
;
2833 llvm::FunctionCallee
CodeGenModule::getBlockObjectAssign() {
2834 if (BlockObjectAssign
)
2835 return BlockObjectAssign
;
2837 llvm::Type
*args
[] = { Int8PtrTy
, Int8PtrTy
, Int32Ty
};
2838 llvm::FunctionType
*fty
2839 = llvm::FunctionType::get(VoidTy
, args
, false);
2840 BlockObjectAssign
= CreateRuntimeFunction(fty
, "_Block_object_assign");
2841 configureBlocksRuntimeObject(
2842 *this, cast
<llvm::Constant
>(BlockObjectAssign
.getCallee()));
2843 return BlockObjectAssign
;
2846 llvm::Constant
*CodeGenModule::getNSConcreteGlobalBlock() {
2847 if (NSConcreteGlobalBlock
)
2848 return NSConcreteGlobalBlock
;
2850 NSConcreteGlobalBlock
= GetOrCreateLLVMGlobal(
2851 "_NSConcreteGlobalBlock", Int8PtrTy
, LangAS::Default
, nullptr);
2852 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock
);
2853 return NSConcreteGlobalBlock
;
2856 llvm::Constant
*CodeGenModule::getNSConcreteStackBlock() {
2857 if (NSConcreteStackBlock
)
2858 return NSConcreteStackBlock
;
2860 NSConcreteStackBlock
= GetOrCreateLLVMGlobal(
2861 "_NSConcreteStackBlock", Int8PtrTy
, LangAS::Default
, nullptr);
2862 configureBlocksRuntimeObject(*this, NSConcreteStackBlock
);
2863 return NSConcreteStackBlock
;