#include "CGBlocks.h"
#include "CGCXXABI.h"
#include "CGDebugInfo.h"
#include "CGObjCRuntime.h"
#include "CGOpenCLRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "ConstantEmitter.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ScopedPrinter.h"
#include <algorithm>
#include <cstdio>
using namespace clang;
using namespace CodeGen;
CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
: Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
NoEscape(false), HasCXXObject(false), UsesStret(false),
HasCapturedVariableLayout(false), CapturesNonExternalType(false),
LocalAddress(Address::invalid()), StructureType(nullptr), Block(block) {
if (!name.empty() && name[0] == '\01')
name = name.substr(1);
}
BlockByrefHelpers::~BlockByrefHelpers() {}
static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
const CGBlockInfo &blockInfo,
llvm::Constant *blockFn);
static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) {
return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
}
static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) {
return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
}
namespace {
struct BlockCaptureManagedEntity {
BlockCaptureEntityKind CopyKind, DisposeKind;
BlockFieldFlags CopyFlags, DisposeFlags;
const BlockDecl::Capture *CI;
const CGBlockInfo::Capture *Capture;
BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
BlockCaptureEntityKind DisposeType,
BlockFieldFlags CopyFlags,
BlockFieldFlags DisposeFlags,
const BlockDecl::Capture &CI,
const CGBlockInfo::Capture &Capture)
: CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
bool operator<(const BlockCaptureManagedEntity &Other) const {
return Capture->getOffset() < Other.Capture->getOffset();
}
};
enum class CaptureStrKind {
CopyHelper,
DisposeHelper,
Merged
};
}
static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
CaptureStrKind StrKind,
CharUnits BlockAlignment,
CodeGenModule &CGM);
static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
CodeGenModule &CGM) {
std::string Name = "__block_descriptor_";
Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
if (BlockInfo.NeedsCopyDispose) {
if (CGM.getLangOpts().Exceptions)
Name += "e";
if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
Name += "a";
Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
for (auto &Cap : BlockInfo.SortedCaptures) {
if (Cap.isConstantOrTrivial())
continue;
Name += llvm::to_string(Cap.getOffset().getQuantity());
if (Cap.CopyKind == Cap.DisposeKind) {
assert(Cap.CopyKind != BlockCaptureEntityKind::None &&
"shouldn't see BlockCaptureManagedEntity that is None");
Name += getBlockCaptureStr(Cap, CaptureStrKind::Merged,
BlockInfo.BlockAlign, CGM);
} else {
Name += getBlockCaptureStr(Cap, CaptureStrKind::CopyHelper,
BlockInfo.BlockAlign, CGM);
Name += getBlockCaptureStr(Cap, CaptureStrKind::DisposeHelper,
BlockInfo.BlockAlign, CGM);
}
}
Name += "_";
}
std::string TypeAtEncoding =
CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
return Name;
}
static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) {
ASTContext &C = CGM.getContext();
llvm::IntegerType *ulong =
cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
llvm::PointerType *i8p = nullptr;
if (CGM.getLangOpts().OpenCL)
i8p =
llvm::Type::getInt8PtrTy(
CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
else
i8p = CGM.VoidPtrTy;
std::string descName;
if (C.getLangOpts().ObjC &&
CGM.getLangOpts().getGC() == LangOptions::NonGC) {
descName = getBlockDescriptorName(blockInfo, CGM);
if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
return llvm::ConstantExpr::getBitCast(desc,
CGM.getBlockDescriptorType());
}
ConstantInitBuilder builder(CGM);
auto elements = builder.beginStruct();
elements.addInt(ulong, 0);
elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
bool hasInternalHelper = false;
if (blockInfo.NeedsCopyDispose) {
llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
elements.add(copyHelper);
llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
elements.add(disposeHelper);
if (cast<llvm::Function>(copyHelper->stripPointerCasts())
->hasInternalLinkage() ||
cast<llvm::Function>(disposeHelper->stripPointerCasts())
->hasInternalLinkage())
hasInternalHelper = true;
}
std::string typeAtEncoding =
CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
elements.add(llvm::ConstantExpr::getBitCast(
CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
if (C.getLangOpts().ObjC) {
if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
else
elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
}
else
elements.addNullPointer(i8p);
unsigned AddrSpace = 0;
if (C.getLangOpts().OpenCL)
AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
llvm::GlobalValue::LinkageTypes linkage;
if (descName.empty()) {
linkage = llvm::GlobalValue::InternalLinkage;
descName = "__block_descriptor_tmp";
} else if (hasInternalHelper) {
linkage = llvm::GlobalValue::InternalLinkage;
} else {
linkage = llvm::GlobalValue::LinkOnceODRLinkage;
}
llvm::GlobalVariable *global =
elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
true, linkage, AddrSpace);
if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
if (CGM.supportsCOMDAT())
global->setComdat(CGM.getModule().getOrInsertComdat(descName));
global->setVisibility(llvm::GlobalValue::HiddenVisibility);
global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
}
return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
}
namespace {
struct BlockLayoutChunk {
CharUnits Alignment;
CharUnits Size;
const BlockDecl::Capture *Capture; llvm::Type *Type;
QualType FieldType;
BlockCaptureEntityKind CopyKind, DisposeKind;
BlockFieldFlags CopyFlags, DisposeFlags;
BlockLayoutChunk(CharUnits align, CharUnits size,
const BlockDecl::Capture *capture, llvm::Type *type,
QualType fieldType, BlockCaptureEntityKind CopyKind,
BlockFieldFlags CopyFlags,
BlockCaptureEntityKind DisposeKind,
BlockFieldFlags DisposeFlags)
: Alignment(align), Size(size), Capture(capture), Type(type),
FieldType(fieldType), CopyKind(CopyKind), DisposeKind(DisposeKind),
CopyFlags(CopyFlags), DisposeFlags(DisposeFlags) {}
void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
if (!Capture) {
info.CXXThisIndex = index;
info.CXXThisOffset = offset;
} else {
info.SortedCaptures.push_back(CGBlockInfo::Capture::makeIndex(
index, offset, FieldType, CopyKind, CopyFlags, DisposeKind,
DisposeFlags, Capture));
}
}
bool isTrivial() const {
return CopyKind == BlockCaptureEntityKind::None &&
DisposeKind == BlockCaptureEntityKind::None;
}
};
bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
if (left.Alignment != right.Alignment)
return left.Alignment > right.Alignment;
auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
switch (chunk.CopyKind) {
case BlockCaptureEntityKind::ARCStrong:
return 0;
case BlockCaptureEntityKind::BlockObject:
switch (chunk.CopyFlags.getBitMask()) {
case BLOCK_FIELD_IS_OBJECT:
return 0;
case BLOCK_FIELD_IS_BLOCK:
return 1;
case BLOCK_FIELD_IS_BYREF:
return 2;
default:
break;
}
break;
case BlockCaptureEntityKind::ARCWeak:
return 3;
default:
break;
}
return 4;
};
return getPrefOrder(left) < getPrefOrder(right);
}
}
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
const LangOptions &LangOpts);
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
const LangOptions &LangOpts);
static void addBlockLayout(CharUnits align, CharUnits size,
const BlockDecl::Capture *capture, llvm::Type *type,
QualType fieldType,
SmallVectorImpl<BlockLayoutChunk> &Layout,
CGBlockInfo &Info, CodeGenModule &CGM) {
if (!capture) {
Layout.push_back(BlockLayoutChunk(
align, size, capture, type, fieldType, BlockCaptureEntityKind::None,
BlockFieldFlags(), BlockCaptureEntityKind::None, BlockFieldFlags()));
return;
}
const LangOptions &LangOpts = CGM.getLangOpts();
BlockCaptureEntityKind CopyKind, DisposeKind;
BlockFieldFlags CopyFlags, DisposeFlags;
std::tie(CopyKind, CopyFlags) =
computeCopyInfoForBlockCapture(*capture, fieldType, LangOpts);
std::tie(DisposeKind, DisposeFlags) =
computeDestroyInfoForBlockCapture(*capture, fieldType, LangOpts);
Layout.push_back(BlockLayoutChunk(align, size, capture, type, fieldType,
CopyKind, CopyFlags, DisposeKind,
DisposeFlags));
if (Info.NoEscape)
return;
if (!Layout.back().isTrivial())
Info.NeedsCopyDispose = true;
}
static bool isSafeForCXXConstantCapture(QualType type) {
const RecordType *recordType =
type->getBaseElementTypeUnsafe()->getAs<RecordType>();
if (!recordType) return true;
const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
if (!record->hasTrivialDestructor()) return false;
if (record->hasNonTrivialCopyConstructor()) return false;
return !record->hasMutableFields();
}
static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
CodeGenFunction *CGF,
const VarDecl *var) {
if (isa<ParmVarDecl>(var))
return nullptr;
QualType type = var->getType();
if (!type.isConstQualified()) return nullptr;
if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
return nullptr;
const Expr *init = var->getInit();
if (!init) return nullptr;
return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
}
static CharUnits getLowBit(CharUnits v) {
return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
}
static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
SmallVectorImpl<llvm::Type*> &elementTypes) {
assert(elementTypes.empty());
if (CGM.getLangOpts().OpenCL) {
auto GenericAS =
CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
auto GenPtrAlign =
CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
auto GenPtrSize =
CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
assert(CGM.getIntSize() <= GenPtrSize);
assert(CGM.getIntAlign() <= GenPtrAlign);
assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
elementTypes.push_back(CGM.IntTy);
elementTypes.push_back(CGM.IntTy);
elementTypes.push_back(
CGM.getOpenCLRuntime()
.getGenericVoidPointerType());
unsigned Offset =
2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
unsigned BlockAlign = GenPtrAlign.getQuantity();
if (auto *Helper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
for (auto I : Helper->getCustomFieldTypes()) {
unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
if (BlockAlign < Align)
BlockAlign = Align;
assert(Offset % Align == 0);
Offset += CGM.getDataLayout().getTypeAllocSize(I);
elementTypes.push_back(I);
}
}
info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
info.BlockSize = CharUnits::fromQuantity(Offset);
} else {
assert(CGM.getIntSize() <= CGM.getPointerSize());
assert(CGM.getIntAlign() <= CGM.getPointerAlign());
assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
info.BlockAlign = CGM.getPointerAlign();
info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
elementTypes.push_back(CGM.VoidPtrTy);
elementTypes.push_back(CGM.IntTy);
elementTypes.push_back(CGM.IntTy);
elementTypes.push_back(CGM.VoidPtrTy);
elementTypes.push_back(CGM.getBlockDescriptorType());
}
}
static QualType getCaptureFieldType(const CodeGenFunction &CGF,
const BlockDecl::Capture &CI) {
const VarDecl *VD = CI.getVariable();
if (CGF.BlockInfo && CI.isNested())
return CGF.BlockInfo->getCapture(VD).fieldType();
if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
return FD->getType();
return VD->isNonEscapingByref() ?
CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
}
static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
CGBlockInfo &info) {
ASTContext &C = CGM.getContext();
const BlockDecl *block = info.getBlockDecl();
SmallVector<llvm::Type*, 8> elementTypes;
initializeForBlockHeader(CGM, info, elementTypes);
bool hasNonConstantCustomFields = false;
if (auto *OpenCLHelper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
hasNonConstantCustomFields =
!OpenCLHelper->areAllCustomFieldValuesConstant(info);
if (!block->hasCaptures() && !hasNonConstantCustomFields) {
info.StructureType =
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
info.CanBeGlobal = true;
return;
}
else if (C.getLangOpts().ObjC &&
CGM.getLangOpts().getGC() == LangOptions::NonGC)
info.HasCapturedVariableLayout = true;
if (block->doesNotEscape())
info.NoEscape = true;
SmallVector<BlockLayoutChunk, 16> layout;
layout.reserve(block->capturesCXXThis() +
(block->capture_end() - block->capture_begin()));
CharUnits maxFieldAlign;
if (block->capturesCXXThis()) {
assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
"Can't capture 'this' outside a method");
QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
auto TInfo = CGM.getContext().getTypeInfoInChars(thisType);
maxFieldAlign = std::max(maxFieldAlign, TInfo.Align);
addBlockLayout(TInfo.Align, TInfo.Width, nullptr, llvmType, thisType,
layout, info, CGM);
}
for (const auto &CI : block->captures()) {
const VarDecl *variable = CI.getVariable();
if (CI.isEscapingByref()) {
CharUnits align = CGM.getPointerAlign();
maxFieldAlign = std::max(maxFieldAlign, align);
assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() &&
"capture type differs from the variable type");
addBlockLayout(align, CGM.getPointerSize(), &CI, CGM.VoidPtrTy,
variable->getType(), layout, info, CGM);
continue;
}
if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
info.SortedCaptures.push_back(
CGBlockInfo::Capture::makeConstant(constant, &CI));
continue;
}
QualType VT = getCaptureFieldType(*CGF, CI);
if (CGM.getLangOpts().CPlusPlus)
if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl())
if (CI.hasCopyExpr() || !record->hasTrivialDestructor()) {
info.HasCXXObject = true;
if (!record->isExternallyVisible())
info.CapturesNonExternalType = true;
}
CharUnits size = C.getTypeSizeInChars(VT);
CharUnits align = C.getDeclAlign(variable);
maxFieldAlign = std::max(maxFieldAlign, align);
llvm::Type *llvmType =
CGM.getTypes().ConvertTypeForMem(VT);
addBlockLayout(align, size, &CI, llvmType, VT, layout, info, CGM);
}
if (layout.empty()) {
info.StructureType =
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
info.CanBeGlobal = true;
info.buildCaptureMap();
return;
}
llvm::stable_sort(layout);
info.BlockHeaderForcedGapOffset = info.BlockSize;
info.BlockHeaderForcedGapSize = CharUnits::Zero();
CharUnits &blockSize = info.BlockSize;
info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
CharUnits endAlign = getLowBit(blockSize);
if (endAlign < maxFieldAlign) {
SmallVectorImpl<BlockLayoutChunk>::iterator
li = layout.begin() + 1, le = layout.end();
for (; li != le && endAlign < li->Alignment; ++li)
;
if (li != le) {
SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
for (; li != le; ++li) {
assert(endAlign >= li->Alignment);
li->setIndex(info, elementTypes.size(), blockSize);
elementTypes.push_back(li->Type);
blockSize += li->Size;
endAlign = getLowBit(blockSize);
if (endAlign >= maxFieldAlign) {
++li;
break;
}
}
layout.erase(first, li);
}
}
assert(endAlign == getLowBit(blockSize));
if (endAlign < maxFieldAlign) {
CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
CharUnits padding = newBlockSize - blockSize;
if (blockSize == info.BlockHeaderForcedGapOffset) {
info.BlockHeaderForcedGapSize = padding;
}
elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
padding.getQuantity()));
blockSize = newBlockSize;
endAlign = getLowBit(blockSize); }
assert(endAlign >= maxFieldAlign);
assert(endAlign == getLowBit(blockSize));
for (SmallVectorImpl<BlockLayoutChunk>::iterator
li = layout.begin(), le = layout.end(); li != le; ++li) {
if (endAlign < li->Alignment) {
CharUnits padding = li->Alignment - endAlign;
elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
padding.getQuantity()));
blockSize += padding;
endAlign = getLowBit(blockSize);
}
assert(endAlign >= li->Alignment);
li->setIndex(info, elementTypes.size(), blockSize);
elementTypes.push_back(li->Type);
blockSize += li->Size;
endAlign = getLowBit(blockSize);
}
info.buildCaptureMap();
info.StructureType =
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
}
llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
if (!blockExpr->getBlockDecl()->hasCaptures())
if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
return Block;
CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
computeBlockInfo(CGM, this, blockInfo);
blockInfo.BlockExpression = blockExpr;
if (!blockInfo.CanBeGlobal)
blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
blockInfo.BlockAlign, "block");
return EmitBlockLiteral(blockInfo);
}
llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
auto GenVoidPtrTy =
IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
auto GenVoidPtrSize = CharUnits::fromQuantity(
CGM.getTarget().getPointerWidth(
CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
8);
bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
CodeGenFunction BlockCGF{CGM, true};
BlockCGF.SanOpts = SanOpts;
auto *InvokeFn = BlockCGF.GenerateBlockFunction(
CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
if (blockInfo.CanBeGlobal)
return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
Address blockAddr = blockInfo.LocalAddress;
assert(blockAddr.isValid() && "block has no address!");
llvm::Constant *isa;
llvm::Constant *descriptor;
BlockFlags flags;
if (!IsOpenCL) {
llvm::Constant *blockISA = blockInfo.NoEscape
? CGM.getNSConcreteGlobalBlock()
: CGM.getNSConcreteStackBlock();
isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
descriptor = buildBlockDescriptor(CGM, blockInfo);
flags = BLOCK_HAS_SIGNATURE;
if (blockInfo.HasCapturedVariableLayout)
flags |= BLOCK_HAS_EXTENDED_LAYOUT;
if (blockInfo.NeedsCopyDispose)
flags |= BLOCK_HAS_COPY_DISPOSE;
if (blockInfo.HasCXXObject)
flags |= BLOCK_HAS_CXX_OBJ;
if (blockInfo.UsesStret)
flags |= BLOCK_USE_STRET;
if (blockInfo.NoEscape)
flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
}
auto projectField = [&](unsigned index, const Twine &name) -> Address {
return Builder.CreateStructGEP(blockAddr, index, name);
};
auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
Builder.CreateStore(value, projectField(index, name));
};
{
unsigned index = 0;
CharUnits offset;
auto addHeaderField = [&](llvm::Value *value, CharUnits size,
const Twine &name) {
storeField(value, index, name);
offset += size;
index++;
};
if (!IsOpenCL) {
addHeaderField(isa, getPointerSize(), "block.isa");
addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
getIntSize(), "block.flags");
addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
"block.reserved");
} else {
addHeaderField(
llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
getIntSize(), "block.size");
addHeaderField(
llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
getIntSize(), "block.align");
}
addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
if (!IsOpenCL)
addHeaderField(descriptor, getPointerSize(), "block.descriptor");
else if (auto *Helper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
addHeaderField(
I.first,
CharUnits::fromQuantity(
CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
I.second);
}
}
}
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
if (blockDecl->capturesCXXThis()) {
Address addr =
projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
Builder.CreateStore(LoadCXXThis(), addr);
}
for (const auto &CI : blockDecl->captures()) {
const VarDecl *variable = CI.getVariable();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) continue;
QualType type = capture.fieldType();
Address blockField = projectField(capture.getIndex(), "block.captured");
Address src = Address::invalid();
if (blockDecl->isConversionFromLambda()) {
src = Address::invalid();
} else if (CI.isEscapingByref()) {
if (BlockInfo && CI.isNested()) {
const CGBlockInfo::Capture &enclosingCapture =
BlockInfo->getCapture(variable);
src = Builder.CreateStructGEP(LoadBlockStruct(),
enclosingCapture.getIndex(),
"block.capture.addr");
} else {
auto I = LocalDeclMap.find(variable);
assert(I != LocalDeclMap.end());
src = I->second;
}
} else {
DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
CI.isNested(),
type.getNonReferenceType(), VK_LValue,
SourceLocation());
src = EmitDeclRefLValue(&declRef).getAddress(*this);
};
if (CI.isEscapingByref()) {
llvm::Value *byrefPointer;
if (CI.isNested())
byrefPointer = Builder.CreateLoad(src, "byref.capture");
else
byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
Builder.CreateStore(byrefPointer, blockField);
} else if (const Expr *copyExpr = CI.getCopyExpr()) {
if (blockDecl->isConversionFromLambda()) {
AggValueSlot Slot =
AggValueSlot::forAddr(blockField, Qualifiers(),
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased,
AggValueSlot::DoesNotOverlap);
EmitAggExpr(copyExpr, Slot);
} else {
EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
}
} else if (type->isReferenceType()) {
Builder.CreateStore(src.getPointer(), blockField);
} else if (type.isConstQualified() &&
type.getObjCLifetime() == Qualifiers::OCL_Strong &&
CGM.getCodeGenOpts().OptimizationLevel != 0) {
llvm::Value *value = Builder.CreateLoad(src, "captured");
Builder.CreateStore(value, blockField);
} else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
type->isBlockPointerType()) {
llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
value = EmitARCRetainNonBlock(value);
Builder.CreateStore(value, blockField);
} else {
ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
ImplicitParamDecl::Other);
DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
CI.isNested(),
type, VK_LValue, SourceLocation());
ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
&declRef, VK_PRValue, FPOptionsOverride());
EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
MakeAddrLValue(blockField, type, AlignmentSource::Decl),
false);
}
if (!blockInfo.NoEscape && !blockInfo.NeedsCopyDispose)
continue;
if (CI.isByRef())
continue;
QualType::DestructionKind dtorKind = type.isDestructedType();
if (dtorKind == QualType::DK_none)
continue;
CodeGenFunction::Destroyer *destroyer;
if (type.isConstQualified() &&
type.getObjCLifetime() == Qualifiers::OCL_Strong &&
CGM.getCodeGenOpts().OptimizationLevel != 0) {
assert(CGM.getLangOpts().ObjCAutoRefCount &&
"expected ObjC ARC to be enabled");
destroyer = emitARCIntrinsicUse;
} else if (dtorKind == QualType::DK_objc_strong_lifetime) {
destroyer = destroyARCStrongImprecise;
} else {
destroyer = getDestroyer(dtorKind);
}
CleanupKind cleanupKind = NormalCleanup;
bool useArrayEHCleanup = needsEHCleanup(dtorKind);
if (useArrayEHCleanup)
cleanupKind = NormalAndEHCleanup;
auto IsBlockDeclInRetExpr = [&]() {
auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
if (EWC)
for (auto &C : EWC->getObjects())
if (auto *BD = C.dyn_cast<BlockDecl *>())
if (BD == blockDecl)
return true;
return false;
};
if (IsBlockDeclInRetExpr())
pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
else
pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
useArrayEHCleanup);
}
llvm::Value *result = Builder.CreatePointerCast(
blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
if (IsOpenCL) {
CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
result, blockInfo.StructureType);
}
return result;
}
llvm::Type *CodeGenModule::getBlockDescriptorType() {
if (BlockDescriptorType)
return BlockDescriptorType;
llvm::Type *UnsignedLongTy =
getTypes().ConvertType(getContext().UnsignedLongTy);
BlockDescriptorType = llvm::StructType::create(
"struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
unsigned AddrSpace = 0;
if (getLangOpts().OpenCL)
AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
return BlockDescriptorType;
}
llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
if (GenericBlockLiteralType)
return GenericBlockLiteralType;
llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
if (getLangOpts().OpenCL) {
SmallVector<llvm::Type *, 8> StructFields(
{IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
llvm::append_range(StructFields, Helper->getCustomFieldTypes());
}
GenericBlockLiteralType = llvm::StructType::create(
StructFields, "struct.__opencl_block_literal_generic");
} else {
GenericBlockLiteralType =
llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
}
return GenericBlockLiteralType;
}
RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
ReturnValueSlot ReturnValue) {
const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
llvm::Value *Func = nullptr;
QualType FnType = BPT->getPointeeType();
ASTContext &Ctx = getContext();
CallArgList Args;
if (getLangOpts().OpenCL) {
llvm::Type *GenericVoidPtrTy =
CGM.getOpenCLRuntime().getGenericVoidPointerType();
llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
BlockPtr, GenericVoidPtrTy);
QualType VoidPtrQualTy = Ctx.getPointerType(
Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
if (!isa<ParmVarDecl>(E->getCalleeDecl()))
Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
else {
llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
Func = Builder.CreateAlignedLoad(GenericVoidPtrTy, FuncPtr,
getPointerAlign());
}
} else {
BlockPtr = Builder.CreatePointerCast(
BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Func = Builder.CreateAlignedLoad(VoidPtrTy, FuncPtr, getPointerAlign());
}
const FunctionType *FuncTy = FnType->castAs<FunctionType>();
const CGFunctionInfo &FnInfo =
CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
CGCallee Callee(CGCalleeInfo(), Func);
return EmitCall(FnInfo, Callee, ReturnValue, Args);
}
Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
assert(BlockInfo && "evaluating block ref without block information?");
const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
"block.capture.addr");
if (variable->isEscapingByref()) {
auto &byrefInfo = getBlockByrefInfo(variable);
addr = Address(Builder.CreateLoad(addr), Int8Ty, byrefInfo.ByrefAlignment);
addr = Builder.CreateElementBitCast(addr, byrefInfo.Type, "byref.addr");
addr = emitBlockByrefAddress(addr, byrefInfo, true,
variable->getName());
}
assert((!variable->isNonEscapingByref() ||
capture.fieldType()->isReferenceType()) &&
"the capture field of a non-escaping variable should have a "
"reference type");
if (capture.fieldType()->isReferenceType())
addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
return addr;
}
void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
llvm::Constant *Addr) {
bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
(void)Ok;
assert(Ok && "Trying to replace an already-existing global block!");
}
llvm::Constant *
CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
StringRef Name) {
if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
return Block;
CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
blockInfo.BlockExpression = BE;
computeBlockInfo(*this, nullptr, blockInfo);
{
CodeGenFunction::DeclMapTy LocalDeclMap;
CodeGenFunction(*this).GenerateBlockFunction(
GlobalDecl(), blockInfo, LocalDeclMap,
false, true);
}
return getAddrOfGlobalBlockIfEmitted(BE);
}
static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
const CGBlockInfo &blockInfo,
llvm::Constant *blockFn) {
assert(blockInfo.CanBeGlobal);
assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
"Refusing to re-emit a global block.");
ConstantInitBuilder builder(CGM);
auto fields = builder.beginStruct();
bool IsOpenCL = CGM.getLangOpts().OpenCL;
bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
if (!IsOpenCL) {
if (IsWindows)
fields.addNullPointer(CGM.Int8PtrPtrTy);
else
fields.add(CGM.getNSConcreteGlobalBlock());
BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
if (blockInfo.UsesStret)
flags |= BLOCK_USE_STRET;
fields.addInt(CGM.IntTy, flags.getBitMask());
fields.addInt(CGM.IntTy, 0);
} else {
fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
}
fields.add(blockFn);
if (!IsOpenCL) {
fields.add(buildBlockDescriptor(CGM, blockInfo));
} else if (auto *Helper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
fields.add(I);
}
}
unsigned AddrSpace = 0;
if (CGM.getContext().getLangOpts().OpenCL)
AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
"__block_literal_global", blockInfo.BlockAlign,
!IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
literal->addAttribute("objc_arc_inert");
if (IsWindows) {
auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
{}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
&CGM.getModule());
llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
Init));
b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
b.CreateStructGEP(literal->getValueType(), literal, 0),
CGM.getPointerAlign().getAsAlign());
b.CreateRetVoid();
auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
true, llvm::GlobalValue::InternalLinkage,
Init, ".block_isa_init_ptr");
InitVar->setSection(".CRT$XCLa");
CGM.addUsedGlobal(InitVar);
}
llvm::Type *RequiredType =
CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
llvm::Constant *Result =
llvm::ConstantExpr::getPointerCast(literal, RequiredType);
CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
if (CGM.getContext().getLangOpts().OpenCL)
CGM.getOpenCLRuntime().recordBlockInfo(
blockInfo.BlockExpression,
cast<llvm::Function>(blockFn->stripPointerCasts()), Result,
literal->getValueType());
return Result;
}
void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
unsigned argNum,
llvm::Value *arg) {
assert(BlockInfo && "not emitting prologue of block invocation function?!");
Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
Builder.CreateStore(arg, alloc);
if (CGDebugInfo *DI = getDebugInfo()) {
if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
DI->setLocation(D->getLocation());
DI->EmitDeclareOfBlockLiteralArgVariable(
*BlockInfo, D->getName(), argNum,
cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
}
}
SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
ApplyDebugLocation Scope(*this, StartLoc);
BlockPointer = Builder.CreatePointerCast(
arg,
BlockInfo->StructureType->getPointerTo(
getContext().getLangOpts().OpenCL
? getContext().getTargetAddressSpace(LangAS::opencl_generic)
: 0),
"block");
}
Address CodeGenFunction::LoadBlockStruct() {
assert(BlockInfo && "not in a block invocation function!");
assert(BlockPointer && "no block pointer set!");
return Address(BlockPointer, BlockInfo->StructureType, BlockInfo->BlockAlign);
}
llvm::Function *CodeGenFunction::GenerateBlockFunction(
GlobalDecl GD, const CGBlockInfo &blockInfo, const DeclMapTy &ldm,
bool IsLambdaConversionToBlock, bool BuildGlobalBlock) {
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
CurGD = GD;
CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
BlockInfo = &blockInfo;
for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
const auto *var = dyn_cast<VarDecl>(i->first);
if (var && !var->hasLocalStorage())
setAddrOfLocalVar(var, i->second);
}
FunctionArgList args;
QualType selfTy = getContext().VoidPtrTy;
if (getLangOpts().OpenCL)
selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
getContext().VoidTy, LangAS::opencl_generic));
IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
SourceLocation(), II, selfTy,
ImplicitParamDecl::ObjCSelf);
args.push_back(&SelfDecl);
args.append(blockDecl->param_begin(), blockDecl->param_end());
const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
const CGFunctionInfo &fnInfo =
CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
blockInfo.UsesStret = true;
llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
StringRef name = CGM.getBlockMangledName(GD, blockDecl);
llvm::Function *fn = llvm::Function::Create(
fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
if (BuildGlobalBlock) {
auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
? CGM.getOpenCLRuntime().getGenericVoidPointerType()
: VoidPtrTy;
buildGlobalBlock(CGM, blockInfo,
llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
}
StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
blockDecl->getLocation(),
blockInfo.getBlockExpr()->getBody()->getBeginLoc());
llvm::Value *BlockPointerDbgLoc = BlockPointer;
if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Address Alloca = CreateTempAlloca(BlockPointer->getType(),
getPointerAlign(),
"block.addr");
auto NL = ApplyDebugLocation::CreateEmpty(*this);
Builder.CreateStore(BlockPointer, Alloca);
BlockPointerDbgLoc = Alloca.getPointer();
}
if (blockDecl->capturesCXXThis()) {
Address addr = Builder.CreateStructGEP(
LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
CXXThisValue = Builder.CreateLoad(addr, "this");
}
for (const auto &CI : blockDecl->captures()) {
const VarDecl *variable = CI.getVariable();
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (!capture.isConstant()) continue;
CharUnits align = getContext().getDeclAlign(variable);
Address alloca =
CreateMemTemp(variable->getType(), align, "block.captured-const");
Builder.CreateStore(capture.getConstant(), alloca);
setAddrOfLocalVar(variable, alloca);
}
llvm::BasicBlock *entry = Builder.GetInsertBlock();
llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
--entry_ptr;
if (IsLambdaConversionToBlock)
EmitLambdaBlockInvokeBody();
else {
PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
incrementProfileCounter(blockDecl->getBody());
EmitStmt(blockDecl->getBody());
}
llvm::BasicBlock *resume = Builder.GetInsertBlock();
++entry_ptr;
Builder.SetInsertPoint(entry, entry_ptr);
if (CGDebugInfo *DI = getDebugInfo()) {
for (const auto &CI : blockDecl->captures()) {
const VarDecl *variable = CI.getVariable();
DI->EmitLocation(Builder, variable->getLocation());
if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
if (capture.isConstant()) {
auto addr = LocalDeclMap.find(variable)->second;
(void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Builder);
continue;
}
DI->EmitDeclareOfBlockDeclRefVariable(
variable, BlockPointerDbgLoc, Builder, blockInfo,
entry_ptr == entry->end() ? nullptr : &*entry_ptr);
}
}
DI->EmitLocation(Builder,
cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
}
if (resume == nullptr)
Builder.ClearInsertionPoint();
else
Builder.SetInsertPoint(resume);
FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
return fn;
}
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
const LangOptions &LangOpts) {
if (CI.getCopyExpr()) {
assert(!CI.isByRef());
return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
}
BlockFieldFlags Flags;
if (CI.isEscapingByref()) {
Flags = BLOCK_FIELD_IS_BYREF;
if (T.isObjCGCWeak())
Flags |= BLOCK_FIELD_IS_WEAK;
return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
}
Flags = BLOCK_FIELD_IS_OBJECT;
bool isBlockPointer = T->isBlockPointerType();
if (isBlockPointer)
Flags = BLOCK_FIELD_IS_BLOCK;
switch (T.isNonTrivialToPrimitiveCopy()) {
case QualType::PCK_Struct:
return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
BlockFieldFlags());
case QualType::PCK_ARCWeak:
return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
case QualType::PCK_ARCStrong:
return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
: BlockCaptureEntityKind::BlockObject,
Flags);
case QualType::PCK_Trivial:
case QualType::PCK_VolatileTrivial: {
if (!T->isObjCRetainableType())
return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
if (T->isObjCInertUnsafeUnretainedType())
return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Qualifiers QS = T.getQualifiers();
if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
}
}
llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
}
namespace {
struct CallBlockRelease final : EHScopeStack::Cleanup {
Address Addr;
BlockFieldFlags FieldFlags;
bool LoadBlockVarAddr, CanThrow;
CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
bool CT)
: Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
CanThrow(CT) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
llvm::Value *BlockVarAddr;
if (LoadBlockVarAddr) {
BlockVarAddr = CGF.Builder.CreateLoad(Addr);
BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
} else {
BlockVarAddr = Addr.getPointer();
}
CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
}
};
}
bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
if (const auto *RD = T->getAsCXXRecordDecl())
if (const CXXDestructorDecl *DD = RD->getDestructor())
return DD->getType()->castAs<FunctionProtoType>()->canThrow();
return false;
}
static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
CaptureStrKind StrKind,
CharUnits BlockAlignment,
CodeGenModule &CGM) {
std::string Str;
ASTContext &Ctx = CGM.getContext();
const BlockDecl::Capture &CI = *Cap.Cap;
QualType CaptureTy = CI.getVariable()->getType();
BlockCaptureEntityKind Kind;
BlockFieldFlags Flags;
assert((StrKind != CaptureStrKind::Merged ||
(Cap.CopyKind == Cap.DisposeKind &&
Cap.CopyFlags == Cap.DisposeFlags)) &&
"different operations and flags");
if (StrKind == CaptureStrKind::DisposeHelper) {
Kind = Cap.DisposeKind;
Flags = Cap.DisposeFlags;
} else {
Kind = Cap.CopyKind;
Flags = Cap.CopyFlags;
}
switch (Kind) {
case BlockCaptureEntityKind::CXXRecord: {
Str += "c";
SmallString<256> TyStr;
llvm::raw_svector_ostream Out(TyStr);
CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
break;
}
case BlockCaptureEntityKind::ARCWeak:
Str += "w";
break;
case BlockCaptureEntityKind::ARCStrong:
Str += "s";
break;
case BlockCaptureEntityKind::BlockObject: {
const VarDecl *Var = CI.getVariable();
unsigned F = Flags.getBitMask();
if (F & BLOCK_FIELD_IS_BYREF) {
Str += "r";
if (F & BLOCK_FIELD_IS_WEAK)
Str += "w";
else {
if (StrKind != CaptureStrKind::DisposeHelper) {
if (Ctx.getBlockVarCopyInit(Var).canThrow())
Str += "c";
}
if (StrKind != CaptureStrKind::CopyHelper) {
if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
Str += "d";
}
}
} else {
assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
if (F == BLOCK_FIELD_IS_BLOCK)
Str += "b";
else
Str += "o";
}
break;
}
case BlockCaptureEntityKind::NonTrivialCStruct: {
bool IsVolatile = CaptureTy.isVolatileQualified();
CharUnits Alignment = BlockAlignment.alignmentAtOffset(Cap.getOffset());
Str += "n";
std::string FuncStr;
if (StrKind == CaptureStrKind::DisposeHelper)
FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
CaptureTy, Alignment, IsVolatile, Ctx);
else
FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
CaptureTy, Alignment, IsVolatile, Ctx);
Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
break;
}
case BlockCaptureEntityKind::None:
break;
}
return Str;
}
static std::string getCopyDestroyHelperFuncName(
const SmallVectorImpl<CGBlockInfo::Capture> &Captures,
CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
assert((StrKind == CaptureStrKind::CopyHelper ||
StrKind == CaptureStrKind::DisposeHelper) &&
"unexpected CaptureStrKind");
std::string Name = StrKind == CaptureStrKind::CopyHelper
? "__copy_helper_block_"
: "__destroy_helper_block_";
if (CGM.getLangOpts().Exceptions)
Name += "e";
if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
Name += "a";
Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
for (auto &Cap : Captures) {
if (Cap.isConstantOrTrivial())
continue;
Name += llvm::to_string(Cap.getOffset().getQuantity());
Name += getBlockCaptureStr(Cap, StrKind, BlockAlignment, CGM);
}
return Name;
}
static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
Address Field, QualType CaptureType,
BlockFieldFlags Flags, bool ForCopyHelper,
VarDecl *Var, CodeGenFunction &CGF) {
bool EHOnly = ForCopyHelper;
switch (CaptureKind) {
case BlockCaptureEntityKind::CXXRecord:
case BlockCaptureEntityKind::ARCWeak:
case BlockCaptureEntityKind::NonTrivialCStruct:
case BlockCaptureEntityKind::ARCStrong: {
if (CaptureType.isDestructedType() &&
(!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
CodeGenFunction::Destroyer *Destroyer =
CaptureKind == BlockCaptureEntityKind::ARCStrong
? CodeGenFunction::destroyARCStrongImprecise
: CGF.getDestroyer(CaptureType.isDestructedType());
CleanupKind Kind =
EHOnly ? EHCleanup
: CGF.getCleanupKind(CaptureType.isDestructedType());
CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
}
break;
}
case BlockCaptureEntityKind::BlockObject: {
if (!EHOnly || CGF.getLangOpts().Exceptions) {
CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
bool CanThrow =
!ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
CGF.enterByrefCleanup(Kind, Field, Flags, true,
CanThrow);
}
break;
}
case BlockCaptureEntityKind::None:
break;
}
}
static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
llvm::Function *Fn,
const CGFunctionInfo &FI,
CodeGenModule &CGM) {
if (CapturesNonExternalType) {
CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
} else {
Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, false);
CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
}
}
llvm::Constant *
CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
std::string FuncName = getCopyDestroyHelperFuncName(
blockInfo.SortedCaptures, blockInfo.BlockAlign,
CaptureStrKind::CopyHelper, CGM);
if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
ASTContext &C = getContext();
QualType ReturnTy = C.VoidTy;
FunctionArgList args;
ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
args.push_back(&DstDecl);
ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
args.push_back(&SrcDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
FuncName, &CGM.getModule());
if (CGM.supportsCOMDAT())
Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
SmallVector<QualType, 2> ArgTys;
ArgTys.push_back(C.VoidPtrTy);
ArgTys.push_back(C.VoidPtrTy);
setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
CGM);
StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
auto AL = ApplyDebugLocation::CreateArtificial(*this);
Address src = GetAddrOfLocalVar(&SrcDecl);
src = Address(Builder.CreateLoad(src), Int8Ty, blockInfo.BlockAlign);
src = Builder.CreateElementBitCast(src, blockInfo.StructureType,
"block.source");
Address dst = GetAddrOfLocalVar(&DstDecl);
dst = Address(Builder.CreateLoad(dst), Int8Ty, blockInfo.BlockAlign);
dst =
Builder.CreateElementBitCast(dst, blockInfo.StructureType, "block.dest");
for (auto &capture : blockInfo.SortedCaptures) {
if (capture.isConstantOrTrivial())
continue;
const BlockDecl::Capture &CI = *capture.Cap;
QualType captureType = CI.getVariable()->getType();
BlockFieldFlags flags = capture.CopyFlags;
unsigned index = capture.getIndex();
Address srcField = Builder.CreateStructGEP(src, index);
Address dstField = Builder.CreateStructGEP(dst, index);
switch (capture.CopyKind) {
case BlockCaptureEntityKind::CXXRecord:
assert(CI.getCopyExpr() && "copy expression for variable is missing");
EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
break;
case BlockCaptureEntityKind::ARCWeak:
EmitARCCopyWeak(dstField, srcField);
break;
case BlockCaptureEntityKind::NonTrivialCStruct: {
QualType varType = CI.getVariable()->getType();
callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
MakeAddrLValue(srcField, varType));
break;
}
case BlockCaptureEntityKind::ARCStrong: {
llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
auto *ty = cast<llvm::PointerType>(srcValue->getType());
llvm::Value *null = llvm::ConstantPointerNull::get(ty);
Builder.CreateStore(null, dstField);
EmitARCStoreStrongCall(dstField, srcValue, true);
} else {
EmitARCRetainNonBlock(srcValue);
if (!needsEHCleanup(captureType.isDestructedType()))
cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
}
break;
}
case BlockCaptureEntityKind::BlockObject: {
llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
llvm::Value *dstAddr =
Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
llvm::Value *args[] = {
dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
};
if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
else
EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
break;
}
case BlockCaptureEntityKind::None:
continue;
}
pushCaptureCleanup(capture.CopyKind, dstField, captureType, flags,
true, CI.getVariable(), *this);
}
FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
}
static BlockFieldFlags
getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
QualType T) {
BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
if (T->isBlockPointerType())
Flags = BLOCK_FIELD_IS_BLOCK;
return Flags;
}
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
const LangOptions &LangOpts) {
if (CI.isEscapingByref()) {
BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
if (T.isObjCGCWeak())
Flags |= BLOCK_FIELD_IS_WEAK;
return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
}
switch (T.isDestructedType()) {
case QualType::DK_cxx_destructor:
return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
case QualType::DK_objc_strong_lifetime:
return std::make_pair(BlockCaptureEntityKind::ARCStrong,
getBlockFieldFlagsForObjCObjectPointer(CI, T));
case QualType::DK_objc_weak_lifetime:
return std::make_pair(BlockCaptureEntityKind::ARCWeak,
getBlockFieldFlagsForObjCObjectPointer(CI, T));
case QualType::DK_nontrivial_c_struct:
return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
BlockFieldFlags());
case QualType::DK_none: {
if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
!LangOpts.ObjCAutoRefCount && !T->isObjCInertUnsafeUnretainedType())
return std::make_pair(BlockCaptureEntityKind::BlockObject,
getBlockFieldFlagsForObjCObjectPointer(CI, T));
return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
}
}
llvm_unreachable("after exhaustive DestructionKind switch");
}
llvm::Constant *
CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
std::string FuncName = getCopyDestroyHelperFuncName(
blockInfo.SortedCaptures, blockInfo.BlockAlign,
CaptureStrKind::DisposeHelper, CGM);
if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
ASTContext &C = getContext();
QualType ReturnTy = C.VoidTy;
FunctionArgList args;
ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
args.push_back(&SrcDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
FuncName, &CGM.getModule());
if (CGM.supportsCOMDAT())
Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
SmallVector<QualType, 1> ArgTys;
ArgTys.push_back(C.VoidPtrTy);
setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
CGM);
StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
markAsIgnoreThreadCheckingAtRuntime(Fn);
auto AL = ApplyDebugLocation::CreateArtificial(*this);
Address src = GetAddrOfLocalVar(&SrcDecl);
src = Address(Builder.CreateLoad(src), Int8Ty, blockInfo.BlockAlign);
src = Builder.CreateElementBitCast(src, blockInfo.StructureType, "block");
CodeGenFunction::RunCleanupsScope cleanups(*this);
for (auto &capture : blockInfo.SortedCaptures) {
if (capture.isConstantOrTrivial())
continue;
const BlockDecl::Capture &CI = *capture.Cap;
BlockFieldFlags flags = capture.DisposeFlags;
Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
pushCaptureCleanup(capture.DisposeKind, srcField,
CI.getVariable()->getType(), flags,
false, CI.getVariable(), *this);
}
cleanups.ForceCleanup();
FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
}
namespace {
class ObjectByrefHelpers final : public BlockByrefHelpers {
BlockFieldFlags Flags;
public:
ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
: BlockByrefHelpers(alignment), Flags(flags) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
destField = CGF.Builder.CreateElementBitCast(destField, CGF.Int8Ty);
srcField = CGF.Builder.CreateElementBitCast(srcField, CGF.Int8PtrTy);
llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
CGF.EmitNounwindRuntimeCall(fn, args);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
field = CGF.Builder.CreateElementBitCast(field, CGF.Int8PtrTy);
llvm::Value *value = CGF.Builder.CreateLoad(field);
CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(Flags.getBitMask());
}
};
class ARCWeakByrefHelpers final : public BlockByrefHelpers {
public:
ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
CGF.EmitARCMoveWeak(destField, srcField);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
CGF.EmitARCDestroyWeak(field);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(0);
}
};
class ARCStrongByrefHelpers final : public BlockByrefHelpers {
public:
ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
llvm::Value *value = CGF.Builder.CreateLoad(srcField);
llvm::Value *null =
llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
CGF.Builder.CreateStore(null, destField);
CGF.EmitARCStoreStrongCall(destField, value, true);
CGF.EmitARCStoreStrongCall(srcField, null, true);
return;
}
CGF.Builder.CreateStore(value, destField);
CGF.Builder.CreateStore(null, srcField);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(1);
}
};
class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
public:
ARCStrongBlockByrefHelpers(CharUnits alignment)
: BlockByrefHelpers(alignment) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, true);
CGF.Builder.CreateStore(copy, destField);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddInteger(2);
}
};
class CXXByrefHelpers final : public BlockByrefHelpers {
QualType VarType;
const Expr *CopyExpr;
public:
CXXByrefHelpers(CharUnits alignment, QualType type,
const Expr *copyExpr)
: BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
bool needsCopy() const override { return CopyExpr != nullptr; }
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
if (!CopyExpr) return;
CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
CGF.PushDestructorCleanup(VarType, field);
CGF.PopCleanupBlocks(cleanupDepth);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
}
};
class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
QualType VarType;
public:
NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
: BlockByrefHelpers(alignment), VarType(type) {}
void emitCopy(CodeGenFunction &CGF, Address destField,
Address srcField) override {
CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
CGF.MakeAddrLValue(srcField, VarType));
}
bool needsDispose() const override {
return VarType.isDestructedType();
}
void emitDispose(CodeGenFunction &CGF, Address field) override {
EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
CGF.PopCleanupBlocks(cleanupDepth);
}
void profileImpl(llvm::FoldingSetNodeID &id) const override {
id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
}
};
}
static llvm::Constant *
generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
ASTContext &Context = CGF.getContext();
QualType ReturnTy = Context.VoidTy;
FunctionArgList args;
ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
args.push_back(&Dst);
ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
args.push_back(&Src);
const CGFunctionInfo &FI =
CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__Block_byref_object_copy_", &CGF.CGM.getModule());
SmallVector<QualType, 2> ArgTys;
ArgTys.push_back(Context.VoidPtrTy);
ArgTys.push_back(Context.VoidPtrTy);
CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
CGF.StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
auto AL = ApplyDebugLocation::CreateArtificial(CGF);
if (generator.needsCopy()) {
Address destField = CGF.GetAddrOfLocalVar(&Dst);
destField = Address(CGF.Builder.CreateLoad(destField), CGF.Int8Ty,
byrefInfo.ByrefAlignment);
destField = CGF.Builder.CreateElementBitCast(destField, byrefInfo.Type);
destField =
CGF.emitBlockByrefAddress(destField, byrefInfo, false, "dest-object");
Address srcField = CGF.GetAddrOfLocalVar(&Src);
srcField = Address(CGF.Builder.CreateLoad(srcField), CGF.Int8Ty,
byrefInfo.ByrefAlignment);
srcField = CGF.Builder.CreateElementBitCast(srcField, byrefInfo.Type);
srcField =
CGF.emitBlockByrefAddress(srcField, byrefInfo, false, "src-object");
generator.emitCopy(CGF, destField, srcField);
}
CGF.FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
}
static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
CodeGenFunction CGF(CGM);
return generateByrefCopyHelper(CGF, byrefInfo, generator);
}
static llvm::Constant *
generateByrefDisposeHelper(CodeGenFunction &CGF,
const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
ASTContext &Context = CGF.getContext();
QualType R = Context.VoidTy;
FunctionArgList args;
ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
ImplicitParamDecl::Other);
args.push_back(&Src);
const CGFunctionInfo &FI =
CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn =
llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
"__Block_byref_object_dispose_",
&CGF.CGM.getModule());
SmallVector<QualType, 1> ArgTys;
ArgTys.push_back(Context.VoidPtrTy);
CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
CGF.StartFunction(GlobalDecl(), R, Fn, FI, args);
auto AL = ApplyDebugLocation::CreateArtificial(CGF);
if (generator.needsDispose()) {
Address addr = CGF.GetAddrOfLocalVar(&Src);
addr = Address(CGF.Builder.CreateLoad(addr), CGF.Int8Ty,
byrefInfo.ByrefAlignment);
addr = CGF.Builder.CreateElementBitCast(addr, byrefInfo.Type);
addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
generator.emitDispose(CGF, addr);
}
CGF.FinishFunction();
return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
}
static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
const BlockByrefInfo &byrefInfo,
BlockByrefHelpers &generator) {
CodeGenFunction CGF(CGM);
return generateByrefDisposeHelper(CGF, byrefInfo, generator);
}
template <class T>
static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
T &&generator) {
llvm::FoldingSetNodeID id;
generator.Profile(id);
void *insertPos;
BlockByrefHelpers *node
= CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
if (node) return static_cast<T*>(node);
generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
return copy;
}
BlockByrefHelpers *
CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
const AutoVarEmission &emission) {
const VarDecl &var = *emission.Variable;
assert(var.isEscapingByref() &&
"only escaping __block variables need byref helpers");
QualType type = var.getType();
auto &byrefInfo = getBlockByrefInfo(&var);
CharUnits valueAlignment =
byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
const Expr *copyExpr =
CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
return ::buildByrefHelpers(
CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
}
if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
type.isDestructedType() == QualType::DK_nontrivial_c_struct)
return ::buildByrefHelpers(
CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
if (!type->isObjCRetainableType()) return nullptr;
Qualifiers qs = type.getQualifiers();
if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
switch (lifetime) {
case Qualifiers::OCL_None: llvm_unreachable("impossible");
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
return nullptr;
case Qualifiers::OCL_Weak:
return ::buildByrefHelpers(CGM, byrefInfo,
ARCWeakByrefHelpers(valueAlignment));
case Qualifiers::OCL_Strong:
if (type->isBlockPointerType()) {
return ::buildByrefHelpers(CGM, byrefInfo,
ARCStrongBlockByrefHelpers(valueAlignment));
} else {
return ::buildByrefHelpers(CGM, byrefInfo,
ARCStrongByrefHelpers(valueAlignment));
}
}
llvm_unreachable("fell out of lifetime switch!");
}
BlockFieldFlags flags;
if (type->isBlockPointerType()) {
flags |= BLOCK_FIELD_IS_BLOCK;
} else if (CGM.getContext().isObjCNSObjectType(type) ||
type->isObjCObjectPointerType()) {
flags |= BLOCK_FIELD_IS_OBJECT;
} else {
return nullptr;
}
if (type.isObjCGCWeak())
flags |= BLOCK_FIELD_IS_WEAK;
return ::buildByrefHelpers(CGM, byrefInfo,
ObjectByrefHelpers(valueAlignment, flags));
}
Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
const VarDecl *var,
bool followForward) {
auto &info = getBlockByrefInfo(var);
return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
}
Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
const BlockByrefInfo &info,
bool followForward,
const llvm::Twine &name) {
if (followForward) {
Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.Type,
info.ByrefAlignment);
}
return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
}
const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
auto it = BlockByrefInfos.find(D);
if (it != BlockByrefInfos.end())
return it->second;
llvm::StructType *byrefType =
llvm::StructType::create(getLLVMContext(),
"struct.__block_byref_" + D->getNameAsString());
QualType Ty = D->getType();
CharUnits size;
SmallVector<llvm::Type *, 8> types;
types.push_back(Int8PtrTy);
size += getPointerSize();
types.push_back(llvm::PointerType::getUnqual(byrefType));
size += getPointerSize();
types.push_back(Int32Ty);
size += CharUnits::fromQuantity(4);
types.push_back(Int32Ty);
size += CharUnits::fromQuantity(4);
bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
if (hasCopyAndDispose) {
types.push_back(Int8PtrTy);
size += getPointerSize();
types.push_back(Int8PtrTy);
size += getPointerSize();
}
bool HasByrefExtendedLayout = false;
Qualifiers::ObjCLifetime Lifetime = Qualifiers::OCL_None;
if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
HasByrefExtendedLayout) {
types.push_back(Int8PtrTy);
size += CharUnits::fromQuantity(PointerSizeInBytes);
}
llvm::Type *varTy = ConvertTypeForMem(Ty);
bool packed = false;
CharUnits varAlign = getContext().getDeclAlign(D);
CharUnits varOffset = size.alignTo(varAlign);
if (varOffset != size) {
llvm::Type *paddingTy =
llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
types.push_back(paddingTy);
size = varOffset;
} else if (CGM.getDataLayout().getABITypeAlignment(varTy) >
uint64_t(varAlign.getQuantity())) {
packed = true;
}
types.push_back(varTy);
byrefType->setBody(types, packed);
BlockByrefInfo info;
info.Type = byrefType;
info.FieldIndex = types.size() - 1;
info.FieldOffset = varOffset;
info.ByrefAlignment = std::max(varAlign, getPointerAlign());
auto pair = BlockByrefInfos.insert({D, info});
assert(pair.second && "info was inserted recursively?");
return pair.first->second;
}
void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
Address addr = emission.Addr;
llvm::StructType *byrefType = cast<llvm::StructType>(addr.getElementType());
unsigned nextHeaderIndex = 0;
CharUnits nextHeaderOffset;
auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
const Twine &name) {
auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
Builder.CreateStore(value, fieldAddr);
nextHeaderIndex++;
nextHeaderOffset += fieldSize;
};
BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
const VarDecl &D = *emission.Variable;
QualType type = D.getType();
bool HasByrefExtendedLayout = false;
Qualifiers::ObjCLifetime ByrefLifetime = Qualifiers::OCL_None;
bool ByRefHasLifetime =
getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
llvm::Value *V;
int isa = 0;
if (type.isObjCGCWeak())
isa = 1;
V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
storeHeaderField(V, getPointerSize(), "byref.isa");
storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
BlockFlags flags;
if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
if (ByRefHasLifetime) {
if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
else switch (ByrefLifetime) {
case Qualifiers::OCL_Strong:
flags |= BLOCK_BYREF_LAYOUT_STRONG;
break;
case Qualifiers::OCL_Weak:
flags |= BLOCK_BYREF_LAYOUT_WEAK;
break;
case Qualifiers::OCL_ExplicitNone:
flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
break;
case Qualifiers::OCL_None:
if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
break;
default:
break;
}
if (CGM.getLangOpts().ObjCGCBitmapPrint) {
printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
if (flags & BLOCK_BYREF_LAYOUT_MASK) {
BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
printf(" BLOCK_BYREF_LAYOUT_STRONG");
if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
printf(" BLOCK_BYREF_LAYOUT_WEAK");
if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
}
printf("\n");
}
}
storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
getIntSize(), "byref.flags");
CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
storeHeaderField(V, getIntSize(), "byref.size");
if (helpers) {
storeHeaderField(helpers->CopyHelper, getPointerSize(),
"byref.copyHelper");
storeHeaderField(helpers->DisposeHelper, getPointerSize(),
"byref.disposeHelper");
}
if (ByRefHasLifetime && HasByrefExtendedLayout) {
auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
}
}
void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
bool CanThrow) {
llvm::FunctionCallee F = CGM.getBlockObjectDispose();
llvm::Value *args[] = {
Builder.CreateBitCast(V, Int8PtrTy),
llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
};
if (CanThrow)
EmitRuntimeCallOrInvoke(F, args);
else
EmitNounwindRuntimeCall(F, args);
}
void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
BlockFieldFlags Flags,
bool LoadBlockVarAddr, bool CanThrow) {
EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
CanThrow);
}
static void configureBlocksRuntimeObject(CodeGenModule &CGM,
llvm::Constant *C) {
auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
assert((isa<llvm::Function>(C->stripPointerCasts()) ||
isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
"expected Function or GlobalVariable");
const NamedDecl *ND = nullptr;
for (const auto *Result : DC->lookup(&II))
if ((ND = dyn_cast<FunctionDecl>(Result)) ||
(ND = dyn_cast<VarDecl>(Result)))
break;
if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else {
GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
}
}
if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
GV->hasExternalLinkage())
GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
CGM.setDSOLocal(GV);
}
llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
if (BlockObjectDispose)
return BlockObjectDispose;
llvm::Type *args[] = { Int8PtrTy, Int32Ty };
llvm::FunctionType *fty
= llvm::FunctionType::get(VoidTy, args, false);
BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
configureBlocksRuntimeObject(
*this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
return BlockObjectDispose;
}
llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
if (BlockObjectAssign)
return BlockObjectAssign;
llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
llvm::FunctionType *fty
= llvm::FunctionType::get(VoidTy, args, false);
BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
configureBlocksRuntimeObject(
*this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
return BlockObjectAssign;
}
llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
if (NSConcreteGlobalBlock)
return NSConcreteGlobalBlock;
NSConcreteGlobalBlock = GetOrCreateLLVMGlobal(
"_NSConcreteGlobalBlock", Int8PtrTy, LangAS::Default, nullptr);
configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
return NSConcreteGlobalBlock;
}
llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
if (NSConcreteStackBlock)
return NSConcreteStackBlock;
NSConcreteStackBlock = GetOrCreateLLVMGlobal(
"_NSConcreteStackBlock", Int8PtrTy, LangAS::Default, nullptr);
configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
return NSConcreteStackBlock;
}