15#include "mlir/Dialect/Func/IR/FuncOps.h"
16#include "mlir/IR/Block.h"
17#include "mlir/IR/Builders.h"
18#include "mlir/IR/PatternMatch.h"
19#include "mlir/Interfaces/SideEffectInterfaces.h"
20#include "mlir/Support/LogicalResult.h"
21#include "mlir/Transforms/DialectConversion.h"
22#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
28#include "llvm/ADT/TypeSwitch.h"
34#define GEN_PASS_DEF_CIRFLATTENCFG
35#include "clang/CIR/Dialect/Passes.h.inc"
41void lowerTerminator(mlir::Operation *op, mlir::Block *dest,
42 mlir::PatternRewriter &rewriter) {
43 assert(op->hasTrait<mlir::OpTrait::IsTerminator>() &&
"not a terminator");
44 mlir::OpBuilder::InsertionGuard guard(rewriter);
45 rewriter.setInsertionPoint(op);
46 rewriter.replaceOpWithNewOp<cir::BrOp>(op, dest);
51template <
typename... Ops>
52void walkRegionSkipping(
54 mlir::function_ref<mlir::WalkResult(mlir::Operation *)> callback) {
55 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
57 return mlir::WalkResult::skip();
71static bool hasNestedOpsToFlatten(mlir::Region ®ion) {
73 .walk([](mlir::Operation *op) {
74 if (op->getNumRegions() > 0 && !isa<cir::CaseOp>(op))
75 return mlir::WalkResult::interrupt();
76 return mlir::WalkResult::advance();
87static bool isNonReturningTerminator(mlir::Operation *op) {
88 return mlir::isa_and_nonnull<cir::UnreachableOp, cir::TrapOp>(op);
106static mlir::LogicalResult
107rewriteRegionExitToContinue(mlir::PatternRewriter &rewriter,
108 mlir::Region ®ion, mlir::Block *continueBlock,
109 llvm::StringRef regionDescription) {
110 mlir::Operation *terminator = region.back().getTerminator();
111 rewriter.setInsertionPointToEnd(®ion.back());
112 if (
auto yieldOp = mlir::dyn_cast<cir::YieldOp>(terminator)) {
113 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getArgs(),
115 return mlir::success();
117 if (isNonReturningTerminator(terminator))
118 return mlir::success();
119 terminator->emitError(
"unexpected terminator in ")
121 <<
" region, expected yield, unreachable, or trap, got: "
122 << terminator->getName();
123 return mlir::failure();
126struct CIRFlattenCFGPass :
public impl::CIRFlattenCFGBase<CIRFlattenCFGPass> {
128 CIRFlattenCFGPass() =
default;
129 void runOnOperation()
override;
132struct CIRIfFlattening :
public mlir::OpRewritePattern<cir::IfOp> {
133 using OpRewritePattern<IfOp>::OpRewritePattern;
136 matchAndRewrite(cir::IfOp ifOp,
137 mlir::PatternRewriter &rewriter)
const override {
138 mlir::OpBuilder::InsertionGuard guard(rewriter);
139 mlir::Location loc = ifOp.getLoc();
140 bool emptyElse = ifOp.getElseRegion().empty();
141 mlir::Block *currentBlock = rewriter.getInsertionBlock();
142 mlir::Block *remainingOpsBlock =
143 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
144 mlir::Block *continueBlock;
145 if (ifOp->getResults().empty())
146 continueBlock = remainingOpsBlock;
148 llvm_unreachable(
"NYI");
151 mlir::Block *thenBeforeBody = &ifOp.getThenRegion().front();
152 mlir::Block *thenAfterBody = &ifOp.getThenRegion().back();
153 rewriter.inlineRegionBefore(ifOp.getThenRegion(), continueBlock);
155 rewriter.setInsertionPointToEnd(thenAfterBody);
156 if (
auto thenYieldOp =
157 dyn_cast<cir::YieldOp>(thenAfterBody->getTerminator())) {
158 rewriter.replaceOpWithNewOp<cir::BrOp>(thenYieldOp, thenYieldOp.getArgs(),
162 rewriter.setInsertionPointToEnd(continueBlock);
165 mlir::Block *elseBeforeBody =
nullptr;
166 mlir::Block *elseAfterBody =
nullptr;
168 elseBeforeBody = &ifOp.getElseRegion().front();
169 elseAfterBody = &ifOp.getElseRegion().back();
170 rewriter.inlineRegionBefore(ifOp.getElseRegion(), continueBlock);
172 elseBeforeBody = elseAfterBody = continueBlock;
175 rewriter.setInsertionPointToEnd(currentBlock);
176 cir::BrCondOp::create(rewriter, loc, ifOp.getCondition(), thenBeforeBody,
180 rewriter.setInsertionPointToEnd(elseAfterBody);
181 if (
auto elseYieldOP =
182 dyn_cast<cir::YieldOp>(elseAfterBody->getTerminator())) {
183 rewriter.replaceOpWithNewOp<cir::BrOp>(
184 elseYieldOP, elseYieldOP.getArgs(), continueBlock);
188 rewriter.replaceOp(ifOp, continueBlock->getArguments());
189 return mlir::success();
193class CIRScopeOpFlattening :
public mlir::OpRewritePattern<cir::ScopeOp> {
195 using OpRewritePattern<cir::ScopeOp>::OpRewritePattern;
198 matchAndRewrite(cir::ScopeOp scopeOp,
199 mlir::PatternRewriter &rewriter)
const override {
200 mlir::OpBuilder::InsertionGuard guard(rewriter);
201 mlir::Location loc = scopeOp.getLoc();
209 if (scopeOp.isEmpty()) {
210 rewriter.eraseOp(scopeOp);
211 return mlir::success();
216 mlir::Block *currentBlock = rewriter.getInsertionBlock();
217 mlir::Block *continueBlock =
218 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
219 if (scopeOp.getNumResults() > 0)
220 continueBlock->addArguments(scopeOp.getResultTypes(), loc);
223 mlir::Block *beforeBody = &scopeOp.getScopeRegion().front();
224 mlir::Block *afterBody = &scopeOp.getScopeRegion().back();
225 rewriter.inlineRegionBefore(scopeOp.getScopeRegion(), continueBlock);
228 rewriter.setInsertionPointToEnd(currentBlock);
230 cir::BrOp::create(rewriter, loc, mlir::ValueRange(), beforeBody);
234 rewriter.setInsertionPointToEnd(afterBody);
235 if (
auto yieldOp = dyn_cast<cir::YieldOp>(afterBody->getTerminator())) {
236 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getArgs(),
241 rewriter.replaceOp(scopeOp, continueBlock->getArguments());
243 return mlir::success();
247class CIRSwitchOpFlattening :
public mlir::OpRewritePattern<cir::SwitchOp> {
249 using OpRewritePattern<cir::SwitchOp>::OpRewritePattern;
251 inline void rewriteYieldOp(mlir::PatternRewriter &rewriter,
252 cir::YieldOp yieldOp,
253 mlir::Block *destination)
const {
254 rewriter.setInsertionPoint(yieldOp);
255 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getOperands(),
260 Block *condBrToRangeDestination(cir::SwitchOp op,
261 mlir::PatternRewriter &rewriter,
262 mlir::Block *rangeDestination,
263 mlir::Block *defaultDestination,
264 const APInt &lowerBound,
265 const APInt &upperBound)
const {
266 auto condType = mlir::cast<cir::IntType>(op.getCondition().getType());
267 bool isSigned = condType.isSigned();
269 (isSigned ? lowerBound.sle(upperBound) : lowerBound.ule(upperBound)) &&
271 mlir::Block *resBlock = rewriter.createBlock(defaultDestination);
277 cir::IntType uIntType =
278 cir::IntType::get(op.getContext(), condType.getWidth(),
281 cir::ConstantOp lowerBoundValue = cir::ConstantOp::create(
282 rewriter, op.getLoc(), cir::IntAttr::get(condType, lowerBound));
283 mlir::Value diffValue = cir::SubOp::create(
284 rewriter, op.getLoc(), op.getCondition(), lowerBoundValue);
292 diffValue = cir::CastOp::create(rewriter, op.getLoc(), uIntType,
293 CastKind::integral, diffValue);
295 cir::ConstantOp rangeLength = cir::ConstantOp::create(
296 rewriter, op.getLoc(),
297 cir::IntAttr::get(uIntType, upperBound - lowerBound));
299 cir::CmpOp cmpResult = cir::CmpOp::create(
300 rewriter, op.getLoc(), cir::CmpOpKind::le, diffValue, rangeLength);
301 cir::BrCondOp::create(rewriter, op.getLoc(), cmpResult, rangeDestination,
307 matchAndRewrite(cir::SwitchOp op,
308 mlir::PatternRewriter &rewriter)
const override {
313 for (mlir::Region ®ion : op->getRegions())
314 if (hasNestedOpsToFlatten(region))
315 return mlir::failure();
318 if (op.getBody().hasOneBlock() &&
319 op.getBody().front().without_terminator().empty()) {
320 rewriter.eraseOp(op);
321 return mlir::success();
324 llvm::SmallVector<CaseOp> cases;
325 op.collectCases(cases);
328 mlir::Block *exitBlock = rewriter.splitBlock(
329 rewriter.getBlock(), op->getNextNode()->getIterator());
342 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
343 op.getBody(), [&](mlir::Operation *op) {
344 if (!isa<cir::BreakOp>(op))
345 return mlir::WalkResult::advance();
347 lowerTerminator(op, exitBlock, rewriter);
348 return mlir::WalkResult::skip();
354 cir::YieldOp switchYield =
nullptr;
356 for (mlir::Block &block :
357 llvm::make_early_inc_range(op.getBody().getBlocks()))
358 if (
auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator()))
359 switchYield = yieldOp;
361 assert(!op.getBody().empty());
362 mlir::Block *originalBlock = op->getBlock();
363 mlir::Block *swopBlock =
364 rewriter.splitBlock(originalBlock, op->getIterator());
365 rewriter.inlineRegionBefore(op.getBody(), exitBlock);
368 rewriteYieldOp(rewriter, switchYield, exitBlock);
370 rewriter.setInsertionPointToEnd(originalBlock);
371 cir::BrOp::create(rewriter, op.getLoc(), swopBlock);
376 llvm::SmallVector<mlir::APInt, 8> caseValues;
377 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
378 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
380 llvm::SmallVector<std::pair<APInt, APInt>> rangeValues;
381 llvm::SmallVector<mlir::Block *> rangeDestinations;
382 llvm::SmallVector<mlir::ValueRange> rangeOperands;
385 mlir::Block *defaultDestination = exitBlock;
386 mlir::ValueRange defaultOperands = exitBlock->getArguments();
389 for (cir::CaseOp caseOp : cases) {
390 mlir::Region ®ion = caseOp.getCaseRegion();
393 switch (caseOp.getKind()) {
394 case cir::CaseOpKind::Default:
395 defaultDestination = ®ion.front();
396 defaultOperands = defaultDestination->getArguments();
398 case cir::CaseOpKind::Range:
399 assert(caseOp.getValue().size() == 2 &&
400 "Case range should have 2 case value");
401 rangeValues.push_back(
402 {cast<cir::IntAttr>(caseOp.getValue()[0]).getValue(),
403 cast<cir::IntAttr>(caseOp.getValue()[1]).getValue()});
404 rangeDestinations.push_back(®ion.front());
405 rangeOperands.push_back(rangeDestinations.back()->getArguments());
407 case cir::CaseOpKind::Anyof:
408 case cir::CaseOpKind::Equal:
410 for (
const mlir::Attribute &value : caseOp.getValue()) {
411 caseValues.push_back(cast<cir::IntAttr>(value).getValue());
412 caseDestinations.push_back(®ion.front());
413 caseOperands.push_back(caseDestinations.back()->getArguments());
419 for (mlir::Block &blk : region.getBlocks()) {
420 if (blk.getNumSuccessors())
423 if (
auto yieldOp = dyn_cast<cir::YieldOp>(blk.getTerminator())) {
424 mlir::Operation *nextOp = caseOp->getNextNode();
425 assert(nextOp &&
"caseOp is not expected to be the last op");
426 mlir::Block *oldBlock = nextOp->getBlock();
427 mlir::Block *newBlock =
428 rewriter.splitBlock(oldBlock, nextOp->getIterator());
429 rewriter.setInsertionPointToEnd(oldBlock);
430 cir::BrOp::create(rewriter, nextOp->getLoc(), mlir::ValueRange(),
432 rewriteYieldOp(rewriter, yieldOp, newBlock);
436 mlir::Block *oldBlock = caseOp->getBlock();
437 mlir::Block *newBlock =
438 rewriter.splitBlock(oldBlock, caseOp->getIterator());
440 mlir::Block &entryBlock = caseOp.getCaseRegion().front();
441 rewriter.inlineRegionBefore(caseOp.getCaseRegion(), newBlock);
444 rewriter.setInsertionPointToEnd(oldBlock);
445 cir::BrOp::create(rewriter, caseOp.getLoc(), &entryBlock);
449 for (cir::CaseOp caseOp : cases) {
450 mlir::Block *caseBlock = caseOp->getBlock();
453 if (caseBlock->hasNoPredecessors())
454 rewriter.eraseBlock(caseBlock);
456 rewriter.eraseOp(caseOp);
460 mlir::cast<cir::IntType>(op.getCondition().getType()).isSigned();
461 for (
auto [rangeVal, operand, destination] :
462 llvm::zip(rangeValues, rangeOperands, rangeDestinations)) {
463 APInt lowerBound = rangeVal.first;
464 APInt upperBound = rangeVal.second;
467 if (isSigned ? lowerBound.sgt(upperBound) : lowerBound.ugt(upperBound))
472 constexpr uint64_t kSmallRangeThreshold = 64;
473 APInt rangeSize = upperBound - lowerBound;
474 if (rangeSize.ult(kSmallRangeThreshold)) {
481 APInt caseValue = lowerBound;
482 for (uint64_t n = rangeSize.getZExtValue() + 1; n != 0; --n) {
483 caseValues.push_back(caseValue++);
484 caseOperands.push_back(operand);
485 caseDestinations.push_back(destination);
491 condBrToRangeDestination(op, rewriter, destination,
492 defaultDestination, lowerBound, upperBound);
493 defaultOperands = operand;
497 rewriter.setInsertionPoint(op);
498 rewriter.replaceOpWithNewOp<cir::SwitchFlatOp>(
499 op, op.getCondition(), defaultDestination, defaultOperands, caseValues,
500 caseDestinations, caseOperands);
502 return mlir::success();
506class CIRLoopOpInterfaceFlattening
507 :
public mlir::OpInterfaceRewritePattern<cir::LoopOpInterface> {
509 using mlir::OpInterfaceRewritePattern<
510 cir::LoopOpInterface>::OpInterfaceRewritePattern;
512 inline void lowerConditionOp(cir::ConditionOp op, mlir::Block *body,
514 mlir::PatternRewriter &rewriter)
const {
515 mlir::OpBuilder::InsertionGuard guard(rewriter);
516 rewriter.setInsertionPoint(op);
517 rewriter.replaceOpWithNewOp<cir::BrCondOp>(op, op.getCondition(), body,
522 matchAndRewrite(cir::LoopOpInterface op,
523 mlir::PatternRewriter &rewriter)
const final {
528 for (mlir::Region ®ion : op->getRegions())
529 if (hasNestedOpsToFlatten(region))
530 return mlir::failure();
533 mlir::Block *entry = rewriter.getInsertionBlock();
535 rewriter.splitBlock(entry, rewriter.getInsertionPoint());
536 mlir::Block *cond = &op.getCond().front();
537 mlir::Block *body = &op.getBody().front();
539 (op.maybeGetStep() ? &op.maybeGetStep()->front() :
nullptr);
542 rewriter.setInsertionPointToEnd(entry);
543 cir::BrOp::create(rewriter, op.getLoc(), &op.getEntry().front());
550 cast<cir::ConditionOp>(op.getCond().back().getTerminator());
551 lowerConditionOp(conditionOp, body, exit, rewriter);
558 mlir::Block *dest = (
step ?
step : cond);
559 op.walkBodySkippingNestedLoops([&](mlir::Operation *op) {
560 if (!isa<cir::ContinueOp>(op))
561 return mlir::WalkResult::advance();
563 lowerTerminator(op, dest, rewriter);
564 return mlir::WalkResult::skip();
568 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
569 op.getBody(), [&](mlir::Operation *op) {
570 if (!isa<cir::BreakOp>(op))
571 return mlir::WalkResult::advance();
573 lowerTerminator(op, exit, rewriter);
574 return mlir::WalkResult::skip();
578 for (mlir::Block &blk : op.getBody().getBlocks()) {
579 auto bodyYield = dyn_cast<cir::YieldOp>(blk.getTerminator());
581 lowerTerminator(bodyYield, (
step ?
step : cond), rewriter);
589 cast<cir::YieldOp>(op.maybeGetStep()->back().getTerminator()), cond,
593 rewriter.inlineRegionBefore(op.getCond(), exit);
594 rewriter.inlineRegionBefore(op.getBody(), exit);
596 rewriter.inlineRegionBefore(*op.maybeGetStep(), exit);
598 rewriter.eraseOp(op);
599 return mlir::success();
603class CIRTernaryOpFlattening :
public mlir::OpRewritePattern<cir::TernaryOp> {
605 using OpRewritePattern<cir::TernaryOp>::OpRewritePattern;
608 matchAndRewrite(cir::TernaryOp op,
609 mlir::PatternRewriter &rewriter)
const override {
610 Location loc = op->getLoc();
611 Block *condBlock = rewriter.getInsertionBlock();
612 Block::iterator opPosition = rewriter.getInsertionPoint();
613 Block *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition);
614 llvm::SmallVector<mlir::Location, 2> locs;
617 if (op->getResultTypes().size())
619 Block *continueBlock =
620 rewriter.createBlock(remainingOpsBlock, op->getResultTypes(), locs);
621 cir::BrOp::create(rewriter, loc, remainingOpsBlock);
623 Region &trueRegion = op.getTrueRegion();
624 Block *trueBlock = &trueRegion.front();
629 if (failed(rewriteRegionExitToContinue(rewriter, trueRegion, continueBlock,
631 return mlir::success();
632 rewriter.inlineRegionBefore(trueRegion, continueBlock);
634 Block *falseBlock = continueBlock;
635 Region &falseRegion = op.getFalseRegion();
637 falseBlock = &falseRegion.front();
638 if (failed(rewriteRegionExitToContinue(rewriter, falseRegion, continueBlock,
640 return mlir::success();
641 rewriter.inlineRegionBefore(falseRegion, continueBlock);
643 rewriter.setInsertionPointToEnd(condBlock);
644 cir::BrCondOp::create(rewriter, loc, op.getCond(), trueBlock, falseBlock);
646 rewriter.replaceOp(op, continueBlock->getArguments());
649 return mlir::success();
656static cir::AllocaOp getOrCreateCleanupDestSlot(cir::FuncOp funcOp,
657 mlir::PatternRewriter &rewriter,
658 mlir::Location loc) {
659 mlir::Block &entryBlock = funcOp.getBody().front();
662 auto it = llvm::find_if(entryBlock, [](
auto &op) {
663 return mlir::isa<AllocaOp>(&op) &&
664 mlir::cast<AllocaOp>(&op).getCleanupDestSlot();
666 if (it != entryBlock.end())
667 return mlir::cast<cir::AllocaOp>(*it);
670 mlir::OpBuilder::InsertionGuard guard(rewriter);
671 rewriter.setInsertionPointToStart(&entryBlock);
672 cir::IntType s32Type =
673 cir::IntType::get(rewriter.getContext(), 32,
true);
674 cir::PointerType ptrToS32Type = cir::PointerType::get(s32Type);
676 uint64_t alignment = dataLayout.getAlignment(s32Type,
true).value();
677 auto allocaOp = cir::AllocaOp::create(
678 rewriter, loc, ptrToS32Type,
"__cleanup_dest_slot",
679 rewriter.getI64IntegerAttr(alignment));
680 allocaOp.setCleanupDestSlot(
true);
692collectThrowingCalls(mlir::Region ®ion,
694 region.walk([&](cir::CallOp callOp) {
695 if (!callOp.getNothrow())
696 callsToRewrite.push_back(callOp);
706collectThrows(mlir::Region ®ion,
709 [&](cir::ThrowOp throwOp) { throwsToRewrite.push_back(throwOp); });
718static void collectResumeOps(mlir::Region ®ion,
720 region.walk([&](cir::ResumeOp resumeOp) { resumeOps.push_back(resumeOp); });
726static mlir::Block *buildUnwindBlock(mlir::Block *dest,
bool isCleanupOnly,
728 mlir::Block *insertBefore,
729 mlir::PatternRewriter &rewriter) {
730 mlir::Block *unwindBlock = rewriter.createBlock(insertBefore);
731 rewriter.setInsertionPointToEnd(unwindBlock);
733 cir::EhInitiateOp::create(rewriter, loc, isCleanupOnly);
734 cir::BrOp::create(rewriter, loc, mlir::ValueRange{ehInitiate.getEhToken()},
742static mlir::Block *buildTerminateUnwindBlock(mlir::Location loc,
743 mlir::Block *insertBefore,
744 mlir::PatternRewriter &rewriter) {
745 mlir::Block *terminateBlock = rewriter.createBlock(insertBefore);
746 rewriter.setInsertionPointToEnd(terminateBlock);
747 auto ehInitiate = cir::EhInitiateOp::create(rewriter, loc,
false);
748 cir::EhTerminateOp::create(rewriter, loc, ehInitiate.getEhToken());
749 return terminateBlock;
752class CIRCleanupScopeOpFlattening
753 :
public mlir::OpRewritePattern<cir::CleanupScopeOp> {
755 using OpRewritePattern<cir::CleanupScopeOp>::OpRewritePattern;
760 mlir::Operation *exitOp;
766 CleanupExit(mlir::Operation *op,
int id) : exitOp(op), destinationId(id) {}
776 static bool gotoTargetsLabelInRegion(cir::GotoOp gotoOp,
777 mlir::Region ®ion) {
778 llvm::StringRef targetLabel = gotoOp.getLabel();
780 .walk([&](cir::LabelOp labelOp) {
781 if (labelOp.getLabel() == targetLabel)
782 return mlir::WalkResult::interrupt();
783 return mlir::WalkResult::advance();
806 void collectExits(mlir::Region &cleanupBodyRegion,
807 llvm::SmallVectorImpl<CleanupExit> &exits,
812 for (mlir::Block &block : cleanupBodyRegion) {
813 auto *terminator = block.getTerminator();
814 if (isa<cir::YieldOp>(terminator))
815 exits.emplace_back(terminator, nextId++);
822 auto isGotoThatExitsCleanup = [&](mlir::Operation *op) {
823 auto gotoOp = dyn_cast<cir::GotoOp>(op);
824 return gotoOp && !gotoTargetsLabelInRegion(gotoOp, cleanupBodyRegion);
831 auto collectExitsInLoop = [&](mlir::Operation *loopOp) {
832 loopOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
833 if (isa<cir::ReturnOp>(nestedOp)) {
834 exits.emplace_back(nestedOp, nextId++);
835 }
else if (isGotoThatExitsCleanup(nestedOp)) {
836 exits.emplace_back(nestedOp, nextId++);
838 return mlir::WalkResult::advance();
843 std::function<void(mlir::Region &,
bool)> collectExitsInCleanup;
848 collectExitsInSwitch = [&](mlir::Operation *switchOp) {
849 switchOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
850 if (isa<cir::CleanupScopeOp>(nestedOp)) {
853 collectExitsInCleanup(
854 cast<cir::CleanupScopeOp>(nestedOp).getBodyRegion(),
856 return mlir::WalkResult::skip();
857 }
else if (isa<cir::LoopOpInterface>(nestedOp)) {
858 collectExitsInLoop(nestedOp);
859 return mlir::WalkResult::skip();
860 }
else if (isa<cir::ReturnOp, cir::ContinueOp>(nestedOp)) {
861 exits.emplace_back(nestedOp, nextId++);
862 }
else if (isGotoThatExitsCleanup(nestedOp)) {
863 exits.emplace_back(nestedOp, nextId++);
865 return mlir::WalkResult::advance();
872 collectExitsInCleanup = [&](mlir::Region ®ion,
bool ignoreBreak) {
873 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
880 if (!ignoreBreak && isa<cir::BreakOp>(op)) {
881 exits.emplace_back(op, nextId++);
882 }
else if (isa<cir::ContinueOp, cir::ReturnOp>(op)) {
883 exits.emplace_back(op, nextId++);
884 }
else if (isGotoThatExitsCleanup(op)) {
885 exits.emplace_back(op, nextId++);
886 }
else if (isa<cir::CleanupScopeOp>(op)) {
888 collectExitsInCleanup(cast<cir::CleanupScopeOp>(op).getBodyRegion(),
890 return mlir::WalkResult::skip();
891 }
else if (isa<cir::LoopOpInterface>(op)) {
895 collectExitsInLoop(op);
896 return mlir::WalkResult::skip();
897 }
else if (isa<cir::SwitchOp>(op)) {
901 collectExitsInSwitch(op);
902 return mlir::WalkResult::skip();
904 return mlir::WalkResult::advance();
909 collectExitsInCleanup(cleanupBodyRegion,
false);
915 static bool shouldSinkReturnOperand(mlir::Value operand,
916 cir::ReturnOp returnOp) {
918 mlir::Operation *defOp = operand.getDefiningOp();
924 if (!mlir::isa<cir::ConstantOp, cir::LoadOp>(defOp))
928 if (!operand.hasOneUse())
932 if (defOp->getBlock() != returnOp->getBlock())
935 if (
auto loadOp = mlir::dyn_cast<cir::LoadOp>(defOp)) {
937 mlir::Value ptr = loadOp.getAddr();
938 auto funcOp = returnOp->getParentOfType<cir::FuncOp>();
939 assert(funcOp &&
"Return op has no function parent?");
940 mlir::Block &funcEntryBlock = funcOp.getBody().front();
944 mlir::dyn_cast_if_present<cir::AllocaOp>(ptr.getDefiningOp()))
945 return allocaOp->getBlock() == &funcEntryBlock;
951 assert(mlir::isa<cir::ConstantOp>(defOp) &&
"Expected constant op");
960 getReturnOpOperands(cir::ReturnOp returnOp, mlir::Operation *exitOp,
961 mlir::Location loc, mlir::PatternRewriter &rewriter,
962 llvm::SmallVectorImpl<mlir::Value> &returnValues)
const {
963 mlir::Block *destBlock = rewriter.getInsertionBlock();
964 auto funcOp = exitOp->getParentOfType<cir::FuncOp>();
965 assert(funcOp &&
"Return op has no function parent?");
966 mlir::Block &funcEntryBlock = funcOp.getBody().front();
968 for (mlir::Value operand : returnOp.getOperands()) {
969 if (shouldSinkReturnOperand(operand, returnOp)) {
971 mlir::Operation *defOp = operand.getDefiningOp();
972 rewriter.moveOpBefore(defOp, destBlock, destBlock->end());
973 returnValues.push_back(operand);
976 cir::AllocaOp alloca;
978 mlir::OpBuilder::InsertionGuard guard(rewriter);
979 rewriter.setInsertionPointToStart(&funcEntryBlock);
980 cir::CIRDataLayout dataLayout(
981 funcOp->getParentOfType<mlir::ModuleOp>());
983 dataLayout.getAlignment(operand.getType(),
true).value();
984 cir::PointerType ptrType = cir::PointerType::get(operand.getType());
986 cir::AllocaOp::create(rewriter, loc, ptrType,
"__ret_operand_tmp",
987 rewriter.getI64IntegerAttr(alignment));
992 mlir::OpBuilder::InsertionGuard guard(rewriter);
993 rewriter.setInsertionPoint(exitOp);
994 cir::StoreOp::create(rewriter, loc, operand, alloca,
998 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1002 rewriter.setInsertionPointToEnd(destBlock);
1004 cir::LoadOp::create(rewriter, loc, alloca,
false,
1006 mlir::IntegerAttr(),
1007 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1009 returnValues.push_back(loaded);
1019 createExitTerminator(mlir::Operation *exitOp, mlir::Location loc,
1020 mlir::Block *continueBlock,
1021 mlir::PatternRewriter &rewriter)
const {
1022 return llvm::TypeSwitch<mlir::Operation *, mlir::LogicalResult>(exitOp)
1023 .Case<cir::YieldOp>([&](
auto) {
1025 cir::BrOp::create(rewriter, loc, continueBlock);
1026 return mlir::success();
1028 .Case<cir::BreakOp>([&](
auto) {
1030 cir::BreakOp::create(rewriter, loc);
1031 return mlir::success();
1033 .Case<cir::ContinueOp>([&](
auto) {
1035 cir::ContinueOp::create(rewriter, loc);
1036 return mlir::success();
1038 .Case<cir::ReturnOp>([&](
auto returnOp) {
1042 if (returnOp.hasOperand()) {
1043 llvm::SmallVector<mlir::Value, 2> returnValues;
1044 getReturnOpOperands(returnOp, exitOp, loc, rewriter, returnValues);
1045 cir::ReturnOp::create(rewriter, loc, returnValues);
1047 cir::ReturnOp::create(rewriter, loc);
1049 return mlir::success();
1051 .Case<cir::GotoOp>([&](
auto gotoOp) {
1056 cir::GotoOp::create(rewriter, loc, gotoOp.getLabel());
1057 return mlir::success();
1059 .
Default([&](mlir::Operation *op) {
1060 cir::UnreachableOp::create(rewriter, loc);
1061 return op->emitError(
1062 "unexpected exit operation in cleanup scope body");
1068 static bool regionExitsOnlyFromLastBlock(mlir::Region ®ion) {
1069 for (mlir::Block &block : region) {
1070 if (&block == ®ion.back())
1072 bool expectedTerminator =
1073 llvm::TypeSwitch<mlir::Operation *, bool>(block.getTerminator())
1080 .Case<cir::YieldOp, cir::ReturnOp, cir::ResumeFlatOp,
1081 cir::ContinueOp, cir::BreakOp, cir::GotoOp>(
1082 [](
auto) {
return false; })
1091 .Case<cir::TryCallOp>([](
auto) {
return false; })
1095 .Case<cir::EhDispatchOp>([](
auto) {
return false; })
1099 .Case<cir::SwitchFlatOp>([](
auto) {
return false; })
1102 .Case<cir::UnreachableOp, cir::TrapOp>([](
auto) {
return true; })
1104 .Case<cir::IndirectBrOp>([](
auto) {
return false; })
1107 .Case<cir::BrOp>([&](cir::BrOp brOp) {
1108 assert(brOp.getDest()->getParent() == ®ion &&
1109 "branch destination is not in the region");
1112 .Case<cir::BrCondOp>([&](cir::BrCondOp brCondOp) {
1113 assert(brCondOp.getDestTrue()->getParent() == ®ion &&
1114 "branch destination is not in the region");
1115 assert(brCondOp.getDestFalse()->getParent() == ®ion &&
1116 "branch destination is not in the region");
1120 .
Default([](mlir::Operation *) ->
bool {
1121 llvm_unreachable(
"unexpected terminator in cleanup region");
1123 if (!expectedTerminator)
1151 mlir::Block *buildEHCleanupBlocks(cir::CleanupScopeOp cleanupOp,
1153 mlir::Block *insertBefore,
1154 mlir::PatternRewriter &rewriter)
const {
1155 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1156 "cleanup region has exits in non-final blocks");
1160 mlir::Block *blockBeforeClone =
insertBefore->getPrevNode();
1163 rewriter.cloneRegionBefore(cleanupOp.getCleanupRegion(), insertBefore);
1166 mlir::Block *clonedEntry = blockBeforeClone
1167 ? blockBeforeClone->getNextNode()
1172 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1173 mlir::Value ehToken = clonedEntry->addArgument(ehTokenType, loc);
1175 rewriter.setInsertionPointToStart(clonedEntry);
1176 auto beginCleanup = cir::BeginCleanupOp::create(rewriter, loc, ehToken);
1180 mlir::Block *lastClonedBlock =
insertBefore->getPrevNode();
1182 mlir::dyn_cast<cir::YieldOp>(lastClonedBlock->getTerminator());
1184 rewriter.setInsertionPoint(yieldOp);
1185 cir::EndCleanupOp::create(rewriter, loc, beginCleanup.getCleanupToken());
1186 rewriter.replaceOpWithNewOp<cir::ResumeOp>(yieldOp, ehToken);
1188 cleanupOp->emitError(
"Not yet implemented: cleanup region terminated "
1189 "with non-yield operation");
1218 flattenCleanup(cir::CleanupScopeOp cleanupOp,
1219 llvm::SmallVectorImpl<CleanupExit> &exits,
1220 llvm::SmallVectorImpl<cir::CallOp> &callsToRewrite,
1221 llvm::SmallVectorImpl<cir::ThrowOp> &throwsToRewrite,
1222 llvm::SmallVectorImpl<cir::ResumeOp> &resumeOpsToChain,
1223 mlir::PatternRewriter &rewriter)
const {
1224 mlir::Location loc = cleanupOp.getLoc();
1225 cir::CleanupKind cleanupKind = cleanupOp.getCleanupKind();
1226 bool hasNormalCleanup = cleanupKind == cir::CleanupKind::Normal ||
1227 cleanupKind == cir::CleanupKind::All;
1228 bool hasEHCleanup = cleanupKind == cir::CleanupKind::EH ||
1229 cleanupKind == cir::CleanupKind::All;
1230 bool isMultiExit = exits.size() > 1;
1233 mlir::Block *bodyEntry = &cleanupOp.getBodyRegion().front();
1234 mlir::Block *cleanupEntry = &cleanupOp.getCleanupRegion().front();
1235 mlir::Block *cleanupExit = &cleanupOp.getCleanupRegion().back();
1236 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1237 "cleanup region has exits in non-final blocks");
1238 auto cleanupYield = dyn_cast<cir::YieldOp>(cleanupExit->getTerminator());
1239 if (!cleanupYield) {
1240 return rewriter.notifyMatchFailure(cleanupOp,
1241 "Not yet implemented: cleanup region "
1242 "terminated with non-yield operation");
1249 cir::AllocaOp destSlot;
1250 if (isMultiExit && hasNormalCleanup) {
1251 auto funcOp = cleanupOp->getParentOfType<cir::FuncOp>();
1253 return cleanupOp->emitError(
"cleanup scope not inside a function");
1254 destSlot = getOrCreateCleanupDestSlot(funcOp, rewriter, loc);
1258 mlir::Block *currentBlock = rewriter.getInsertionBlock();
1259 mlir::Block *continueBlock =
1260 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
1270 mlir::Block *unwindBlock =
nullptr;
1271 mlir::Block *ehCleanupEntry =
nullptr;
1272 if (hasEHCleanup && (!callsToRewrite.empty() || !throwsToRewrite.empty() ||
1273 !resumeOpsToChain.empty())) {
1275 buildEHCleanupBlocks(cleanupOp, loc, continueBlock, rewriter);
1279 if (!callsToRewrite.empty() || !throwsToRewrite.empty())
1280 unwindBlock = buildUnwindBlock(ehCleanupEntry,
true,
1281 loc, ehCleanupEntry, rewriter);
1288 mlir::Block *normalInsertPt =
1289 unwindBlock ? unwindBlock
1290 : (ehCleanupEntry ? ehCleanupEntry : continueBlock);
1293 rewriter.inlineRegionBefore(cleanupOp.getBodyRegion(), normalInsertPt);
1296 if (hasNormalCleanup)
1297 rewriter.inlineRegionBefore(cleanupOp.getCleanupRegion(), normalInsertPt);
1300 rewriter.setInsertionPointToEnd(currentBlock);
1301 cir::BrOp::create(rewriter, loc, bodyEntry);
1304 mlir::LogicalResult result = mlir::success();
1305 if (hasNormalCleanup) {
1307 mlir::Block *exitBlock = rewriter.createBlock(normalInsertPt);
1310 rewriter.setInsertionPoint(cleanupYield);
1311 rewriter.replaceOpWithNewOp<cir::BrOp>(cleanupYield, exitBlock);
1315 rewriter.setInsertionPointToEnd(exitBlock);
1319 cir::LoadOp::create(rewriter, loc, destSlot,
false,
1321 mlir::IntegerAttr(),
1322 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1326 llvm::SmallVector<mlir::APInt, 8> caseValues;
1327 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
1328 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
1329 cir::IntType s32Type =
1330 cir::IntType::get(rewriter.getContext(), 32,
true);
1332 for (
const CleanupExit &exit : exits) {
1334 mlir::Block *destBlock = rewriter.createBlock(normalInsertPt);
1335 rewriter.setInsertionPointToEnd(destBlock);
1337 createExitTerminator(exit.exitOp, loc, continueBlock, rewriter);
1340 caseValues.push_back(
1341 llvm::APInt(32,
static_cast<uint64_t>(exit.destinationId),
true));
1342 caseDestinations.push_back(destBlock);
1343 caseOperands.push_back(mlir::ValueRange());
1347 rewriter.setInsertionPoint(exit.exitOp);
1348 auto destIdConst = cir::ConstantOp::create(
1349 rewriter, loc, cir::IntAttr::get(s32Type, exit.destinationId));
1350 cir::StoreOp::create(rewriter, loc, destIdConst, destSlot,
1353 mlir::IntegerAttr(),
1354 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1355 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, cleanupEntry);
1363 if (result.failed())
1368 mlir::Block *defaultBlock = rewriter.createBlock(normalInsertPt);
1369 rewriter.setInsertionPointToEnd(defaultBlock);
1370 cir::UnreachableOp::create(rewriter, loc);
1373 rewriter.setInsertionPointToEnd(exitBlock);
1374 cir::SwitchFlatOp::create(rewriter, loc, slotValue, defaultBlock,
1375 mlir::ValueRange(), caseValues,
1376 caseDestinations, caseOperands);
1380 rewriter.setInsertionPointToEnd(exitBlock);
1381 mlir::Operation *exitOp = exits[0].exitOp;
1382 result = createExitTerminator(exitOp, loc, continueBlock, rewriter);
1385 rewriter.setInsertionPoint(exitOp);
1386 rewriter.replaceOpWithNewOp<cir::BrOp>(exitOp, cleanupEntry);
1391 for (CleanupExit &exit : exits) {
1392 if (isa<cir::YieldOp>(exit.exitOp)) {
1393 rewriter.setInsertionPoint(exit.exitOp);
1394 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, continueBlock);
1405 for (cir::CallOp callOp : callsToRewrite)
1407 for (cir::ThrowOp throwOp : throwsToRewrite)
1417 if (ehCleanupEntry) {
1418 llvm::SmallVector<cir::CallOp> ehCleanupThrowingCalls;
1419 llvm::SmallVector<cir::ThrowOp> ehCleanupThrows;
1420 for (mlir::Block *block = ehCleanupEntry; block != continueBlock;
1421 block = block->getNextNode()) {
1422 block->walk([&](mlir::Operation *op) {
1423 if (
auto callOp = mlir::dyn_cast<cir::CallOp>(op)) {
1424 if (!callOp.getNothrow())
1425 ehCleanupThrowingCalls.push_back(callOp);
1426 }
else if (
auto throwOp = mlir::dyn_cast<cir::ThrowOp>(op)) {
1427 ehCleanupThrows.push_back(throwOp);
1431 if (!ehCleanupThrowingCalls.empty() || !ehCleanupThrows.empty()) {
1432 mlir::Block *terminateBlock =
1433 buildTerminateUnwindBlock(loc, continueBlock, rewriter);
1434 for (cir::CallOp callOp : ehCleanupThrowingCalls)
1436 for (cir::ThrowOp throwOp : ehCleanupThrows)
1446 if (ehCleanupEntry) {
1447 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
1448 mlir::Value ehToken = resumeOp.getEhToken();
1449 rewriter.setInsertionPoint(resumeOp);
1450 rewriter.replaceOpWithNewOp<cir::BrOp>(
1451 resumeOp, mlir::ValueRange{ehToken}, ehCleanupEntry);
1456 rewriter.eraseOp(cleanupOp);
1461 return mlir::success();
1465 matchAndRewrite(cir::CleanupScopeOp cleanupOp,
1466 mlir::PatternRewriter &rewriter)
const override {
1467 mlir::OpBuilder::InsertionGuard guard(rewriter);
1481 llvm::SmallVector<cir::CleanupScopeOp> deadNestedOps;
1482 cleanupOp.getBodyRegion().walk([&](cir::CleanupScopeOp nested) {
1483 if (mlir::isOpTriviallyDead(nested))
1484 deadNestedOps.push_back(nested);
1486 for (
auto op : deadNestedOps)
1487 rewriter.eraseOp(op);
1489 if (hasNestedOpsToFlatten(cleanupOp.getBodyRegion()))
1490 return mlir::failure();
1492 cir::CleanupKind cleanupKind = cleanupOp.getCleanupKind();
1495 llvm::SmallVector<CleanupExit> exits;
1497 collectExits(cleanupOp.getBodyRegion(), exits, nextId);
1499 assert(!exits.empty() &&
"cleanup scope body has no exit");
1504 llvm::SmallVector<cir::CallOp> callsToRewrite;
1505 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
1506 if (cleanupKind != cir::CleanupKind::Normal) {
1507 collectThrowingCalls(cleanupOp.getBodyRegion(), callsToRewrite);
1508 collectThrows(cleanupOp.getBodyRegion(), throwsToRewrite);
1513 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
1514 if (cleanupKind != cir::CleanupKind::Normal)
1515 collectResumeOps(cleanupOp.getBodyRegion(), resumeOpsToChain);
1517 return flattenCleanup(cleanupOp, exits, callsToRewrite, throwsToRewrite,
1518 resumeOpsToChain, rewriter);
1525static cir::EhInitiateOp traceToEhInitiate(mlir::Value ehToken) {
1527 if (
auto initiate = ehToken.getDefiningOp<cir::EhInitiateOp>())
1529 auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(ehToken);
1532 mlir::Block *pred = blockArg.getOwner()->getSinglePredecessor();
1535 auto brOp = mlir::dyn_cast<cir::BrOp>(pred->getTerminator());
1538 ehToken = brOp.getDestOperands()[blockArg.getArgNumber()];
1543class CIRTryOpFlattening :
public mlir::OpRewritePattern<cir::TryOp> {
1545 using OpRewritePattern<cir::TryOp>::OpRewritePattern;
1550 mlir::Block *buildCatchDispatchBlock(
1551 cir::TryOp tryOp, mlir::ArrayAttr handlerTypes,
1552 llvm::SmallVectorImpl<mlir::Block *> &catchHandlerBlocks,
1553 mlir::Location loc, mlir::Block *insertBefore,
1554 mlir::PatternRewriter &rewriter)
const {
1555 mlir::Block *dispatchBlock = rewriter.createBlock(insertBefore);
1556 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1557 mlir::Value ehToken = dispatchBlock->addArgument(ehTokenType, loc);
1559 rewriter.setInsertionPointToEnd(dispatchBlock);
1562 llvm::SmallVector<mlir::Attribute> catchTypeAttrs;
1563 llvm::SmallVector<mlir::Block *> catchDests;
1564 mlir::Block *defaultDest =
nullptr;
1565 bool defaultIsCatchAll =
false;
1567 for (
auto [typeAttr, handlerBlock] :
1568 llvm::zip(handlerTypes, catchHandlerBlocks)) {
1569 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
1570 assert(!defaultDest &&
"multiple catch_all or unwind handlers");
1571 defaultDest = handlerBlock;
1572 defaultIsCatchAll =
true;
1573 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
1574 assert(!defaultDest &&
"multiple catch_all or unwind handlers");
1575 defaultDest = handlerBlock;
1576 defaultIsCatchAll =
false;
1579 catchTypeAttrs.push_back(typeAttr);
1580 catchDests.push_back(handlerBlock);
1584 assert(defaultDest &&
"dispatch must have a catch_all or unwind handler");
1586 mlir::ArrayAttr catchTypesArrayAttr;
1587 if (!catchTypeAttrs.empty())
1588 catchTypesArrayAttr = rewriter.getArrayAttr(catchTypeAttrs);
1590 cir::EhDispatchOp::create(rewriter, loc, ehToken, catchTypesArrayAttr,
1591 defaultIsCatchAll, defaultDest, catchDests);
1593 return dispatchBlock;
1610 mlir::Block *flattenCatchHandler(mlir::Region &handlerRegion,
1611 mlir::Block *continueBlock,
1613 mlir::Block *insertBefore,
1614 mlir::PatternRewriter &rewriter)
const {
1616 mlir::Block *handlerEntry = &handlerRegion.front();
1619 rewriter.inlineRegionBefore(handlerRegion, insertBefore);
1622 for (mlir::Block &block : llvm::make_range(handlerEntry->getIterator(),
1624 if (
auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator())) {
1637 if (mlir::Operation *prev = yieldOp->getPrevNode())
1638 return isa<cir::EndCatchOp>(prev);
1639 llvm::SmallPtrSet<mlir::Block *, 8> visited;
1640 llvm::SmallVector<mlir::Block *, 4> worklist;
1641 for (mlir::Block *pred : block.getPredecessors())
1642 worklist.push_back(pred);
1643 while (!worklist.empty()) {
1644 mlir::Block *b = worklist.pop_back_val();
1645 if (!visited.insert(b).second)
1647 mlir::Operation *term = b->getTerminator();
1648 if (mlir::Operation *prev = term->getPrevNode()) {
1649 if (isa<cir::EndCatchOp>(prev))
1652 for (mlir::Block *pred : b->getPredecessors())
1653 worklist.push_back(pred);
1657 "expected end_catch reachable before yield "
1658 "in catch handler");
1659 rewriter.setInsertionPoint(yieldOp);
1660 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, continueBlock);
1664 return handlerEntry;
1673 mlir::Block *flattenUnwindHandler(mlir::Region &unwindRegion,
1675 mlir::Block *insertBefore,
1676 mlir::PatternRewriter &rewriter)
const {
1677 mlir::Block *unwindEntry = &unwindRegion.front();
1678 rewriter.inlineRegionBefore(unwindRegion, insertBefore);
1683 matchAndRewrite(cir::TryOp tryOp,
1684 mlir::PatternRewriter &rewriter)
const override {
1691 for (mlir::Region ®ion : tryOp->getRegions())
1692 if (hasNestedOpsToFlatten(region))
1693 return mlir::failure();
1695 mlir::OpBuilder::InsertionGuard guard(rewriter);
1696 mlir::Location loc = tryOp.getLoc();
1698 mlir::ArrayAttr handlerTypes = tryOp.getHandlerTypesAttr();
1699 mlir::MutableArrayRef<mlir::Region> handlerRegions =
1700 tryOp.getHandlerRegions();
1703 llvm::SmallVector<cir::CallOp> callsToRewrite;
1704 collectThrowingCalls(tryOp.getTryRegion(), callsToRewrite);
1705 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
1706 collectThrows(tryOp.getTryRegion(), throwsToRewrite);
1709 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
1710 collectResumeOps(tryOp.getTryRegion(), resumeOpsToChain);
1713 mlir::Block *currentBlock = rewriter.getInsertionBlock();
1714 mlir::Block *continueBlock =
1715 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
1718 mlir::Block *bodyEntry = &tryOp.getTryRegion().front();
1719 mlir::Block *bodyExit = &tryOp.getTryRegion().back();
1722 rewriter.inlineRegionBefore(tryOp.getTryRegion(), continueBlock);
1725 rewriter.setInsertionPointToEnd(currentBlock);
1726 cir::BrOp::create(rewriter, loc, bodyEntry);
1729 if (
auto bodyYield = dyn_cast<cir::YieldOp>(bodyExit->getTerminator())) {
1730 rewriter.setInsertionPoint(bodyYield);
1731 rewriter.replaceOpWithNewOp<cir::BrOp>(bodyYield, continueBlock);
1735 if (!handlerTypes || handlerTypes.empty()) {
1736 rewriter.eraseOp(tryOp);
1737 return mlir::success();
1745 if (callsToRewrite.empty() && throwsToRewrite.empty() &&
1746 resumeOpsToChain.empty()) {
1747 for (mlir::Region &handlerRegion : handlerRegions)
1748 for (mlir::Block &block : handlerRegion)
1749 block.dropAllDefinedValueUses();
1750 rewriter.eraseOp(tryOp);
1751 return mlir::success();
1757 llvm::SmallVector<mlir::Block *> catchHandlerBlocks;
1759 for (
const auto &[idx, typeAttr] : llvm::enumerate(handlerTypes)) {
1760 mlir::Region &handlerRegion = handlerRegions[idx];
1762 if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
1763 mlir::Block *unwindEntry =
1764 flattenUnwindHandler(handlerRegion, loc, continueBlock, rewriter);
1765 catchHandlerBlocks.push_back(unwindEntry);
1767 mlir::Block *handlerEntry = flattenCatchHandler(
1768 handlerRegion, continueBlock, loc, continueBlock, rewriter);
1769 catchHandlerBlocks.push_back(handlerEntry);
1774 mlir::Block *dispatchBlock =
1775 buildCatchDispatchBlock(tryOp, handlerTypes, catchHandlerBlocks, loc,
1776 catchHandlerBlocks.front(), rewriter);
1787 handlerTypes && llvm::any_of(handlerTypes, [](mlir::Attribute attr) {
1788 return mlir::isa<cir::CatchAllAttr>(attr);
1797 bool isCleanupOnly = tryOp.getCleanup() && !hasCatchAll;
1798 if (!callsToRewrite.empty() || !throwsToRewrite.empty()) {
1800 mlir::Block *unwindBlock = buildUnwindBlock(dispatchBlock, isCleanupOnly,
1801 loc, dispatchBlock, rewriter);
1803 for (cir::CallOp callOp : callsToRewrite)
1805 for (cir::ThrowOp throwOp : throwsToRewrite)
1812 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
1817 if (
auto ehInitiate = traceToEhInitiate(resumeOp.getEhToken())) {
1818 rewriter.modifyOpInPlace(ehInitiate,
1819 [&] { ehInitiate.removeCleanupAttr(); });
1823 mlir::Value ehToken = resumeOp.getEhToken();
1824 rewriter.setInsertionPoint(resumeOp);
1825 rewriter.replaceOpWithNewOp<cir::BrOp>(
1826 resumeOp, mlir::ValueRange{ehToken}, dispatchBlock);
1830 rewriter.eraseOp(tryOp);
1832 return mlir::success();
1836void populateFlattenCFGPatterns(RewritePatternSet &patterns) {
1838 .add<CIRIfFlattening, CIRLoopOpInterfaceFlattening, CIRScopeOpFlattening,
1839 CIRSwitchOpFlattening, CIRTernaryOpFlattening,
1840 CIRCleanupScopeOpFlattening, CIRTryOpFlattening>(
1841 patterns.getContext());
1844void CIRFlattenCFGPass::runOnOperation() {
1845 RewritePatternSet patterns(&getContext());
1846 populateFlattenCFGPatterns(patterns);
1849 llvm::SmallVector<Operation *, 16> ops;
1850 getOperation()->walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
1851 if (isa<IfOp, ScopeOp, SwitchOp, LoopOpInterface, TernaryOp, CleanupScopeOp,
1857 if (applyOpPatternsGreedily(ops, std::move(patterns)).failed())
1858 signalPassFailure();
1866 return std::make_unique<CIRFlattenCFGPass>();
mlir::Block * replaceThrowWithTryThrow(cir::ThrowOp throwOp, mlir::Block *unwindDest, mlir::Location loc, mlir::RewriterBase &rewriter)
Replace a cir::ThrowOp with a cir::TryThrowOp whose unwind destination is unwindDest.
mlir::Block * replaceCallWithTryCall(cir::CallOp callOp, mlir::Block *unwindDest, mlir::Location loc, mlir::RewriterBase &rewriter)
Replace a cir::CallOp with a cir::TryCallOp whose unwind destination is unwindDest.
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCIRFlattenCFGPass()
int const char * function
float __ovld __cnfn step(float, float)
Returns 0.0 if x < edge, otherwise it returns 1.0.
static bool stackSaveOp()