31class ConditionalEvaluationFinder
33 bool foundConditional =
false;
36 bool found()
const {
return foundConditional; }
38 bool VisitAbstractConditionalOperator(AbstractConditionalOperator *) {
39 foundConditional =
true;
43 bool VisitCXXNewExpr(CXXNewExpr *e) {
48 foundConditional =
true;
55 bool TraverseLambdaExpr(
LambdaExpr *) {
return true; }
56 bool TraverseBlockExpr(BlockExpr *) {
return true; }
57 bool TraverseStmtExpr(StmtExpr *) {
return true; }
73 mlir::Location loc = builder.getUnknownLoc();
86 mlir::OpBuilder::InsertionGuard guard(builder);
88 builder.createFlagStore(loc,
false, active.
getPointer());
92 builder.createFlagStore(loc,
true, active.
getPointer());
103 assert(!cleanup.hasActiveFlag() &&
"cleanup already has active flag?");
104 cleanup.setActiveFlag(activeFlag);
106 cleanup.setTestFlagInNormalCleanup(cleanup.isNormalCleanup());
107 cleanup.setTestFlagInEHCleanup(cleanup.isEHCleanup());
112 : cgf(cgf), cleanups(cgf), scope(
nullptr),
115 assert(subExpr &&
"ExprWithCleanups always has a sub-expression");
116 ConditionalEvaluationFinder finder;
117 finder.TraverseStmt(
const_cast<Expr *
>(subExpr));
118 if (finder.found()) {
119 mlir::Location loc = cgf.builder.getUnknownLoc();
120 cir::CleanupKind cleanupKind = cgf.getLangOpts().Exceptions
121 ? cir::CleanupKind::All
122 : cir::CleanupKind::Normal;
123 scope = cir::CleanupScopeOp::create(
124 cgf.builder, loc, cleanupKind,
126 [&](mlir::OpBuilder &b, mlir::Location loc) {},
128 [&](mlir::OpBuilder &b, mlir::Location loc) {});
129 cgf.builder.setInsertionPointToEnd(&scope.getBodyRegion().front());
137 cir::CleanupScopeOp scope) {
144 auto cur = alloca->getParentOfType<cir::CleanupScopeOp>();
145 while (cur && cur != scope)
146 cur = cur->getParentOfType<cir::CleanupScopeOp>();
153 mlir::Block *parentBlock = scope->getBlock();
154 mlir::OpBuilder::InsertPoint ip =
156 alloca->moveBefore(parentBlock, ip.getPoint());
165 for (mlir::Operation *cur = ptr.getDefiningOp(); cur && cur != alloca;) {
166 auto cast = mlir::dyn_cast<cir::CastOp>(cur);
169 casts.push_back(
cast);
170 cur =
cast.getSrc().getDefiningOp();
173 mlir::Operation *prev = alloca;
174 for (cir::CastOp
cast : llvm::reverse(casts)) {
175 cast->moveAfter(prev);
182 assert(!exited &&
"FullExprCleanupScope::exit called twice");
185 size_t oldSize = deferredCleanupStackSize;
186 bool hasDeferredCleanups =
187 cgf.deferredConditionalCleanupStack.size() > oldSize;
190 cgf.deferredConditionalCleanupStack.truncate(oldSize);
191 cleanups.forceCleanup(valuesToReload);
197 for (mlir::Value *valPtr : valuesToReload) {
198 mlir::Value val = *valPtr;
203 Address temp = cgf.createDefaultAlignTempAlloca(val.getType(), val.getLoc(),
205 tempAllocas.push_back(temp);
206 cgf.builder.createStore(val.getLoc(), val, temp);
212 cleanups.forceCleanupExceptLifetimeExtended();
216 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
217 mlir::Block &lastBodyBlock = scope.getBodyRegion().back();
218 cgf.builder.setInsertionPointToEnd(&lastBodyBlock);
219 if (lastBodyBlock.empty() ||
220 !lastBodyBlock.back().hasTrait<mlir::OpTrait::IsTerminator>())
221 cgf.builder.createYield(scope.getLoc());
228 if (hasDeferredCleanups) {
230 llvm::make_range(cgf.deferredConditionalCleanupStack.begin() + oldSize,
231 cgf.deferredConditionalCleanupStack.end())) {
238 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
239 mlir::Block &cleanupBlock = scope.getCleanupRegion().front();
240 cgf.builder.setInsertionPointToEnd(&cleanupBlock);
242 if (hasDeferredCleanups) {
244 cgf.deferredConditionalCleanupStack.begin() + oldSize,
245 cgf.deferredConditionalCleanupStack.end()))) {
246 if (entry.activeFlag.isValid()) {
254 assert(entry.addr.getUnderlyingAllocaOp() &&
255 (entry.addr.getUnderlyingAllocaOp()->getBlock() ==
256 entry.addr.getPointer().getDefiningOp()->getBlock()) &&
257 "alloca and cast are in different blocks");
259 cgf.builder.createLoad(scope.getLoc(), entry.activeFlag);
261 cgf.builder, scope.getLoc(), flag,
false,
262 [&](mlir::OpBuilder &b, mlir::Location loc) {
263 cgf.emitDestroy(entry.addr, entry.type, entry.destroyer);
264 cgf.builder.createYield(loc);
267 cgf.emitDestroy(entry.addr, entry.type, entry.destroyer);
271 cgf.builder.createYield(scope.getLoc());
274 cgf.deferredConditionalCleanupStack.truncate(oldSize);
275 cgf.builder.setInsertionPointAfter(scope);
281 cleanups.forceLifetimeExtendedCleanups();
284 for (
auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
287 *valPtr = cgf.builder.createLoad(valPtr->getLoc(), addr);
295void EHScopeStack::Cleanup::anchor() {}
299 stable_iterator si = getInnermostNormalCleanup();
300 stable_iterator se = stable_end();
303 if (cleanup.isActive())
305 si = cleanup.getEnclosingNormalCleanup();
311char *EHScopeStack::allocate(
size_t size) {
312 size = llvm::alignTo(size, ScopeStackAlignment);
313 if (!startOfBuffer) {
314 unsigned capacity = llvm::PowerOf2Ceil(std::max<size_t>(size, 1024ul));
315 startOfBuffer = std::make_unique<char[]>(capacity);
316 startOfData = endOfBuffer = startOfBuffer.get() + capacity;
317 }
else if (
static_cast<size_t>(startOfData - startOfBuffer.get()) < size) {
318 unsigned currentCapacity = endOfBuffer - startOfBuffer.get();
319 unsigned usedCapacity =
320 currentCapacity - (startOfData - startOfBuffer.get());
321 unsigned requiredCapacity = usedCapacity + size;
324 unsigned newCapacity = llvm::PowerOf2Ceil(requiredCapacity);
326 std::unique_ptr<char[]> newStartOfBuffer =
327 std::make_unique<char[]>(newCapacity);
328 char *newEndOfBuffer = newStartOfBuffer.get() + newCapacity;
329 char *newStartOfData = newEndOfBuffer - usedCapacity;
330 memcpy(newStartOfData, startOfData, usedCapacity);
331 startOfBuffer.swap(newStartOfBuffer);
332 endOfBuffer = newEndOfBuffer;
333 startOfData = newStartOfData;
336 assert(startOfBuffer.get() + size <= startOfData);
341void EHScopeStack::deallocate(
size_t size) {
342 startOfData += llvm::alignTo(size, ScopeStackAlignment);
350 bool skipCleanupScope =
false;
352 cir::CleanupKind cleanupKind = cir::CleanupKind::All;
353 if (isEHCleanup && cgf->getLangOpts().Exceptions) {
355 isNormalCleanup ? cir::CleanupKind::All : cir::CleanupKind::EH;
361 cleanupKind = cir::CleanupKind::Normal;
363 skipCleanupScope =
true;
369 if (capturingLoopConditionCleanups)
370 skipCleanupScope =
true;
372 cir::CleanupScopeOp cleanupScope =
nullptr;
373 if (!skipCleanupScope) {
374 CIRGenBuilderTy &builder = cgf->getBuilder();
375 mlir::Location loc = builder.getUnknownLoc();
376 cleanupScope = cir::CleanupScopeOp::create(
377 builder, loc, cleanupKind,
379 [&](mlir::OpBuilder &b, mlir::Location loc) {
383 [&](mlir::OpBuilder &b, mlir::Location loc) {
387 builder.setInsertionPointToEnd(&cleanupScope.getBodyRegion().back());
394 if (innermostEHScope != stable_end() &&
398 EHCleanupScope *scope =
new (buffer)
399 EHCleanupScope(isNormalCleanup, isEHCleanup, size, cleanupScope,
400 innermostNormalCleanup, innermostEHScope);
403 innermostNormalCleanup = stable_begin();
406 innermostEHScope = stable_begin();
408 if (isLifetimeMarker)
409 cgf->cgm.errorNYI(
"push lifetime marker cleanup");
412 if (cgf->getLangOpts().EHAsynch && isEHCleanup && !isLifetimeMarker &&
413 cgf->getTarget().getCXXABI().isMicrosoft())
414 cgf->cgm.errorNYI(
"push seh cleanup");
420 assert(!empty() &&
"popping exception stack when not empty");
424 innermostNormalCleanup =
cleanup.getEnclosingNormalCleanup();
425 innermostEHScope =
cleanup.getEnclosingEHScope();
426 deallocate(
cleanup.getAllocatedSize());
428 cir::CleanupScopeOp cleanupScope =
cleanup.getCleanupScopeOp();
430 auto *block = &cleanupScope.getBodyRegion().back();
431 if (!block->mightHaveTerminator()) {
432 mlir::OpBuilder::InsertionGuard guard(cgf->getBuilder());
433 cgf->getBuilder().setInsertionPointToEnd(block);
434 cir::YieldOp::create(cgf->getBuilder(),
435 cgf->getBuilder().getUnknownLoc());
439 mlir::Block *insertBlock = cgf->getBuilder().getInsertionBlock();
441 cleanupScope.getBodyRegion().findAncestorBlockInRegion(*insertBlock))
442 cgf->getBuilder().setInsertionPointAfter(cleanupScope);
450 for (stable_iterator si = getInnermostEHScope(); si != stable_end();) {
451 if (
auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si))) {
452 if (
cleanup->isLifetimeMarker()) {
467 mlir::Operation *dominatingIP) {
471 "cleanup block is neither normal nor EH?");
482 if (!var.isValid()) {
483 mlir::Location loc = builder.getUnknownLoc();
486 loc,
"cleanup.isactive");
489 assert(dominatingIP &&
"no existing variable and no dominating IP!");
492 mlir::Value val = builder.
getBool(
true, loc);
495 mlir::OpBuilder::InsertionGuard guard(builder);
496 builder.setInsertionPoint(dominatingIP);
504 mlir::Location loc = builder.getUnknownLoc();
510 mlir::Operation *dominatingIP) {
511 assert(c !=
ehStack.stable_end() &&
"deactivating bottom of stack?");
513 assert(scope.
isActive() &&
"double deactivation");
517 if (c ==
ehStack.stable_begin() &&
531 Address activeFlag, mlir::Location loc) {
539 cir::IfOp::create(builder, loc, isActive,
542 [&](mlir::OpBuilder &, mlir::Location) {
543 cleanup->emit(cgf, flags);
545 "cleanup ended with no insertion point?");
549 cleanup->emit(cgf, flags);
550 assert(cgf.
haveInsertPoint() &&
"cleanup ended with no insertion point?");
555 EHScopeStack::Cleanup *cleanup,
559 mlir::Block &block = cleanupScope.getCleanupRegion().back();
561 mlir::OpBuilder::InsertionGuard guard(builder);
562 builder.setInsertionPointToStart(&block);
564 emitCleanupBody(cgf, cleanup, flags, activeFlag, cleanupScope.getLoc());
566 mlir::Block &cleanupRegionLastBlock = cleanupScope.getCleanupRegion().back();
567 if (cleanupRegionLastBlock.empty() ||
568 !cleanupRegionLastBlock.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
569 mlir::OpBuilder::InsertionGuard guardCase(builder);
570 builder.setInsertionPointToEnd(&cleanupRegionLastBlock);
581 .walk([&](mlir::Operation *op) {
583 return mlir::WalkResult::interrupt();
584 return mlir::WalkResult::advance();
594 assert(!
ehStack.empty() &&
"cleanup stack is empty!");
604 "missing cir.cleanup.scope for active cleanup");
626 if (forDeactivation && requiresNormalCleanup) {
633 mlir::Location loc = builder.getUnknownLoc();
640 mlir::OpBuilder::InsertionGuard guard(builder);
641 builder.setInsertionPoint(cleanupScope);
642 builder.createFlagStore(loc,
true, activeFlag.
getPointer());
646 assert(builder.getInsertionBlock() ==
647 &cleanupScope.getBodyRegion().back() &&
648 "expected insertion point in cleanup body");
649 builder.createFlagStore(loc,
false, activeFlag.
getPointer());
656 if (requiresEHCleanup)
657 cleanupScope.setCleanupKind(cir::CleanupKind::EH);
658 requiresNormalCleanup =
false;
670 if (!requiresNormalCleanup && !requiresEHCleanup) {
675 mlir::Block &cleanupBlock = cleanupScope.getCleanupRegion().back();
676 if (!cleanupBlock.mightHaveTerminator()) {
677 mlir::OpBuilder::InsertionGuard guard(builder);
678 builder.setInsertionPointToEnd(&cleanupBlock);
679 cir::YieldOp::create(builder, builder.getUnknownLoc());
692 cleanupBufferStack[8 *
sizeof(
void *)];
693 std::unique_ptr<char[]> cleanupBufferHeap;
699 if (cleanupSize <=
sizeof(cleanupBufferStack)) {
700 memcpy(cleanupBufferStack, cleanupSource, cleanupSize);
703 cleanupBufferHeap.reset(
new char[cleanupSize]);
704 memcpy(cleanupBufferHeap.get(), cleanupSource, cleanupSize);
716 Address cleanupActiveFlag = normalActiveFlag.
isValid() ? normalActiveFlag
717 : ehActiveFlag.
isValid() ? ehActiveFlag
725 emitCleanup(*
this, cleanupScope, cleanup, cleanupFlags, cleanupActiveFlag);
734 while (
ehStack.stable_begin() != depth) {
738 "captured loop-condition cleanup should not own a cleanup scope");
756 cleanupBufferStack[8 *
sizeof(
void *)];
757 std::unique_ptr<char[]> cleanupBufferHeap;
760 if (cleanupSize <=
sizeof(cleanupBufferStack)) {
761 memcpy(cleanupBufferStack, cleanupSource, cleanupSize);
764 cleanupBufferHeap.reset(
new char[cleanupSize]);
765 memcpy(cleanupBufferHeap.get(), cleanupSource, cleanupSize);
782 bool requiresCleanup =
false;
783 for (
auto it =
ehStack.begin(), ie =
ehStack.find(oldCleanupStackDepth);
786 requiresCleanup =
true;
795 if (requiresCleanup) {
796 for (mlir::Value *valPtr : valuesToReload) {
797 mlir::Value val = *valPtr;
805 tempAllocas.push_back(temp);
806 builder.createStore(val.getLoc(), val, temp);
812 while (
ehStack.stable_begin() != oldCleanupStackDepth)
816 if (requiresCleanup) {
817 for (
auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
818 mlir::Location loc = valPtr->getLoc();
819 *valPtr = builder.createLoad(loc, addr);
static void setupCleanupBlockDeactivation(CIRGenFunction &cgf, EHScopeStack::stable_iterator c, mlir::Operation *dominatingIP)
The given cleanup block is being deactivated.
static bool bodyHasBranchThroughExits(mlir::Region &bodyRegion)
Check whether a cleanup scope body contains any non-yield exits that branch through the cleanup.
static void hoistAllocaOutOfCleanupScope(CIRGenFunction &cgf, Address addr, cir::CleanupScopeOp scope)
If the alloca that backs addr is currently nested inside the body region of scope,...
static void emitCleanupBody(CIRGenFunction &cgf, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag, mlir::Location loc)
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
cir::ConstantOp getBool(bool state, mlir::Location loc)
cir::StoreOp createFlagStore(mlir::Location loc, bool val, mlir::Value dst)
static OpBuilder::InsertPoint getBestAllocaInsertPoint(mlir::Block *block)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::LoadOp createFlagLoad(mlir::Location loc, mlir::Value addr)
Emit a load from an boolean flag variable.
cir::BoolType getBoolTy()
mlir::Value getPointer() const
cir::AllocaOp getUnderlyingAllocaOp() const
Return the underlying alloca for this address, if any.
FullExprCleanupScope(CIRGenFunction &cgf, const Expr *subExpr)
void exit(ArrayRef< mlir::Value * > valuesToReload={})
llvm::SmallVector< PendingCleanupEntry > lifetimeExtendedCleanupStack
void initFullExprCleanup()
Set up the last cleanup that was pushed as a conditional full-expression cleanup.
mlir::Block * getCurFunctionEntryBlock()
void emitLoopConditionCleanups(EHScopeStack::stable_iterator depth, mlir::Location loc)
Emit the cleanups captured for a loop's condition variable (those pushed above depth while EHScopeSta...
bool isInConditionalBranch() const
void setBeforeOutermostConditional(mlir::Value value, Address addr)
ConditionalEvaluation * outermostConditional
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
llvm::SmallVector< PendingCleanupEntry > deferredConditionalCleanupStack
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
static Destroyer destroyCXXObject
void initFullExprCleanupWithFlag(Address activeFlag)
Address createCleanupActiveFlag()
Create an active flag variable for use with conditional cleanups.
void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup, mlir::Operation *dominatingIP)
Deactivates the given cleanup block.
bool haveInsertPoint() const
True if an insertion point is defined.
void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType, Address ptr)
Emits all the code to cause the given temporary to be cleaned up.
void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth, ArrayRef< mlir::Value * > valuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
CIRGenBuilderTy & getBuilder()
void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry)
Promote a single pending cleanup entry onto the EH scope stack.
void popCleanupBlock(bool forDeactivation=false)
Pop a cleanup block from the stack.
EHScopeStack::stable_iterator currentCleanupStackDepth
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, mlir::OpBuilder::InsertPoint ip={})
This creates a alloca and inserts it into the entry block of the current region.
Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name)
CreateDefaultAlignTempAlloca - This creates an alloca with the default alignment of the corresponding...
A cleanup scope which generates the cleanup blocks lazily.
void setTestFlagInEHCleanup(bool value)
void setTestFlagInNormalCleanup(bool value)
Address getActiveFlag() const
size_t getCleanupSize() const
cir::CleanupScopeOp getCleanupScopeOp()
bool shouldTestFlagInEHCleanup() const
static size_t getSizeForCleanupSize(size_t size)
Gets the size required for a lazy cleanup scope with the given cleanup-data requirements.
bool isNormalCleanup() const
void setActiveFlag(Address var)
void * getCleanupBuffer()
bool shouldTestFlagInNormalCleanup() const
void setActive(bool isActive)
void setIsEHCleanupKind()
void setIsNormalCleanupKind()
Information for lazily generating a cleanup.
A saved depth on the scope stack.
void popCleanup()
Pops a cleanup scope off the stack. This is private to CIRGenCleanup.cpp.
iterator find(stable_iterator savePoint) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
bool requiresCatchOrCleanup() const
stable_iterator getInnermostActiveNormalCleanup() const
bool hasInitializer() const
Whether this new-expression has any initializer at all.
bool shouldNullCheckAllocation() const
True if the allocation result needs to be null-checked.
Represents a C++ temporary.
static CharUnits One()
One - Construct a CharUnits quantity of one.
This represents one expression.
A (possibly-)qualified type.
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
static bool emitLifetimeMarkers()
A cleanup entry that will be promoted onto the EH scope stack at a later point.