clang 24.0.0git
FlattenCFG.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements pass that inlines CIR operations regions into the parent
10// function region.
11//
12//===----------------------------------------------------------------------===//
13
14#include "PassDetail.h"
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/Rewrite/PatternApplicator.h"
21#include "mlir/Support/LogicalResult.h"
22#include "mlir/Transforms/DialectConversion.h"
28#include "llvm/ADT/TypeSwitch.h"
29
30using namespace mlir;
31using namespace cir;
32
33namespace mlir {
34#define GEN_PASS_DEF_CIRFLATTENCFG
35#include "clang/CIR/Dialect/Passes.h.inc"
36} // namespace mlir
37
38namespace {
39
40/// Lowers operations with the terminator trait that have a single successor.
41void lowerTerminator(mlir::Operation *op, mlir::Block *dest,
42 mlir::PatternRewriter &rewriter,
43 mlir::DistinctAttr loopId = {},
44 cir::LoopHintAttr loopHints = {}) {
45 assert(op->hasTrait<mlir::OpTrait::IsTerminator>() && "not a terminator");
46 mlir::OpBuilder::InsertionGuard guard(rewriter);
47 rewriter.setInsertionPoint(op);
48 rewriter.replaceOpWithNewOp<cir::BrOp>(op, mlir::ValueRange{}, loopId,
49 loopHints, dest);
50}
51
52/// Walks a region while skipping operations of type `Ops`. This ensures the
53/// callback is not applied to said operations and its children.
54template <typename... Ops>
55void walkRegionSkipping(
56 mlir::Region &region,
57 mlir::function_ref<mlir::WalkResult(mlir::Operation *)> callback) {
58 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
59 if (isa<Ops...>(op))
60 return mlir::WalkResult::skip();
61 return callback(op);
62 });
63}
64
65/// Check whether a region contains any nested op with regions (i.e. structured
66/// CIR ops that must be flattened before their parent). The greedy pattern
67/// rewriter doesn't guarantee inside-out processing order — when a pattern
68/// fires and modifies IR, newly created ops go onto the worklist and can be
69/// visited in any order. So each flattening pattern must explicitly defer
70/// until its nested structured ops are flat.
71///
72/// CaseOps are excluded because they are structural children of SwitchOp and
73/// are handled by the SwitchOp flattening pattern. Ops from other dialects
74/// (e.g. OpenMP and OpenACC constructs) keep their regions after this pass, so
75/// they never block their parent; CIR ops nested inside them are still found.
76static bool hasNestedOpsToFlatten(mlir::Region &region) {
77 return region
78 .walk([](mlir::Operation *op) {
79 if (op->getNumRegions() > 0 && !isa<cir::CaseOp>(op) &&
80 isa<cir::CIRDialect>(op->getDialect()))
81 return mlir::WalkResult::interrupt();
82 return mlir::WalkResult::advance();
83 })
84 .wasInterrupted();
85}
86
87/// True if `op` is a non-returning terminator — currently `cir.unreachable`
88/// or `cir.trap`. Such terminators don't fall through and don't yield a
89/// value, so when flattening a region they can be left in place rather than
90/// being replaced with a branch to the continuation block. Add new ops here
91/// (e.g. a hypothetical `cir.abort`) so every flattening pattern picks them
92/// up at once.
93static bool isNonReturningTerminator(mlir::Operation *op) {
94 return mlir::isa_and_nonnull<cir::UnreachableOp, cir::TrapOp>(op);
95}
96
97/// Rewrite the terminator of `region`'s exit block so that, after
98/// flattening, control falls through to `continueBlock`. The exit
99/// terminator is expected to be either:
100/// - `cir.yield`: replaced with `cir.br` to `continueBlock` (yielded
101/// args become the destination block's arguments).
102/// - non-returning (`cir.unreachable`, `cir.trap`): left in place — no
103/// branch is needed.
104///
105/// On success returns `success()`. If the terminator is anything else, an
106/// error is emitted and `failure()` is returned. NOTE: callers in this
107/// file have typically already mutated IR (splitBlock / createBlock) by
108/// the time this is invoked, so the MLIR pattern rewriter contract
109/// requires them to still return `success()` from the surrounding
110/// pattern; the `failure()` here just signals "stop trying to wire up
111/// this region".
112static mlir::LogicalResult
113rewriteRegionExitToContinue(mlir::PatternRewriter &rewriter,
114 mlir::Region &region, mlir::Block *continueBlock,
115 llvm::StringRef regionDescription) {
116 mlir::Operation *terminator = region.back().getTerminator();
117 rewriter.setInsertionPointToEnd(&region.back());
118 if (auto yieldOp = mlir::dyn_cast<cir::YieldOp>(terminator)) {
119 rewriter.replaceOpWithNewOp<cir::BrOp>(
120 yieldOp, yieldOp.getArgs(), /*loop_id=*/nullptr, /*loop_hints=*/nullptr,
121 continueBlock);
122 return mlir::success();
123 }
124 if (isNonReturningTerminator(terminator))
125 return mlir::success();
126 terminator->emitError("unexpected terminator in ")
127 << regionDescription
128 << " region, expected yield, unreachable, or trap, got: "
129 << terminator->getName();
130 return mlir::failure();
131}
132
133struct CIRFlattenCFGPass : public impl::CIRFlattenCFGBase<CIRFlattenCFGPass> {
134
135 CIRFlattenCFGPass() = default;
136 void runOnOperation() override;
137};
138
139struct CIRIfFlattening : public mlir::OpRewritePattern<cir::IfOp> {
140 using OpRewritePattern<IfOp>::OpRewritePattern;
141
142 mlir::LogicalResult
143 matchAndRewrite(cir::IfOp ifOp,
144 mlir::PatternRewriter &rewriter) const override {
145 mlir::OpBuilder::InsertionGuard guard(rewriter);
146 mlir::Location loc = ifOp.getLoc();
147 bool emptyElse = ifOp.getElseRegion().empty();
148 mlir::Block *currentBlock = rewriter.getInsertionBlock();
149 mlir::Block *remainingOpsBlock =
150 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
151 mlir::Block *continueBlock;
152 if (ifOp->getResults().empty())
153 continueBlock = remainingOpsBlock;
154 else
155 llvm_unreachable("NYI");
156
157 // Inline the region
158 mlir::Block *thenBeforeBody = &ifOp.getThenRegion().front();
159 mlir::Block *thenAfterBody = &ifOp.getThenRegion().back();
160 rewriter.inlineRegionBefore(ifOp.getThenRegion(), continueBlock);
161
162 rewriter.setInsertionPointToEnd(thenAfterBody);
163 if (auto thenYieldOp =
164 dyn_cast<cir::YieldOp>(thenAfterBody->getTerminator())) {
165 rewriter.replaceOpWithNewOp<cir::BrOp>(
166 thenYieldOp, thenYieldOp.getArgs(),
167 /*loop_id=*/nullptr, /*loop_hints=*/nullptr, continueBlock);
168 }
169
170 rewriter.setInsertionPointToEnd(continueBlock);
171
172 // Has else region: inline it.
173 mlir::Block *elseBeforeBody = nullptr;
174 mlir::Block *elseAfterBody = nullptr;
175 if (!emptyElse) {
176 elseBeforeBody = &ifOp.getElseRegion().front();
177 elseAfterBody = &ifOp.getElseRegion().back();
178 rewriter.inlineRegionBefore(ifOp.getElseRegion(), continueBlock);
179 } else {
180 elseBeforeBody = elseAfterBody = continueBlock;
181 }
182
183 rewriter.setInsertionPointToEnd(currentBlock);
184 cir::BrCondOp::create(rewriter, loc, ifOp.getCondition(), thenBeforeBody,
185 elseBeforeBody);
186
187 if (!emptyElse) {
188 rewriter.setInsertionPointToEnd(elseAfterBody);
189 if (auto elseYieldOP =
190 dyn_cast<cir::YieldOp>(elseAfterBody->getTerminator())) {
191 rewriter.replaceOpWithNewOp<cir::BrOp>(
192 elseYieldOP, elseYieldOP.getArgs(), /*loop_id=*/nullptr,
193 /*loop_hints=*/nullptr, continueBlock);
194 }
195 }
196
197 rewriter.replaceOp(ifOp, continueBlock->getArguments());
198 return mlir::success();
199 }
200};
201
202class CIRScopeOpFlattening : public mlir::OpRewritePattern<cir::ScopeOp> {
203public:
204 using OpRewritePattern<cir::ScopeOp>::OpRewritePattern;
205
206 mlir::LogicalResult
207 matchAndRewrite(cir::ScopeOp scopeOp,
208 mlir::PatternRewriter &rewriter) const override {
209 mlir::OpBuilder::InsertionGuard guard(rewriter);
210 mlir::Location loc = scopeOp.getLoc();
211
212 // Empty scope: just remove it.
213 // TODO: Remove this logic once CIR uses MLIR infrastructure to remove
214 // trivially dead operations. MLIR canonicalizer is too aggressive and we
215 // need to either (a) make sure all our ops model all side-effects and/or
216 // (b) have more options in the canonicalizer in MLIR to temper
217 // aggressiveness level.
218 if (scopeOp.isEmpty()) {
219 rewriter.eraseOp(scopeOp);
220 return mlir::success();
221 }
222
223 // Split the current block before the ScopeOp to create the inlining
224 // point.
225 mlir::Block *currentBlock = rewriter.getInsertionBlock();
226 mlir::Block *continueBlock =
227 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
228 if (scopeOp.getNumResults() > 0)
229 continueBlock->addArguments(scopeOp.getResultTypes(), loc);
230
231 // Inline body region.
232 mlir::Block *beforeBody = &scopeOp.getScopeRegion().front();
233 mlir::Block *afterBody = &scopeOp.getScopeRegion().back();
234 rewriter.inlineRegionBefore(scopeOp.getScopeRegion(), continueBlock);
235
236 // Save stack and then branch into the body of the region.
237 rewriter.setInsertionPointToEnd(currentBlock);
239 cir::BrOp::create(rewriter, loc, mlir::ValueRange(), /*loop_id=*/nullptr,
240 /*loop_hints=*/nullptr, beforeBody);
241
242 // Replace the scopeop return with a branch that jumps out of the body.
243 // Stack restore before leaving the body region.
244 rewriter.setInsertionPointToEnd(afterBody);
245 if (auto yieldOp = dyn_cast<cir::YieldOp>(afterBody->getTerminator())) {
246 rewriter.replaceOpWithNewOp<cir::BrOp>(
247 yieldOp, yieldOp.getArgs(),
248 /*loop_id=*/nullptr, /*loop_hints=*/nullptr, continueBlock);
249 }
250
251 // Replace the op with values return from the body region.
252 rewriter.replaceOp(scopeOp, continueBlock->getArguments());
253
254 return mlir::success();
255 }
256};
257
258class CIRSwitchOpFlattening : public mlir::OpRewritePattern<cir::SwitchOp> {
259public:
260 using OpRewritePattern<cir::SwitchOp>::OpRewritePattern;
261
262 inline void rewriteYieldOp(mlir::PatternRewriter &rewriter,
263 cir::YieldOp yieldOp,
264 mlir::Block *destination) const {
265 rewriter.setInsertionPoint(yieldOp);
266 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getOperands(),
267 /*loop_id=*/nullptr,
268 /*loop_hints=*/nullptr, destination);
269 }
270
271 // Return the new defaultDestination block.
272 Block *condBrToRangeDestination(cir::SwitchOp op,
273 mlir::PatternRewriter &rewriter,
274 mlir::Block *rangeDestination,
275 mlir::Block *defaultDestination,
276 const APInt &lowerBound,
277 const APInt &upperBound) const {
278 auto condType = mlir::cast<cir::IntType>(op.getCondition().getType());
279 bool isSigned = condType.isSigned();
280 assert(
281 (isSigned ? lowerBound.sle(upperBound) : lowerBound.ule(upperBound)) &&
282 "Invalid range");
283 mlir::Block *resBlock = rewriter.createBlock(defaultDestination);
284
285 // Build the range check at the switch operand's width. The classic
286 // `sub x, lo; ule (x - lo), (hi - lo)` idiom is a cyclic-distance test that
287 // is correct for both signed and unsigned switches, so the comparison is
288 // always unsigned.
289 cir::IntType uIntType =
290 cir::IntType::get(op.getContext(), condType.getWidth(),
291 /*isSigned=*/false);
292
293 cir::ConstantOp lowerBoundValue = cir::ConstantOp::create(
294 rewriter, op.getLoc(), cir::IntAttr::get(condType, lowerBound));
295 mlir::Value diffValue = cir::SubOp::create(
296 rewriter, op.getLoc(), op.getCondition(), lowerBoundValue);
297
298 // Use an unsigned comparison to check whether the condition is in range.
299 // cir.cmp takes its signedness from the operand type, so a signed
300 // difference needs a same-width integral cast to the unsigned type (a
301 // signedness reinterpretation) to make the `le` unsigned; an unsigned
302 // difference already has the right type.
303 if (isSigned)
304 diffValue = cir::CastOp::create(rewriter, op.getLoc(), uIntType,
305 CastKind::integral, diffValue);
306
307 cir::ConstantOp rangeLength = cir::ConstantOp::create(
308 rewriter, op.getLoc(),
309 cir::IntAttr::get(uIntType, upperBound - lowerBound));
310
311 cir::CmpOp cmpResult = cir::CmpOp::create(
312 rewriter, op.getLoc(), cir::CmpOpKind::le, diffValue, rangeLength);
313 cir::BrCondOp::create(rewriter, op.getLoc(), cmpResult, rangeDestination,
314 defaultDestination);
315 return resBlock;
316 }
317
318 mlir::LogicalResult
319 matchAndRewrite(cir::SwitchOp op,
320 mlir::PatternRewriter &rewriter) const override {
321 // All nested structured CIR ops must be flattened before the switch.
322 // Break statements inside nested structured ops would create branches to
323 // blocks outside those ops' regions, which is invalid. Fail the match so
324 // the pattern rewriter will process them first.
325 for (mlir::Region &region : op->getRegions())
326 if (hasNestedOpsToFlatten(region))
327 return mlir::failure();
328
329 // Empty switch statement: just erase it.
330 if (op.getBody().hasOneBlock() &&
331 op.getBody().front().without_terminator().empty()) {
332 rewriter.eraseOp(op);
333 return mlir::success();
334 }
335
336 llvm::SmallVector<CaseOp> cases;
337 op.collectCases(cases);
338
339 // Create exit block from the next node of cir.switch op.
340 mlir::Block *exitBlock = rewriter.splitBlock(
341 rewriter.getBlock(), op->getNextNode()->getIterator());
342
343 // We lower cir.switch op in the following process:
344 // 1. Inline the region from the switch op after switch op.
345 // 2. Traverse each cir.case op:
346 // a. Record the entry block, block arguments and condition for every
347 // case. b. Inline the case region after the case op.
348 // 3. Replace the empty cir.switch.op with the new cir.switchflat op by the
349 // recorded block and conditions.
350
351 // First we have to handle the rewrite of all of the 'break' ops to make
352 // sure they now go to the right place, including the ones in the pre-case
353 // blcoks.
354 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
355 op.getBody(), [&](mlir::Operation *op) {
356 if (!isa<cir::BreakOp>(op))
357 return mlir::WalkResult::advance();
358
359 lowerTerminator(op, exitBlock, rewriter);
360 return mlir::WalkResult::skip();
361 });
362
363 // inline everything from switch body between the switch op and the exit
364 // block.
365 {
366 cir::YieldOp switchYield = nullptr;
367 // Clear switch operation.
368 for (mlir::Block &block :
369 llvm::make_early_inc_range(op.getBody().getBlocks()))
370 if (auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator()))
371 switchYield = yieldOp;
372
373 assert(!op.getBody().empty());
374 mlir::Block *originalBlock = op->getBlock();
375 mlir::Block *swopBlock =
376 rewriter.splitBlock(originalBlock, op->getIterator());
377 rewriter.inlineRegionBefore(op.getBody(), exitBlock);
378
379 if (switchYield)
380 rewriteYieldOp(rewriter, switchYield, exitBlock);
381
382 rewriter.setInsertionPointToEnd(originalBlock);
383 cir::BrOp::create(rewriter, op.getLoc(), swopBlock);
384 }
385
386 // Allocate required data structures (disconsider default case in
387 // vectors).
388 llvm::SmallVector<mlir::APInt, 8> caseValues;
389 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
390 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
391
392 llvm::SmallVector<std::pair<APInt, APInt>> rangeValues;
393 llvm::SmallVector<mlir::Block *> rangeDestinations;
394 llvm::SmallVector<mlir::ValueRange> rangeOperands;
395
396 // Initialize default case as optional.
397 mlir::Block *defaultDestination = exitBlock;
398 mlir::ValueRange defaultOperands = exitBlock->getArguments();
399
400 // Digest the case statements values and bodies.
401 for (cir::CaseOp caseOp : cases) {
402 mlir::Region &region = caseOp.getCaseRegion();
403
404 // Found default case: save destination and operands.
405 switch (caseOp.getKind()) {
406 case cir::CaseOpKind::Default:
407 defaultDestination = &region.front();
408 defaultOperands = defaultDestination->getArguments();
409 break;
410 case cir::CaseOpKind::Range:
411 assert(caseOp.getValue().size() == 2 &&
412 "Case range should have 2 case value");
413 rangeValues.push_back(
414 {cast<cir::IntAttr>(caseOp.getValue()[0]).getValue(),
415 cast<cir::IntAttr>(caseOp.getValue()[1]).getValue()});
416 rangeDestinations.push_back(&region.front());
417 rangeOperands.push_back(rangeDestinations.back()->getArguments());
418 break;
419 case cir::CaseOpKind::Anyof:
420 case cir::CaseOpKind::Equal:
421 // AnyOf cases kind can have multiple values, hence the loop below.
422 for (const mlir::Attribute &value : caseOp.getValue()) {
423 caseValues.push_back(cast<cir::IntAttr>(value).getValue());
424 caseDestinations.push_back(&region.front());
425 caseOperands.push_back(caseDestinations.back()->getArguments());
426 }
427 break;
428 }
429
430 // Track fallthrough in cases.
431 for (mlir::Block &blk : region.getBlocks()) {
432 if (blk.getNumSuccessors())
433 continue;
434
435 if (auto yieldOp = dyn_cast<cir::YieldOp>(blk.getTerminator())) {
436 mlir::Operation *nextOp = caseOp->getNextNode();
437 assert(nextOp && "caseOp is not expected to be the last op");
438 mlir::Block *oldBlock = nextOp->getBlock();
439 mlir::Block *newBlock =
440 rewriter.splitBlock(oldBlock, nextOp->getIterator());
441 rewriter.setInsertionPointToEnd(oldBlock);
442 cir::BrOp::create(rewriter, nextOp->getLoc(), mlir::ValueRange(),
443 /*loop_id=*/nullptr, /*loop_hints=*/nullptr,
444 newBlock);
445 rewriteYieldOp(rewriter, yieldOp, newBlock);
446 }
447 }
448
449 mlir::Block *oldBlock = caseOp->getBlock();
450 mlir::Block *newBlock =
451 rewriter.splitBlock(oldBlock, caseOp->getIterator());
452
453 mlir::Block &entryBlock = caseOp.getCaseRegion().front();
454 rewriter.inlineRegionBefore(caseOp.getCaseRegion(), newBlock);
455
456 // Create a branch to the entry of the inlined region.
457 rewriter.setInsertionPointToEnd(oldBlock);
458 cir::BrOp::create(rewriter, caseOp.getLoc(), &entryBlock);
459 }
460
461 // Remove all cases since we've inlined the regions.
462 for (cir::CaseOp caseOp : cases) {
463 mlir::Block *caseBlock = caseOp->getBlock();
464 // Erase the block with no predecessors here to make the generated code
465 // simpler a little bit.
466 if (caseBlock->hasNoPredecessors())
467 rewriter.eraseBlock(caseBlock);
468 else
469 rewriter.eraseOp(caseOp);
470 }
471
472 bool isSigned =
473 mlir::cast<cir::IntType>(op.getCondition().getType()).isSigned();
474 for (auto [rangeVal, operand, destination] :
475 llvm::zip(rangeValues, rangeOperands, rangeDestinations)) {
476 APInt lowerBound = rangeVal.first;
477 APInt upperBound = rangeVal.second;
478
479 // An empty range (lo > hi in the switch's signedness) is unreachable.
480 if (isSigned ? lowerBound.sgt(upperBound) : lowerBound.ugt(upperBound))
481 continue;
482
483 // If range is small, add multiple switch instruction cases.
484 // This magical number is from the original CGStmt code.
485 constexpr uint64_t kSmallRangeThreshold = 64;
486 APInt rangeSize = upperBound - lowerBound;
487 if (rangeSize.ult(kSmallRangeThreshold)) {
488 // Expand into individual cases. rangeSize < kSmallRangeThreshold, so
489 // the inclusive case count (rangeSize + 1) fits in a uint64_t. Drive
490 // termination by the count rather than by comparing caseValue to
491 // upperBound: when upperBound is the type's maximum the final
492 // caseValue++ wraps past the top, which is harmless because the
493 // wrapped value is never used.
494 APInt caseValue = lowerBound;
495 for (uint64_t n = rangeSize.getZExtValue() + 1; n != 0; --n) {
496 caseValues.push_back(caseValue++);
497 caseOperands.push_back(operand);
498 caseDestinations.push_back(destination);
499 }
500 continue;
501 }
502
503 defaultDestination =
504 condBrToRangeDestination(op, rewriter, destination,
505 defaultDestination, lowerBound, upperBound);
506 defaultOperands = operand;
507 }
508
509 // Set switch op to branch to the newly created blocks.
510 rewriter.setInsertionPoint(op);
511 rewriter.replaceOpWithNewOp<cir::SwitchFlatOp>(
512 op, op.getCondition(), defaultDestination, defaultOperands, caseValues,
513 caseDestinations, caseOperands);
514
515 return mlir::success();
516 }
517};
518
519class CIRLoopOpInterfaceFlattening
520 : public mlir::OpInterfaceRewritePattern<cir::LoopOpInterface> {
521public:
522 using mlir::OpInterfaceRewritePattern<
523 cir::LoopOpInterface>::OpInterfaceRewritePattern;
524
525 inline void lowerConditionOp(cir::ConditionOp op, mlir::Block *body,
526 mlir::Block *exit,
527 mlir::PatternRewriter &rewriter,
528 mlir::DistinctAttr loopId = {},
529 cir::LoopHintAttr loopHints = {}) const {
530 mlir::OpBuilder::InsertionGuard guard(rewriter);
531 rewriter.setInsertionPoint(op);
532 rewriter.replaceOpWithNewOp<cir::BrCondOp>(
533 op, op.getCondition(), mlir::ValueRange{}, mlir::ValueRange{}, loopId,
534 loopHints, body, exit);
535 }
536
537 // Rewrite a loop that has a per-iteration cleanup region into a loop whose
538 // condition is always 'true' and whose body is a cir.cleanup.scope enclosing
539 // the original condition, body, and step regions.
540 //
541 // The condition test is sunk to the top of the scope body (a false
542 // result becomes a cir.break out of the loop) and, for a for loop, the step
543 // is appended to the end of the scope body. The loop's cleanup region becomes
544 // the cleanup region of a cir.cleanup.scope enclosing the new body.
545 //
546 // For example, a while loop:
547 //
548 // cir.while { <cond>; cir.condition(%c) }
549 // do { <body> }
550 // cleanup all { <cleanup> }
551 //
552 // becomes:
553 //
554 // cir.while { cir.condition(%true) } do {
555 // cir.cleanup.scope {
556 // <cond>
557 // cir.brcond %c ^body, ^cond_false
558 // ^cond_false:
559 // cir.break
560 // ^body:
561 // <body>
562 // } cleanup all { <cleanup> }
563 // cir.yield
564 // }
565 //
566 // A for loop is the same, except the step region is appended to the scope
567 // body (after the body) and both the body's normal end and any continue are
568 // redirected into the step so that the step runs before the cleanup. The init
569 // section of a for loop is already outside the loop op.
570 mlir::LogicalResult
571 rewriteLoopWithCleanup(cir::LoopOpInterface op,
572 mlir::PatternRewriter &rewriter) const {
573 mlir::Location loc = op.getLoc();
574 mlir::Region *stepRegion = op.maybeGetStep();
575
576 cir::CleanupKindAttr cleanupKind = op.maybeGetCleanupKind();
577 assert(cleanupKind && "loop cleanup region without a cleanup kind");
578
579 mlir::Region &condRegion = op.getCond();
580 mlir::Region &bodyRegion = op.getBody();
581 mlir::Region &cleanupRegion = *op.maybeGetCleanup();
582
583 // The cir.condition is the terminator of the condition region's last block
584 // (there can be more than one block if a nested scope was already
585 // flattened within the condition).
586 auto conditionOp =
587 cast<cir::ConditionOp>(condRegion.back().getTerminator());
588 mlir::Value condVal = conditionOp.getCondition();
589
590 // Capture block references and exit terminators before moving blocks
591 // around. Block pointers stay valid across region inlining because blocks
592 // are reparented, not recreated.
593 mlir::Block *bodyFront = &bodyRegion.front();
594 mlir::Block *stepFront = stepRegion ? &stepRegion->front() : nullptr;
595
596 // For a for loop the body's normal end and any continue must run the step
597 // before the cleanup, so collect them to redirect into the step region. For
598 // a while loop they are genuine cleanup-scope exits and are left untouched.
599 llvm::SmallVector<cir::YieldOp> bodyYieldsToStep;
600 llvm::SmallVector<cir::ContinueOp> continuesToStep;
601 if (stepRegion) {
602 for (mlir::Block &blk : bodyRegion.getBlocks())
603 if (auto y = dyn_cast<cir::YieldOp>(blk.getTerminator()))
604 bodyYieldsToStep.push_back(y);
605 op.walkBodySkippingNestedLoops([&](mlir::Operation *o) {
606 if (auto c = dyn_cast<cir::ContinueOp>(o)) {
607 continuesToStep.push_back(c);
608 return mlir::WalkResult::skip();
609 }
610 return mlir::WalkResult::advance();
611 });
612 }
613
614 // Assemble the per-iteration blocks into the condition region, in
615 // execution order: [ cond blocks..., body blocks..., step blocks... ].
616 rewriter.inlineRegionBefore(bodyRegion, condRegion, condRegion.end());
617 if (stepRegion)
618 rewriter.inlineRegionBefore(*stepRegion, condRegion, condRegion.end());
619
620 // Replace cir.condition(%c) with a conditional branch into the body whose
621 // false edge breaks out of the loop.
622 mlir::Block *breakBlock =
623 rewriter.createBlock(&condRegion, condRegion.end());
624 rewriter.setInsertionPointToEnd(breakBlock);
625 cir::BreakOp::create(rewriter, conditionOp.getLoc());
626
627 rewriter.setInsertionPoint(conditionOp);
628 rewriter.replaceOpWithNewOp<cir::BrCondOp>(conditionOp, condVal, bodyFront,
629 breakBlock);
630
631 // For a for loop, redirect the body's normal end and any continue to the
632 // step. The step's own yield remains the normal end of the iteration.
633 for (cir::YieldOp y : bodyYieldsToStep)
634 lowerTerminator(y, stepFront, rewriter);
635 for (cir::ContinueOp c : continuesToStep)
636 lowerTerminator(c, stepFront, rewriter);
637
638 // Build the trivial loop body: a single cir.cleanup.scope followed by a
639 // yield, in a fresh block (the body region's blocks were moved out above).
640 mlir::Block *newBodyBlock = rewriter.createBlock(&bodyRegion);
641 rewriter.setInsertionPointToEnd(newBodyBlock);
642 auto emitYield = [](mlir::OpBuilder &b, mlir::Location l) {
643 cir::YieldOp::create(b, l);
644 };
645 auto scope = cir::CleanupScopeOp::create(
646 rewriter, loc, cleanupKind.getValue(), emitYield, emitYield);
647 cir::YieldOp::create(rewriter, loc);
648
649 // Move the assembled per-iteration blocks into the scope's body region and
650 // the loop's cleanup blocks into the scope's cleanup region, discarding the
651 // placeholder blocks the builder created.
652 mlir::Block *bodyPlaceholder = &scope.getBodyRegion().front();
653 rewriter.inlineRegionBefore(condRegion, bodyPlaceholder);
654 rewriter.eraseBlock(bodyPlaceholder);
655
656 mlir::Block *cleanupPlaceholder = &scope.getCleanupRegion().front();
657 rewriter.inlineRegionBefore(cleanupRegion, cleanupPlaceholder);
658 rewriter.eraseBlock(cleanupPlaceholder);
659
660 // Rebuild the loop condition region with an always-true condition.
661 mlir::Block *newCondBlock = rewriter.createBlock(&condRegion);
662 rewriter.setInsertionPointToEnd(newCondBlock);
663 mlir::Value trueVal = cir::ConstantOp::create(
664 rewriter, loc, cir::BoolAttr::get(rewriter.getContext(), true));
665 cir::ConditionOp::create(rewriter, loc, trueVal);
666
667 // For a for loop, rebuild the (now empty) step region with a trivial yield.
668 if (stepRegion) {
669 mlir::Block *newStepBlock = rewriter.createBlock(stepRegion);
670 rewriter.setInsertionPointToEnd(newStepBlock);
671 cir::YieldOp::create(rewriter, loc);
672 }
673
674 // Drop the cleanup-kind attribute now that the loop's cleanup region is
675 // empty, so the trivial loop verifies and takes the no-cleanup flattening
676 // path when the greedy driver revisits it.
677 if (auto whileOp = mlir::dyn_cast<cir::WhileOp>(op.getOperation()))
678 whileOp.removeCleanupKindAttr();
679 else if (auto forOp = mlir::dyn_cast<cir::ForOp>(op.getOperation()))
680 forOp.removeCleanupKindAttr();
681
682 return mlir::success();
683 }
684
685 mlir::LogicalResult
686 matchAndRewrite(cir::LoopOpInterface op,
687 mlir::PatternRewriter &rewriter) const final {
688 // All nested structured CIR ops must be flattened before the loop.
689 // Break/continue statements inside nested structured ops would create
690 // branches to blocks outside those ops' regions, which is invalid. Fail
691 // the match so the pattern rewriter will process them first.
692 for (mlir::Region &region : op->getRegions())
693 if (hasNestedOpsToFlatten(region))
694 return mlir::failure();
695
696 // Loops with a per-iteration cleanup region need every iteration-exit edge
697 // routed through that cleanup, including the false-condition exit and any
698 // exceptions that might be thrown from the step region. Rather than trying
699 // to figure out all of the cleanup routing here, we sink the condition into
700 // the body region, hoist the step region (if any) and create a new
701 // cir.cleanup.scope enclosing the body region. A subsequent sweep of the
702 // pass will flatten the cir.cleanup.scope and the loop reusing the normal
703 // handlers.
704 if (op.maybeGetCleanup())
705 return rewriteLoopWithCleanup(op, rewriter);
706
707 // Setup CFG blocks.
708 mlir::Block *entry = rewriter.getInsertionBlock();
709 mlir::Block *exit =
710 rewriter.splitBlock(entry, rewriter.getInsertionPoint());
711 mlir::Block *cond = &op.getCond().front();
712 mlir::Block *body = &op.getBody().front();
713 mlir::Block *step =
714 (op.maybeGetStep() ? &op.maybeGetStep()->front() : nullptr);
715
716 // Setup loop entry branch.
717 mlir::Block *firstBlock = &op.getEntry().front();
718 rewriter.setInsertionPointToEnd(entry);
719 cir::BrOp::create(rewriter, op.getLoc(), firstBlock);
720
721 // We attach the op's loop hints to the ops that break back to the
722 // 'beginning' of the operation. For a while/for it is the condition block,
723 // for a do-while it is the top of the body. All of those ops also get the
724 // loop's id, so that they can be told apart from other loops' hints.
725 cir::LoopHintAttr loopHints = op.getLoopHintsAttr();
726 mlir::DistinctAttr loopId = op.getLoopIdAttr();
727 auto idFor = [&](mlir::Block *target) {
728 return target == firstBlock ? loopId : mlir::DistinctAttr{};
729 };
730 auto hintsFor = [&](mlir::Block *target) {
731 return target == firstBlock ? loopHints : cir::LoopHintAttr{};
732 };
733
734 // Branch from condition region to body or exit. The ConditionOp may not
735 // be in the first block of the condition region if a cleanup scope was
736 // already flattened within it, introducing multiple blocks. The
737 // ConditionOp is always the terminator of the last block.
738 auto conditionOp =
739 cast<cir::ConditionOp>(op.getCond().back().getTerminator());
740 lowerConditionOp(conditionOp, body, exit, rewriter, idFor(body),
741 hintsFor(body));
742
743 // TODO(cir): Remove the walks below. It visits operations unnecessarily.
744 // However, to solve this we would likely need a custom DialectConversion
745 // driver to customize the order that operations are visited.
746
747 // Lower continue statements.
748 mlir::Block *dest = (step ? step : cond);
749 op.walkBodySkippingNestedLoops([&](mlir::Operation *op) {
750 if (!isa<cir::ContinueOp>(op))
751 return mlir::WalkResult::advance();
752
753 lowerTerminator(op, dest, rewriter, idFor(dest), hintsFor(dest));
754 return mlir::WalkResult::skip();
755 });
756
757 // Lower break statements.
758 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
759 op.getBody(), [&](mlir::Operation *op) {
760 if (!isa<cir::BreakOp>(op))
761 return mlir::WalkResult::advance();
762
763 lowerTerminator(op, exit, rewriter);
764 return mlir::WalkResult::skip();
765 });
766
767 // Lower optional body region yield.
768 for (mlir::Block &blk : op.getBody().getBlocks()) {
769 auto bodyYield = dyn_cast<cir::YieldOp>(blk.getTerminator());
770 if (bodyYield)
771 lowerTerminator(bodyYield, dest, rewriter, idFor(dest), hintsFor(dest));
772 }
773
774 // Lower mandatory step region yield. Like the condition region, the
775 // YieldOp may be in the last block rather than the first if a cleanup
776 // scope was already flattened within the step region.
777 if (step)
778 lowerTerminator(
779 cast<cir::YieldOp>(op.maybeGetStep()->back().getTerminator()), cond,
780 rewriter, idFor(cond), hintsFor(cond));
781
782 // Move region contents out of the loop op.
783 rewriter.inlineRegionBefore(op.getCond(), exit);
784 rewriter.inlineRegionBefore(op.getBody(), exit);
785 if (step)
786 rewriter.inlineRegionBefore(*op.maybeGetStep(), exit);
787
788 rewriter.eraseOp(op);
789 return mlir::success();
790 }
791};
792
793class CIRTernaryOpFlattening : public mlir::OpRewritePattern<cir::TernaryOp> {
794public:
795 using OpRewritePattern<cir::TernaryOp>::OpRewritePattern;
796
797 mlir::LogicalResult
798 matchAndRewrite(cir::TernaryOp op,
799 mlir::PatternRewriter &rewriter) const override {
800 Location loc = op->getLoc();
801 Block *condBlock = rewriter.getInsertionBlock();
802 Block::iterator opPosition = rewriter.getInsertionPoint();
803 Block *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition);
804 llvm::SmallVector<mlir::Location, 2> locs;
805 // Ternary result is optional, make sure to populate the location only
806 // when relevant.
807 if (op->getResultTypes().size())
808 locs.push_back(loc);
809 Block *continueBlock =
810 rewriter.createBlock(remainingOpsBlock, op->getResultTypes(), locs);
811 cir::BrOp::create(rewriter, loc, remainingOpsBlock);
812
813 Region &trueRegion = op.getTrueRegion();
814 Block *trueBlock = &trueRegion.front();
815 // Wire up the true region's exit (cir.yield -> br, cir.unreachable /
816 // cir.trap kept as-is). IR has already been modified by splitBlock /
817 // createBlock above, so per the MLIR pattern rewriter contract we must
818 // still return success() if the terminator turns out to be unexpected.
819 if (failed(rewriteRegionExitToContinue(rewriter, trueRegion, continueBlock,
820 "ternary true")))
821 return mlir::success();
822 rewriter.inlineRegionBefore(trueRegion, continueBlock);
823
824 Block *falseBlock = continueBlock;
825 Region &falseRegion = op.getFalseRegion();
826
827 falseBlock = &falseRegion.front();
828 if (failed(rewriteRegionExitToContinue(rewriter, falseRegion, continueBlock,
829 "ternary false")))
830 return mlir::success();
831 rewriter.inlineRegionBefore(falseRegion, continueBlock);
832
833 rewriter.setInsertionPointToEnd(condBlock);
834 cir::BrCondOp::create(rewriter, loc, op.getCond(), trueBlock, falseBlock);
835
836 rewriter.replaceOp(op, continueBlock->getArguments());
837
838 // Ok, we're done!
839 return mlir::success();
840 }
841};
842
843// Get or create the cleanup destination slot for a function. This slot is
844// shared across all cleanup scopes in the function to track which exit path
845// to take after running cleanup code when there are multiple exits.
846static cir::AllocaOp getOrCreateCleanupDestSlot(cir::FuncOp funcOp,
847 mlir::PatternRewriter &rewriter,
848 mlir::Location loc) {
849 mlir::Block &entryBlock = funcOp.getBody().front();
850
851 // Look for an existing cleanup dest slot in the entry block.
852 auto it = llvm::find_if(entryBlock, [](auto &op) {
853 return mlir::isa<AllocaOp>(&op) &&
854 mlir::cast<AllocaOp>(&op).getCleanupDestSlot();
855 });
856 if (it != entryBlock.end())
857 return mlir::cast<cir::AllocaOp>(*it);
858
859 // Create a new cleanup dest slot at the start of the entry block.
860 mlir::OpBuilder::InsertionGuard guard(rewriter);
861 rewriter.setInsertionPointToStart(&entryBlock);
862 cir::IntType s32Type =
863 cir::IntType::get(rewriter.getContext(), 32, /*isSigned=*/true);
864 cir::CIRDataLayout dataLayout(funcOp->getParentOfType<mlir::ModuleOp>());
865 cir::PointerType ptrToS32Type = cir::PointerType::get(
866 s32Type, dataLayout.getAllocaAddrSpace(rewriter.getContext()));
867 uint64_t alignment = dataLayout.getAlignment(s32Type, true).value();
868 auto allocaOp = cir::AllocaOp::create(
869 rewriter, loc, ptrToS32Type, "__cleanup_dest_slot",
870 /*alignment=*/rewriter.getI64IntegerAttr(alignment));
871 allocaOp.setCleanupDestSlot(true);
872 return allocaOp;
873}
874
875/// Shared EH flattening utilities used by both CIRCleanupScopeOpFlattening
876/// and CIRTryOpFlattening.
877
878// Lifetime markers participate in existing EH paths, but do not require an
879// unwind edge on their own. Conservatively treat other cleanup code as real
880// cleanup, including regions with control flow.
881static bool isLifetimeMarkerOnly(mlir::Region &region) {
882 return llvm::hasSingleElement(region) &&
883 llvm::any_of(
884 region.front(),
885 [](mlir::Operation &op) { return isa<cir::LifetimeEndOp>(op); }) &&
886 llvm::all_of(region.front(), [](mlir::Operation &op) {
887 return isa<cir::LifetimeEndOp, cir::YieldOp>(op);
888 });
889}
890
891// Look for an enclosing handler or non-marker EH cleanup that protects this
892// operation. Follow regions, rather than just parent ops: a try does not catch
893// exceptions from its own handlers, and a cleanup does not protect itself.
894static bool hasEnclosingEHRequirement(mlir::Operation *op) {
895 for (mlir::Region *region = op->getParentRegion(); region;
896 region = region->getParentRegion()) {
897 mlir::Operation *parent = region->getParentOp();
898 if (!parent || isa<cir::FuncOp>(parent))
899 break;
900 if (auto tryOp = dyn_cast<cir::TryOp>(parent)) {
901 auto handlers = tryOp.getHandlerTypesAttr();
902 if (region == &tryOp.getTryRegion() && handlers &&
903 llvm::any_of(handlers, [](mlir::Attribute handler) {
904 return !isa<cir::UnwindAttr>(handler);
905 }))
906 return true;
907 } else if (auto cleanupOp = dyn_cast<cir::CleanupScopeOp>(parent)) {
908 if (region == &cleanupOp.getBodyRegion() &&
909 cleanupOp.getCleanupKindAttr().isEH() &&
910 !isLifetimeMarkerOnly(cleanupOp.getCleanupRegion()))
911 return true;
912 } else if (auto loopOp = dyn_cast<cir::LoopOpInterface>(parent)) {
913 // The enclosing loop may not yet have been rewritten to a cleanup scope.
914 mlir::Region *cleanup = loopOp.maybeGetCleanup();
915 if (cleanup && region != cleanup && loopOp.maybeGetCleanupKind().isEH() &&
916 !isLifetimeMarkerOnly(*cleanup))
917 return true;
918 }
919 }
920 return false;
921}
922
923// Collect all function calls in a region that may throw exceptions and need
924// to be replaced with try_call operations. Skips calls marked nothrow.
925// Nested cleanup scopes and try ops are always flattened before their
926// enclosing parents, so there are no nested regions to skip here.
927static void
928collectThrowingCalls(mlir::Region &region,
929 llvm::SmallVectorImpl<cir::CallOp> &callsToRewrite) {
930 region.walk([&](cir::CallOp callOp) {
931 // A musttail call is never an invoke. LLVM has no musttail invoke, and
932 // the tail call replaces the frame the cleanup would have run in, so
933 // there is nothing left to unwind through.
934 if (!callOp.getNothrow() && !callOp.getMusttail())
935 callsToRewrite.push_back(callOp);
936 });
937}
938
939// Collect all cir.throw operations in a region that need to be replaced
940// with cir.try_throw operations so they can unwind through an enclosing
941// cleanup or catch handler. Nested cleanup scopes and try ops are always
942// flattened before their enclosing parents, so there are no nested
943// regions to skip here.
944static void
945collectThrows(mlir::Region &region,
946 llvm::SmallVectorImpl<cir::ThrowOp> &throwsToRewrite) {
947 region.walk(
948 [&](cir::ThrowOp throwOp) { throwsToRewrite.push_back(throwOp); });
949}
950
951// Collect all cir.resume operations in a region that come from
952// already-flattened try or cleanup scope operations. These resume ops need
953// to be chained through this scope's EH handler instead of unwinding
954// directly to the caller. Nested cleanup scopes and try ops are always
955// flattened before their enclosing parents, so there are no nested regions
956// to skip here.
957static void collectResumeOps(mlir::Region &region,
959 region.walk([&](cir::ResumeOp resumeOp) { resumeOps.push_back(resumeOp); });
960}
961
962// Create a shared unwind destination block. The block contains a
963// cir.eh.initiate operation (optionally with the cleanup attribute) and a
964// branch to the given destination block, passing the eh_token.
965static mlir::Block *buildUnwindBlock(mlir::Block *dest, bool isCleanupOnly,
966 mlir::Location loc,
967 mlir::Block *insertBefore,
968 mlir::PatternRewriter &rewriter) {
969 mlir::Block *unwindBlock = rewriter.createBlock(insertBefore);
970 rewriter.setInsertionPointToEnd(unwindBlock);
971 auto ehInitiate =
972 cir::EhInitiateOp::create(rewriter, loc, /*cleanup=*/isCleanupOnly);
973 cir::BrOp::create(rewriter, loc, mlir::ValueRange{ehInitiate.getEhToken()},
974 /*loop_id=*/nullptr, /*loop_hints=*/nullptr, dest);
975 return unwindBlock;
976}
977
978// Create a shared terminate unwind block for throwing calls in EH cleanup
979// regions. When an exception is thrown during cleanup (unwinding), the C++
980// standard requires that std::terminate() be called.
981static mlir::Block *buildTerminateUnwindBlock(mlir::Location loc,
982 mlir::Block *insertBefore,
983 mlir::PatternRewriter &rewriter) {
984 mlir::Block *terminateBlock = rewriter.createBlock(insertBefore);
985 rewriter.setInsertionPointToEnd(terminateBlock);
986 auto ehInitiate = cir::EhInitiateOp::create(rewriter, loc, /*cleanup=*/false);
987 cir::EhTerminateOp::create(rewriter, loc, ehInitiate.getEhToken());
988 return terminateBlock;
989}
990
991class CIRCleanupScopeOpFlattening
992 : public mlir::OpRewritePattern<cir::CleanupScopeOp> {
993public:
994 using OpRewritePattern<cir::CleanupScopeOp>::OpRewritePattern;
995
996 struct CleanupExit {
997 // An operation that exits the cleanup scope (yield, break, continue,
998 // return, etc.)
999 mlir::Operation *exitOp;
1000
1001 // A unique identifier for this exit's destination (used for switch dispatch
1002 // when there are multiple exits).
1003 int destinationId;
1004
1005 CleanupExit(mlir::Operation *op, int id) : exitOp(op), destinationId(id) {}
1006 };
1007
1008 // Determine whether a goto operation transfers control to a label that
1009 // exists somewhere inside the given region (or any of its nested regions).
1010 // Label names are unique within a function, so finding a matching cir.label
1011 // inside the region implies that the goto definitely targets that label and
1012 // therefore stays within the region. If no match is found, the goto either
1013 // exits the region or its target is unknown; in either case the caller must
1014 // treat it as exiting the region.
1015 static bool gotoTargetsLabelInRegion(cir::GotoOp gotoOp,
1016 mlir::Region &region) {
1017 llvm::StringRef targetLabel = gotoOp.getLabel();
1018 return region
1019 .walk([&](cir::LabelOp labelOp) {
1020 if (labelOp.getLabel() == targetLabel)
1021 return mlir::WalkResult::interrupt();
1022 return mlir::WalkResult::advance();
1023 })
1024 .wasInterrupted();
1025 }
1026
1027 // Collect all operations that exit a cleanup scope body. Return, goto, break,
1028 // and continue can all require branches through the cleanup region. When a
1029 // loop is encountered, only return and goto are collected because break and
1030 // continue are handled by the loop and stay within the cleanup scope. When a
1031 // switch is encountered, return, goto and continue are collected because they
1032 // may all branch through the cleanup, but break is local to the switch. When
1033 // a nested cleanup scope is encountered, we recursively collect exits since
1034 // any return, goto, break, or continue from the nested cleanup will also
1035 // branch through the outer cleanup.
1036 //
1037 // A goto is only treated as an exit if its target label is not somewhere
1038 // inside the cleanup body region. Gotos whose target label is within the
1039 // cleanup body stay inside the cleanup scope and need no special handling
1040 // during flattening; they are simply inlined along with the rest of the
1041 // body region.
1042 //
1043 // A musttail return is likewise not an exit. It leaves the function
1044 // directly without running any cleanup, which is what the tail call means:
1045 // the frame those cleanups would run in no longer exists. CIRGen only emits
1046 // one when every cleanup it skips is redundant before a return.
1047 //
1048 // This function assigns unique destination IDs to each exit, which are
1049 // used when multi-exit cleanup scopes are flattened.
1050 void collectExits(mlir::Region &cleanupBodyRegion,
1051 llvm::SmallVectorImpl<CleanupExit> &exits,
1052 int &nextId) const {
1053 // Collect yield terminators from the body region. We do this separately
1054 // because yields in nested operations, including those in nested cleanup
1055 // scopes, won't branch through the outer cleanup region.
1056 for (mlir::Block &block : cleanupBodyRegion) {
1057 auto *terminator = block.getTerminator();
1058 if (isa<cir::YieldOp>(terminator))
1059 exits.emplace_back(terminator, nextId++);
1060 }
1061
1062 // Helper to decide whether an op is a goto that needs to be treated as an
1063 // exit from the cleanup scope being flattened. If op is a goto and targets
1064 // a label inside the cleanup body region, control stays within the cleanup
1065 // and we leave the goto in place.
1066 auto isGotoThatExitsCleanup = [&](mlir::Operation *op) {
1067 auto gotoOp = dyn_cast<cir::GotoOp>(op);
1068 return gotoOp && !gotoTargetsLabelInRegion(gotoOp, cleanupBodyRegion);
1069 };
1070
1071 // Helper to decide whether a return branches through the cleanup. The
1072 // return that completes a musttail call does not. LLVM requires the two
1073 // to stay adjacent, so it cannot be rewritten into a store and a branch
1074 // to the cleanup. CIRGen emits the pair adjacently in the same block, and
1075 // the predecessor is only ever a cir.call, never a cir.try_call, since a
1076 // try_call terminates its block and so cannot be followed by a return.
1077 auto isReturnThatExitsCleanup = [](mlir::Operation *op) {
1078 if (!isa<cir::ReturnOp>(op))
1079 return false;
1080 auto callOp = dyn_cast_if_present<cir::CallOp>(op->getPrevNode());
1081 return !callOp || !callOp.getMusttail();
1082 };
1083
1084 // Lambda to walk a loop and collect only returns and gotos.
1085 // Break and continue inside loops are handled by the loop itself.
1086 // Loops don't require special handling for nested switch or cleanup scopes
1087 // because break and continue never branch out of the loop.
1088 auto collectExitsInLoop = [&](mlir::Operation *loopOp) {
1089 loopOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
1090 if (isa<cir::CoroCleanupOp>(nestedOp) ||
1091 isReturnThatExitsCleanup(nestedOp) ||
1092 isGotoThatExitsCleanup(nestedOp)) {
1093 exits.emplace_back(nestedOp, nextId++);
1094 }
1095 return mlir::WalkResult::advance();
1096 });
1097 };
1098
1099 // Forward declaration for mutual recursion.
1100 std::function<void(mlir::Region &, bool)> collectExitsInCleanup;
1101 std::function<void(mlir::Operation *)> collectExitsInSwitch;
1102
1103 // Lambda to collect exits from a switch. Collects return/goto/continue but
1104 // not break (handled by switch). For nested loops/cleanups, recurses.
1105 collectExitsInSwitch = [&](mlir::Operation *switchOp) {
1106 switchOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
1107 if (isa<cir::CleanupScopeOp>(nestedOp)) {
1108 // Walk the nested cleanup, but ignore break statements because they
1109 // will be handled by the switch we are currently walking.
1110 collectExitsInCleanup(
1111 cast<cir::CleanupScopeOp>(nestedOp).getBodyRegion(),
1112 /*ignoreBreak=*/true);
1113 return mlir::WalkResult::skip();
1114 } else if (isa<cir::LoopOpInterface>(nestedOp)) {
1115 collectExitsInLoop(nestedOp);
1116 return mlir::WalkResult::skip();
1117 } else if (isa<cir::ContinueOp, cir::CoReturnOp, cir::CoroCleanupOp>(
1118 nestedOp) ||
1119 isReturnThatExitsCleanup(nestedOp) ||
1120 isGotoThatExitsCleanup(nestedOp)) {
1121 exits.emplace_back(nestedOp, nextId++);
1122 }
1123 return mlir::WalkResult::advance();
1124 });
1125 };
1126
1127 // Lambda to collect exits from a cleanup scope body region. This collects
1128 // break (optionally), continue, return, and goto, handling nested loops,
1129 // switches, and cleanups appropriately.
1130 collectExitsInCleanup = [&](mlir::Region &region, bool ignoreBreak) {
1131 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1132 // We need special handling for break statements because if this cleanup
1133 // scope was nested within a switch op, break will be handled by the
1134 // switch operation and therefore won't exit the cleanup scope enclosing
1135 // the switch. We're only collecting exits from the cleanup that started
1136 // this walk. Exits from nested cleanups will be handled when we flatten
1137 // the nested cleanup.
1138 if (!ignoreBreak && isa<cir::BreakOp>(op)) {
1139 exits.emplace_back(op, nextId++);
1140 } else if (isa<cir::ContinueOp, cir::CoReturnOp, cir::CoroCleanupOp>(
1141 op) ||
1142 isReturnThatExitsCleanup(op) || isGotoThatExitsCleanup(op)) {
1143 exits.emplace_back(op, nextId++);
1144 } else if (isa<cir::CleanupScopeOp>(op)) {
1145 // Recurse into nested cleanup's body region.
1146 collectExitsInCleanup(cast<cir::CleanupScopeOp>(op).getBodyRegion(),
1147 /*ignoreBreak=*/ignoreBreak);
1148 return mlir::WalkResult::skip();
1149 } else if (isa<cir::LoopOpInterface>(op)) {
1150 // This kicks off a separate walk rather than continuing to dig deeper
1151 // in the current walk because we need to handle break and continue
1152 // differently inside loops.
1153 collectExitsInLoop(op);
1154 return mlir::WalkResult::skip();
1155 } else if (isa<cir::SwitchOp>(op)) {
1156 // This kicks off a separate walk rather than continuing to dig deeper
1157 // in the current walk because we need to handle break differently
1158 // inside switches.
1159 collectExitsInSwitch(op);
1160 return mlir::WalkResult::skip();
1161 }
1162 return mlir::WalkResult::advance();
1163 });
1164 };
1165
1166 // Collect exits from the body region.
1167 collectExitsInCleanup(cleanupBodyRegion, /*ignoreBreak=*/false);
1168 }
1169
1170 // Whether the slot \p alloca read by \p loadOp may change before the end of
1171 // \p cleanupRegion: its address escapes, or a store or lifetime marker on it
1172 // runs after the load, in the load's block or in the cleanup.
1173 static bool slotMayChangeBeforeCleanupEnd(cir::AllocaOp alloca,
1174 cir::LoadOp loadOp,
1175 mlir::Region &cleanupRegion) {
1176 mlir::Block *loadBlock = loadOp->getBlock();
1177 return llvm::any_of(alloca->getUsers(), [&](mlir::Operation *user) {
1178 // Reads never change the slot.
1179 if (mlir::isa<cir::LoadOp>(user))
1180 return false;
1181
1182 // Storing the address, or using it in anything but a store to the slot
1183 // or a lifetime marker, lets it escape.
1184 if (auto storeOp = mlir::dyn_cast<cir::StoreOp>(user)) {
1185 if (storeOp.getValue() == alloca.getResult())
1186 return true;
1187 } else if (!mlir::isa<cir::LifetimeStartOp, cir::LifetimeEndOp>(user)) {
1188 return true;
1189 }
1190
1191 // A store or lifetime marker only matters if it runs after the load.
1192 if (cleanupRegion.isAncestor(user->getParentRegion()))
1193 return true;
1194 mlir::Operation *userInBlock = loadBlock->findAncestorOpInBlock(*user);
1195 return userInBlock && loadOp->isBeforeInBlock(userInBlock);
1196 });
1197 }
1198
1199 // Check if an operand's defining op should be moved to the destination block.
1200 // We only sink constants and simple loads. Anything else should be saved
1201 // to a temporary alloca and reloaded at the destination block. This must be
1202 // called before \p cleanupRegion is inlined.
1203 static bool shouldSinkReturnOperand(mlir::Value operand,
1204 cir::ReturnOp returnOp,
1205 mlir::Region &cleanupRegion) {
1206 // Block arguments can't be moved
1207 mlir::Operation *defOp = operand.getDefiningOp();
1208 if (!defOp)
1209 return false;
1210
1211 // Only move constants and loads to the dispatch block. For anything else,
1212 // we'll store to a temporary and reload in the dispatch block.
1213 if (!mlir::isa<cir::ConstantOp, cir::LoadOp>(defOp))
1214 return false;
1215
1216 // Check if the return is the only user
1217 if (!operand.hasOneUse())
1218 return false;
1219
1220 // Only move ops that are in the same block as the return.
1221 if (defOp->getBlock() != returnOp->getBlock())
1222 return false;
1223
1224 if (auto loadOp = mlir::dyn_cast<cir::LoadOp>(defOp)) {
1225 // A volatile or atomic load must happen before the cleanup runs.
1226 if (loadOp.isVolatileOrAtomic())
1227 return false;
1228
1229 // Only attempt to move loads of allocas in the entry block.
1230 mlir::Value ptr = loadOp.getAddr();
1231 auto funcOp = returnOp->getParentOfType<cir::FuncOp>();
1232 assert(funcOp && "Return op has no function parent?");
1233 mlir::Block &funcEntryBlock = funcOp.getBody().front();
1234
1235 // Check if it's an alloca in the function entry block that keeps its
1236 // value until the cleanup is done.
1237 auto allocaOp =
1238 mlir::dyn_cast_if_present<cir::AllocaOp>(ptr.getDefiningOp());
1239 return allocaOp && allocaOp->getBlock() == &funcEntryBlock &&
1240 !slotMayChangeBeforeCleanupEnd(allocaOp, loadOp, cleanupRegion);
1241 }
1242
1243 // Make sure we only fall through to here with constants.
1244 assert(mlir::isa<cir::ConstantOp>(defOp) && "Expected constant op");
1245 return true;
1246 }
1247
1248 // For returns with operands in cleanup dispatch blocks, the operands may not
1249 // dominate the dispatch block. This function handles that by either sinking
1250 // the operand's defining op to the dispatch block (for the operands in
1251 // \p sinkableOperands) or by storing to a temporary alloca and reloading it.
1252 void getReturnOpOperands(
1253 cir::ReturnOp returnOp, mlir::Operation *exitOp, mlir::Location loc,
1254 const llvm::SmallPtrSetImpl<mlir::Operation *> &sinkableOperands,
1255 mlir::PatternRewriter &rewriter,
1256 llvm::SmallVectorImpl<mlir::Value> &returnValues) const {
1257 mlir::Block *destBlock = rewriter.getInsertionBlock();
1258 auto funcOp = exitOp->getParentOfType<cir::FuncOp>();
1259 assert(funcOp && "Return op has no function parent?");
1260 mlir::Block &funcEntryBlock = funcOp.getBody().front();
1261
1262 for (mlir::Value operand : returnOp.getOperands()) {
1263 if (sinkableOperands.contains(operand.getDefiningOp())) {
1264 // Sink the defining op to the dispatch block.
1265 mlir::Operation *defOp = operand.getDefiningOp();
1266 rewriter.moveOpBefore(defOp, destBlock, destBlock->end());
1267 returnValues.push_back(operand);
1268 } else {
1269 // Create an alloca in the function entry block.
1270 cir::AllocaOp alloca;
1271 {
1272 mlir::OpBuilder::InsertionGuard guard(rewriter);
1273 rewriter.setInsertionPointToStart(&funcEntryBlock);
1274 cir::CIRDataLayout dataLayout(
1275 funcOp->getParentOfType<mlir::ModuleOp>());
1276 uint64_t alignment =
1277 dataLayout.getAlignment(operand.getType(), true).value();
1278 cir::PointerType ptrType = cir::PointerType::get(
1279 operand.getType(),
1280 dataLayout.getAllocaAddrSpace(rewriter.getContext()));
1281 alloca =
1282 cir::AllocaOp::create(rewriter, loc, ptrType, "__ret_operand_tmp",
1283 rewriter.getI64IntegerAttr(alignment));
1284 }
1285
1286 // Store the operand value at the original return location.
1287 {
1288 mlir::OpBuilder::InsertionGuard guard(rewriter);
1289 rewriter.setInsertionPoint(exitOp);
1290 cir::StoreOp::create(rewriter, loc, operand, alloca,
1291 /*isVolatile=*/false,
1292 /*isNontemporal=*/false,
1293 /*alignment=*/mlir::IntegerAttr(),
1294 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1295 }
1296
1297 // Reload the value from the temporary alloca in the destination block.
1298 rewriter.setInsertionPointToEnd(destBlock);
1299 auto loaded =
1300 cir::LoadOp::create(rewriter, loc, alloca, /*isDeref=*/false,
1301 /*isVolatile=*/false, /*isNontemporal=*/false,
1302 /*alignment=*/mlir::IntegerAttr(),
1303 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1304 /*invariant=*/false);
1305 returnValues.push_back(loaded);
1306 }
1307 }
1308 }
1309
1310 // Create the appropriate terminator for an exit operation in the dispatch
1311 // block. For return ops with operands, this handles the dominance issue by
1312 // either moving the operand's defining op to the dispatch block (if it's a
1313 // trivial use) or by storing to a temporary alloca and loading it.
1314 mlir::LogicalResult createExitTerminator(
1315 mlir::Operation *exitOp, mlir::Location loc, mlir::Block *continueBlock,
1316 const llvm::SmallPtrSetImpl<mlir::Operation *> &sinkableOperands,
1317 mlir::PatternRewriter &rewriter) const {
1318 return llvm::TypeSwitch<mlir::Operation *, mlir::LogicalResult>(exitOp)
1319 .Case<cir::YieldOp>([&](auto) {
1320 // Yield becomes a branch to continue block.
1321 cir::BrOp::create(rewriter, loc, continueBlock);
1322 return mlir::success();
1323 })
1324 .Case<cir::BreakOp>([&](auto) {
1325 // Break is preserved for later lowering by enclosing switch/loop.
1326 cir::BreakOp::create(rewriter, loc);
1327 return mlir::success();
1328 })
1329 .Case<cir::ContinueOp>([&](auto) {
1330 // Continue is preserved for later lowering by enclosing loop.
1331 cir::ContinueOp::create(rewriter, loc);
1332 return mlir::success();
1333 })
1334 .Case<cir::CoReturnOp>([&](auto) {
1335 // CoReturnOp does not carry a destination operand. The continuation
1336 // block determines whether execution proceeds to another cleanup or
1337 // to the coroutine's final suspend path.
1338 cir::CoReturnOp::create(rewriter, loc);
1339 return mlir::success();
1340 })
1341 .Case<cir::CoroCleanupOp>([&](auto) {
1342 // Like cir.co_return, it keeps propagating through the enclosing
1343 // cleanup scopes until CIRCoroutineFlattening rewrites it.
1344 cir::CoroCleanupOp::create(rewriter, loc);
1345 return mlir::success();
1346 })
1347 .Case<cir::ReturnOp>([&](auto returnOp) {
1348 // Return from the cleanup exit. Note, if this is a return inside a
1349 // nested cleanup scope, the flattening of the outer scope will handle
1350 // branching through the outer cleanup.
1351 if (returnOp.hasOperand()) {
1353 getReturnOpOperands(returnOp, exitOp, loc, sinkableOperands,
1354 rewriter, returnValues);
1355 cir::ReturnOp::create(rewriter, loc, returnValues);
1356 } else {
1357 cir::ReturnOp::create(rewriter, loc);
1358 }
1359 return mlir::success();
1360 })
1361 .Case<cir::GotoOp>([&](auto gotoOp) {
1362 // Gotos that target a label within the cleanup body region are
1363 // filtered out by collectExits and never reach this code, so any
1364 // goto that does reach here transfers control out of the cleanup
1365 // scope. The goto is just moved to the exit block.
1366 cir::GotoOp::create(rewriter, loc, gotoOp.getLabel());
1367 return mlir::success();
1368 })
1369 .Default([&](mlir::Operation *op) {
1370 cir::UnreachableOp::create(rewriter, loc);
1371 return op->emitError(
1372 "unexpected exit operation in cleanup scope body");
1373 });
1374 }
1375
1376#ifndef NDEBUG
1377 // Check that no block other than the last one in a region exits the region.
1378 static bool regionExitsOnlyFromLastBlock(mlir::Region &region) {
1379 for (mlir::Block &block : region) {
1380 if (&block == &region.back())
1381 continue;
1382 bool expectedTerminator =
1383 llvm::TypeSwitch<mlir::Operation *, bool>(block.getTerminator())
1384 // It is theoretically possible to have a cleanup block with
1385 // any of the following exits in non-final blocks, but we won't
1386 // currently generate any CIR that does that, and being able to
1387 // assume that it doesn't happen simplifies the implementation.
1388 // If we ever need to handle this case, the code will need to
1389 // be updated to handle it.
1390 .Case<cir::YieldOp, cir::ReturnOp, cir::ResumeFlatOp,
1391 cir::ContinueOp, cir::BreakOp, cir::GotoOp>(
1392 [](auto) { return false; })
1393 // We expect that call operations have not yet been rewritten
1394 // as try_call operations. A call can unwind out of the cleanup
1395 // scope, but we will be handling that during flattening. The
1396 // only case where a try_call could be present inside an
1397 // unflattened cleanup region is if the cleanup contained a
1398 // nested try-catch region, and that isn't expected as of the
1399 // time of this implementation. If it does, this could be
1400 // updated to tolerate it.
1401 .Case<cir::TryCallOp>([](auto) { return false; })
1402 // Likewise, we don't expect to find an EH dispatch operation
1403 // because we weren't expecting try-catch regions nested in the
1404 // cleanup region.
1405 .Case<cir::EhDispatchOp>([](auto) { return false; })
1406 // In theory, it would be possible to have a flattened switch
1407 // operation that does not exit the cleanup region. For now,
1408 // that's not happening.
1409 .Case<cir::SwitchFlatOp>([](auto) { return false; })
1410 // These aren't expected either, but if they occur, they don't
1411 // exit the region, so that's OK.
1412 .Case<cir::UnreachableOp, cir::TrapOp>([](auto) { return true; })
1413 // Indirect branches are not expected.
1414 .Case<cir::IndirectBrOp>([](auto) { return false; })
1415 // We do expect branches, but we don't expect them to leave
1416 // the region.
1417 .Case<cir::BrOp>([&](cir::BrOp brOp) {
1418 assert(brOp.getDest()->getParent() == &region &&
1419 "branch destination is not in the region");
1420 return true;
1421 })
1422 .Case<cir::BrCondOp>([&](cir::BrCondOp brCondOp) {
1423 assert(brCondOp.getDestTrue()->getParent() == &region &&
1424 "branch destination is not in the region");
1425 assert(brCondOp.getDestFalse()->getParent() == &region &&
1426 "branch destination is not in the region");
1427 return true;
1428 })
1429 // What else could there be?
1430 .Default([](mlir::Operation *) -> bool {
1431 llvm_unreachable("unexpected terminator in cleanup region");
1432 });
1433 if (!expectedTerminator)
1434 return false;
1435 }
1436 return true;
1437 }
1438#endif
1439
1440 // Build the EH cleanup block structure by cloning the cleanup region. The
1441 // cloned entry block gets an !cir.eh_token argument and a cir.begin_cleanup
1442 // inserted at the top. All cir.yield terminators that might exit the cleanup
1443 // region are replaced with cir.end_cleanup + cir.resume.
1444 //
1445 // For a single-block cleanup region, this produces:
1446 //
1447 // ^eh_cleanup(%eh_token : !cir.eh_token):
1448 // %ct = cir.begin_cleanup %eh_token : !cir.eh_token -> !cir.cleanup_token
1449 // <cloned cleanup operations>
1450 // cir.end_cleanup %ct : !cir.cleanup_token
1451 // cir.resume %eh_token : !cir.eh_token
1452 //
1453 // For a multi-block cleanup region (e.g. containing a flattened cir.if),
1454 // the same wrapping is applied around the cloned block structure: the entry
1455 // block gets begin_cleanup and all exit blocks (those terminated by yield)
1456 // get end_cleanup + resume.
1457 //
1458 // If this cleanup scope is nested within a TryOp, the resume will be updated
1459 // to branch to the catch dispatch block of the enclosing try operation when
1460 // the TryOp is flattened.
1461 mlir::Block *buildEHCleanupBlocks(cir::CleanupScopeOp cleanupOp,
1462 mlir::Location loc,
1463 mlir::Block *insertBefore,
1464 mlir::PatternRewriter &rewriter) const {
1465 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1466 "cleanup region has exits in non-final blocks");
1467
1468 // Track the block before the insertion point so we can find the cloned
1469 // blocks after cloning.
1470 mlir::Block *blockBeforeClone = insertBefore->getPrevNode();
1471
1472 // Clone the entire cleanup region before insertBefore.
1473 rewriter.cloneRegionBefore(cleanupOp.getCleanupRegion(), insertBefore);
1474
1475 // Find the first cloned block.
1476 mlir::Block *clonedEntry = blockBeforeClone
1477 ? blockBeforeClone->getNextNode()
1478 : &insertBefore->getParent()->front();
1479
1480 // Add the eh_token argument to the cloned entry block and insert
1481 // begin_cleanup at the top.
1482 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1483 mlir::Value ehToken = clonedEntry->addArgument(ehTokenType, loc);
1484
1485 rewriter.setInsertionPointToStart(clonedEntry);
1486 auto beginCleanup = cir::BeginCleanupOp::create(rewriter, loc, ehToken);
1487
1488 // Replace the yield terminator in the last cloned block with
1489 // end_cleanup + resume.
1490 mlir::Block *lastClonedBlock = insertBefore->getPrevNode();
1491 auto yieldOp =
1492 mlir::dyn_cast<cir::YieldOp>(lastClonedBlock->getTerminator());
1493 if (yieldOp) {
1494 rewriter.setInsertionPoint(yieldOp);
1495 cir::EndCleanupOp::create(rewriter, loc, beginCleanup.getCleanupToken());
1496 rewriter.replaceOpWithNewOp<cir::ResumeOp>(yieldOp, ehToken);
1497 } else {
1498 cleanupOp->emitError("Not yet implemented: cleanup region terminated "
1499 "with non-yield operation");
1500 }
1501
1502 return clonedEntry;
1503 }
1504
1505 // Flatten a cleanup scope. The body region's exits branch to the cleanup
1506 // block, and the cleanup block branches to destination blocks whose contents
1507 // depend on the type of operation that exited the body region. Yield becomes
1508 // a branch to the block after the cleanup scope, break and continue are
1509 // preserved for later lowering by enclosing switch or loop, and return
1510 // is preserved as is.
1511 //
1512 // If there are multiple exits from the cleanup body, a destination slot and
1513 // switch dispatch are used to continue to the correct destination after the
1514 // cleanup is complete. A destination slot alloca is created at the function
1515 // entry block. Each exit operation is replaced by a store of its unique ID to
1516 // the destination slot and a branch to cleanup. An operation is appended to
1517 // the to branch to a dispatch block that loads the destination slot and uses
1518 // switch.flat to branch to the correct destination.
1519 //
1520 // If the cleanup scope requires EH cleanup, any call operations in the body
1521 // that may throw are replaced with cir.try_call operations that unwind to an
1522 // EH cleanup block. The cleanup block(s) will be terminated with a cir.resume
1523 // operation. If this cleanup scope is enclosed by a try operation, the
1524 // flattening of the try operation flattening will replace the cir.resume with
1525 // a branch to a catch dispatch block. Otherwise, the cir.resume operation
1526 // remains in place and will unwind to the caller.
1527 mlir::LogicalResult
1528 flattenCleanup(cir::CleanupScopeOp cleanupOp,
1530 llvm::SmallVectorImpl<cir::CallOp> &callsToRewrite,
1531 llvm::SmallVectorImpl<cir::ThrowOp> &throwsToRewrite,
1532 llvm::SmallVectorImpl<cir::ResumeOp> &resumeOpsToChain,
1533 mlir::PatternRewriter &rewriter) const {
1534 mlir::Location loc = cleanupOp.getLoc();
1535 cir::CleanupKindAttr cleanupKind = cleanupOp.getCleanupKindAttr();
1536 bool hasNormalCleanup = cleanupKind.isNormal();
1537 bool hasEHCleanup = cleanupKind.isEH();
1538 bool isMultiExit = exits.size() > 1;
1539
1540 // If every exit from the body is a musttail return, nothing reaches the
1541 // normal cleanup, so it is dropped rather than emitted as dead code. The
1542 // EH path is still built. The only cleanup a musttail call may skip and
1543 // still unwind through is a lifetime marker, which is pushed as an "all"
1544 // cleanup, and the body can throw before reaching the tail call.
1545 bool emitNormalCleanup = hasNormalCleanup && !exits.empty();
1546
1547 // Get references to region blocks before inlining.
1548 mlir::Block *bodyEntry = &cleanupOp.getBodyRegion().front();
1549 mlir::Block *cleanupEntry = &cleanupOp.getCleanupRegion().front();
1550 mlir::Block *cleanupExit = &cleanupOp.getCleanupRegion().back();
1551 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1552 "cleanup region has exits in non-final blocks");
1553 auto cleanupYield = dyn_cast<cir::YieldOp>(cleanupExit->getTerminator());
1554 if (!cleanupYield) {
1555 return rewriter.notifyMatchFailure(cleanupOp,
1556 "Not yet implemented: cleanup region "
1557 "terminated with non-yield operation");
1558 }
1559
1560 // For multiple exits from the body region, get or create a destination slot
1561 // at function entry. The slot is shared across all cleanup scopes in the
1562 // function. This is only needed if the cleanup scope requires normal
1563 // cleanup.
1564 cir::AllocaOp destSlot;
1565 if (isMultiExit && emitNormalCleanup) {
1566 auto funcOp = cleanupOp->getParentOfType<cir::FuncOp>();
1567 if (!funcOp)
1568 return cleanupOp->emitError("cleanup scope not inside a function");
1569 destSlot = getOrCreateCleanupDestSlot(funcOp, rewriter, loc);
1570 }
1571
1572 // Pick the return operands to sink past the cleanup while the cleanup
1573 // region is still intact.
1575 if (emitNormalCleanup) {
1576 for (const CleanupExit &exit : exits) {
1577 auto returnOp = dyn_cast<cir::ReturnOp>(exit.exitOp);
1578 if (!returnOp)
1579 continue;
1580 for (mlir::Value operand : returnOp.getOperands())
1581 if (shouldSinkReturnOperand(operand, returnOp,
1582 cleanupOp.getCleanupRegion()))
1583 sinkableOperands.insert(operand.getDefiningOp());
1584 }
1585 }
1586
1587 // Split the current block to create the insertion point.
1588 mlir::Block *currentBlock = rewriter.getInsertionBlock();
1589 mlir::Block *continueBlock =
1590 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
1591
1592 // Build EH cleanup blocks if needed. This must be done before inlining
1593 // the cleanup region since buildEHCleanupBlocks clones from it. The unwind
1594 // block is inserted before the EH cleanup entry so that the final layout
1595 // is: body -> normal cleanup -> exit -> unwind -> EH cleanup -> continue.
1596 // EH cleanup blocks are needed when there are throwing calls or throws
1597 // that need to be rewritten, or when there are resume ops from
1598 // already-flattened inner cleanup scopes that need to chain through this
1599 // cleanup's EH handler.
1600 mlir::Block *unwindBlock = nullptr;
1601 mlir::Block *ehCleanupEntry = nullptr;
1602 if (hasEHCleanup && (!callsToRewrite.empty() || !throwsToRewrite.empty() ||
1603 !resumeOpsToChain.empty())) {
1604 ehCleanupEntry =
1605 buildEHCleanupBlocks(cleanupOp, loc, continueBlock, rewriter);
1606 // The unwind block is only needed when there are throwing calls or
1607 // throws that need a shared unwind destination. Resume ops from inner
1608 // cleanups branch directly to the EH cleanup entry.
1609 if (!callsToRewrite.empty() || !throwsToRewrite.empty())
1610 unwindBlock = buildUnwindBlock(ehCleanupEntry, /*isCleanupOnly=*/true,
1611 loc, ehCleanupEntry, rewriter);
1612 }
1613
1614 // All normal flow blocks are inserted before this point — either before
1615 // the unwind block (if it exists), or before the EH cleanup entry (if EH
1616 // cleanup exists but no unwind block is needed), or before the continue
1617 // block.
1618 mlir::Block *normalInsertPt =
1619 unwindBlock ? unwindBlock
1620 : (ehCleanupEntry ? ehCleanupEntry : continueBlock);
1621
1622 // Inline the body region.
1623 rewriter.inlineRegionBefore(cleanupOp.getBodyRegion(), normalInsertPt);
1624
1625 // Inline the cleanup region for the normal cleanup path.
1626 if (emitNormalCleanup)
1627 rewriter.inlineRegionBefore(cleanupOp.getCleanupRegion(), normalInsertPt);
1628
1629 // Branch from current block to body entry.
1630 rewriter.setInsertionPointToEnd(currentBlock);
1631 cir::BrOp::create(rewriter, loc, bodyEntry);
1632
1633 // Handle normal exits.
1634 mlir::LogicalResult result = mlir::success();
1635 if (emitNormalCleanup) {
1636 // Create the exit/dispatch block (after cleanup, before continue).
1637 mlir::Block *exitBlock = rewriter.createBlock(normalInsertPt);
1638
1639 // Rewrite the cleanup region's yield to branch to exit block.
1640 rewriter.setInsertionPoint(cleanupYield);
1641 rewriter.replaceOpWithNewOp<cir::BrOp>(cleanupYield, exitBlock);
1642
1643 if (isMultiExit) {
1644 // Build the dispatch switch in the exit block.
1645 rewriter.setInsertionPointToEnd(exitBlock);
1646
1647 // Load the destination slot value.
1648 auto slotValue =
1649 cir::LoadOp::create(rewriter, loc, destSlot, /*isDeref=*/false,
1650 /*isVolatile=*/false, /*isNontemporal=*/false,
1651 /*alignment=*/mlir::IntegerAttr(),
1652 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1653 /*invariant=*/false);
1654
1655 // Create destination blocks for each exit and collect switch case info.
1657 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
1659 cir::IntType s32Type =
1660 cir::IntType::get(rewriter.getContext(), 32, /*isSigned=*/true);
1661
1662 for (const CleanupExit &exit : exits) {
1663 // Create a block for this destination.
1664 mlir::Block *destBlock = rewriter.createBlock(normalInsertPt);
1665 rewriter.setInsertionPointToEnd(destBlock);
1666 result = createExitTerminator(exit.exitOp, loc, continueBlock,
1667 sinkableOperands, rewriter);
1668
1669 // Add to switch cases.
1670 caseValues.push_back(
1671 llvm::APInt(32, static_cast<uint64_t>(exit.destinationId), true));
1672 caseDestinations.push_back(destBlock);
1673 caseOperands.push_back(mlir::ValueRange());
1674
1675 // Replace the original exit op with: store dest ID, branch to
1676 // cleanup.
1677 rewriter.setInsertionPoint(exit.exitOp);
1678 auto destIdConst = cir::ConstantOp::create(
1679 rewriter, loc, cir::IntAttr::get(s32Type, exit.destinationId));
1680 cir::StoreOp::create(rewriter, loc, destIdConst, destSlot,
1681 /*isVolatile=*/false,
1682 /*isNontemporal=*/false,
1683 /*alignment=*/mlir::IntegerAttr(),
1684 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1685 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, cleanupEntry);
1686
1687 // If the exit terminator creation failed, we're going to end up with
1688 // partially flattened code, but we'll also have reported an error so
1689 // that's OK. We need to finish out this function to keep the IR in a
1690 // valid state to help diagnose the error. This is a temporary
1691 // possibility during development. It shouldn't ever happen after the
1692 // implementation is complete.
1693 if (result.failed())
1694 break;
1695 }
1696
1697 // Create the default destination (unreachable).
1698 mlir::Block *defaultBlock = rewriter.createBlock(normalInsertPt);
1699 rewriter.setInsertionPointToEnd(defaultBlock);
1700 cir::UnreachableOp::create(rewriter, loc);
1701
1702 // Build the switch.flat operation in the exit block.
1703 rewriter.setInsertionPointToEnd(exitBlock);
1704 cir::SwitchFlatOp::create(rewriter, loc, slotValue, defaultBlock,
1705 mlir::ValueRange(), caseValues,
1706 caseDestinations, caseOperands);
1707 } else {
1708 // Single exit: put the appropriate terminator directly in the exit
1709 // block.
1710 rewriter.setInsertionPointToEnd(exitBlock);
1711 mlir::Operation *exitOp = exits[0].exitOp;
1712 result = createExitTerminator(exitOp, loc, continueBlock,
1713 sinkableOperands, rewriter);
1714
1715 // Replace body exit with branch to cleanup entry.
1716 rewriter.setInsertionPoint(exitOp);
1717 rewriter.replaceOpWithNewOp<cir::BrOp>(exitOp, cleanupEntry);
1718 }
1719 } else {
1720 // No normal cleanup to run: normal exits skip the cleanup entirely.
1721 // Replace yield exits with branches to the continue block.
1722 for (CleanupExit &exit : exits) {
1723 if (isa<cir::YieldOp>(exit.exitOp)) {
1724 rewriter.setInsertionPoint(exit.exitOp);
1725 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, continueBlock);
1726 }
1727 // Non-yield exits (break, continue, return) stay as-is since no normal
1728 // cleanup is needed.
1729 }
1730 }
1731
1732 // Replace non-nothrow calls and throws with try_call/try_throw
1733 // operations. All calls and throws within this cleanup scope share the
1734 // same unwind destination.
1735 if (hasEHCleanup) {
1736 for (cir::CallOp callOp : callsToRewrite)
1737 replaceCallWithTryCall(callOp, unwindBlock, loc, rewriter);
1738 for (cir::ThrowOp throwOp : throwsToRewrite)
1739 replaceThrowWithTryThrow(throwOp, unwindBlock, loc, rewriter);
1740 }
1741
1742 // Handle throwing calls and throws in EH cleanup blocks. When an
1743 // exception is thrown during cleanup code that runs on the exception
1744 // unwind path, the C++ standard requires that std::terminate() be
1745 // called. Replace such calls and throws with try_call/try_throw
1746 // operations that unwind to a terminate block containing
1747 // cir.eh.initiate + cir.eh.terminate.
1748 if (ehCleanupEntry) {
1749 llvm::SmallVector<cir::CallOp> ehCleanupThrowingCalls;
1750 llvm::SmallVector<cir::ThrowOp> ehCleanupThrows;
1751 for (mlir::Block *block = ehCleanupEntry; block != continueBlock;
1752 block = block->getNextNode()) {
1753 block->walk([&](mlir::Operation *op) {
1754 if (auto callOp = mlir::dyn_cast<cir::CallOp>(op)) {
1755 if (!callOp.getNothrow())
1756 ehCleanupThrowingCalls.push_back(callOp);
1757 } else if (auto throwOp = mlir::dyn_cast<cir::ThrowOp>(op)) {
1758 ehCleanupThrows.push_back(throwOp);
1759 }
1760 });
1761 }
1762 if (!ehCleanupThrowingCalls.empty() || !ehCleanupThrows.empty()) {
1763 mlir::Block *terminateBlock =
1764 buildTerminateUnwindBlock(loc, continueBlock, rewriter);
1765 for (cir::CallOp callOp : ehCleanupThrowingCalls)
1766 replaceCallWithTryCall(callOp, terminateBlock, loc, rewriter);
1767 for (cir::ThrowOp throwOp : ehCleanupThrows)
1768 replaceThrowWithTryThrow(throwOp, terminateBlock, loc, rewriter);
1769 }
1770 }
1771
1772 // Chain inner EH cleanup resume ops to this cleanup's EH handler.
1773 // Each cir.resume from an already-flattened inner cleanup is replaced
1774 // with a branch to the outer EH cleanup entry, passing the eh_token
1775 // from the inner's begin_cleanup so that the same in-flight exception
1776 // flows through the outer cleanup before unwinding to the caller.
1777 if (ehCleanupEntry) {
1778 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
1779 mlir::Value ehToken = resumeOp.getEhToken();
1780 rewriter.setInsertionPoint(resumeOp);
1781 rewriter.replaceOpWithNewOp<cir::BrOp>(
1782 resumeOp, mlir::ValueRange{ehToken}, /*loop_id=*/nullptr,
1783 /*loop_hints=*/nullptr, ehCleanupEntry);
1784 }
1785 }
1786
1787 // Erase the original cleanup scope op.
1788 rewriter.eraseOp(cleanupOp);
1789
1790 // Always return success because the IR has been modified (blocks split,
1791 // regions inlined, ops erased, etc.). The MLIR pattern rewriter contract
1792 // requires that if a pattern modifies IR, it must return success().
1793 return mlir::success();
1794 }
1795
1796 mlir::LogicalResult
1797 matchAndRewrite(cir::CleanupScopeOp cleanupOp,
1798 mlir::PatternRewriter &rewriter) const override {
1799 mlir::OpBuilder::InsertionGuard guard(rewriter);
1800
1801 // All nested structured CIR ops must be flattened before the cleanup scope.
1802 // Operations like loops, switches, scopes, and ifs may contain exits
1803 // (return, break, continue) that the cleanup scope will replace with
1804 // branches to the cleanup entry. If those exits are inside a structured
1805 // op's region, the branch would reference a block outside that region,
1806 // which is invalid. Fail the match so they are processed first.
1807 //
1808 // Before checking, erase any trivially dead nested cleanup scopes. These
1809 // arise from deactivated cleanups (e.g. partial-construction guards for
1810 // lambda captures). The greedy rewriter may have already DCE'd them, but
1811 // when a trivially dead nested op is erased first, the parent isn't always
1812 // re-added to the worklist, so we handle it here.
1814 cleanupOp.getBodyRegion().walk([&](cir::CleanupScopeOp nested) {
1815 if (mlir::isOpTriviallyDead(nested))
1816 deadNestedOps.push_back(nested);
1817 });
1818 for (auto op : deadNestedOps)
1819 rewriter.eraseOp(op);
1820
1821 if (hasNestedOpsToFlatten(cleanupOp.getBodyRegion()))
1822 return mlir::failure();
1823
1824 bool hasEHCleanup = cleanupOp.getCleanupKindAttr().isEH();
1825
1826 // Collect all exits from the body region.
1828 int nextId = 0;
1829 collectExits(cleanupOp.getBodyRegion(), exits, nextId);
1830
1831#ifndef NDEBUG
1832 // A body with no exits at all only happens when every path out of it is a
1833 // musttail return, which leaves the function without running the cleanup.
1834 bool hasMustTailCall = false;
1835 cleanupOp.getBodyRegion().walk(
1836 [&](cir::CallOp callOp) { hasMustTailCall |= callOp.getMusttail(); });
1837 assert((!exits.empty() || hasMustTailCall) &&
1838 "cleanup scope body has no exit");
1839#endif
1840
1841 // Collect non-nothrow calls and throws that need to be converted to
1842 // try_call/try_throw. A marker-only cleanup must not introduce an unwind
1843 // edge unless an enclosing handler or real EH cleanup requires one.
1844 llvm::SmallVector<cir::CallOp> callsToRewrite;
1845 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
1846 if (hasEHCleanup && (!isLifetimeMarkerOnly(cleanupOp.getCleanupRegion()) ||
1847 hasEnclosingEHRequirement(cleanupOp))) {
1848 collectThrowingCalls(cleanupOp.getBodyRegion(), callsToRewrite);
1849 collectThrows(cleanupOp.getBodyRegion(), throwsToRewrite);
1850 }
1851
1852 // Collect resume ops from already-flattened inner cleanup scopes that
1853 // need to chain through this cleanup's EH handler, including lifetime
1854 // markers even when they did not introduce any unwind edges themselves.
1855 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
1856 if (hasEHCleanup)
1857 collectResumeOps(cleanupOp.getBodyRegion(), resumeOpsToChain);
1858
1859 return flattenCleanup(cleanupOp, exits, callsToRewrite, throwsToRewrite,
1860 resumeOpsToChain, rewriter);
1861 }
1862};
1863
1864// Trace an !cir.eh_token value back through block arguments to find the
1865// cir.eh.initiate operation that defines it. Returns {} if the defining op
1866// cannot be found (e.g. multiple predecessors).
1867static cir::EhInitiateOp traceToEhInitiate(mlir::Value ehToken) {
1868 while (ehToken) {
1869 if (auto initiate = ehToken.getDefiningOp<cir::EhInitiateOp>())
1870 return initiate;
1871 auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(ehToken);
1872 if (!blockArg)
1873 return {};
1874 mlir::Block *pred = blockArg.getOwner()->getSinglePredecessor();
1875 if (!pred)
1876 return {};
1877 auto brOp = mlir::dyn_cast<cir::BrOp>(pred->getTerminator());
1878 if (!brOp)
1879 return {};
1880 ehToken = brOp.getDestOperands()[blockArg.getArgNumber()];
1881 }
1882 return {};
1883}
1884
1885class CIRTryOpFlattening : public mlir::OpRewritePattern<cir::TryOp> {
1886public:
1887 using OpRewritePattern<cir::TryOp>::OpRewritePattern;
1888
1889 // Build the catch dispatch block with a cir.eh.dispatch operation.
1890 // The dispatch block receives an !cir.eh_token argument and dispatches
1891 // to the appropriate catch handler blocks based on exception types.
1892 mlir::Block *buildCatchDispatchBlock(
1893 cir::TryOp tryOp, mlir::ArrayAttr handlerTypes,
1894 llvm::SmallVectorImpl<mlir::Block *> &catchHandlerBlocks,
1895 mlir::Location loc, mlir::Block *insertBefore,
1896 mlir::PatternRewriter &rewriter) const {
1897 mlir::Block *dispatchBlock = rewriter.createBlock(insertBefore);
1898 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1899 mlir::Value ehToken = dispatchBlock->addArgument(ehTokenType, loc);
1900
1901 rewriter.setInsertionPointToEnd(dispatchBlock);
1902
1903 // Build the catch types and destinations for the dispatch.
1904 llvm::SmallVector<mlir::Attribute> catchTypeAttrs;
1905 llvm::SmallVector<mlir::Block *> catchDests;
1906 mlir::Block *defaultDest = nullptr;
1907 bool defaultIsCatchAll = false;
1908
1909 // A filter try operation has exactly two handlers. The unexpected region
1910 // is the destination of the filter clause (taken when the exception is
1911 // *not* permitted). The filter region is the unwind destination (taken
1912 // when it is).
1913 cir::EhFilterAttr filterAttr;
1914 mlir::Block *filterUnwindDest = nullptr;
1915 mlir::Block *filterClauseDest = nullptr;
1916
1917 for (auto zipped : llvm::zip(handlerTypes, catchHandlerBlocks)) {
1918 mlir::Attribute typeAttr = std::get<0>(zipped);
1919 mlir::Block *handlerBlock = std::get<1>(zipped);
1920 llvm::TypeSwitch<mlir::Attribute>(typeAttr)
1921 .Case<cir::CatchAllAttr>([&](auto) {
1922 assert(!defaultDest && "multiple catch_all or unwind handlers");
1923 defaultDest = handlerBlock;
1924 defaultIsCatchAll = true;
1925 })
1926 .Case<cir::UnwindAttr>([&](auto) {
1927 assert(!defaultDest && "multiple catch_all or unwind handlers");
1928 defaultDest = handlerBlock;
1929 defaultIsCatchAll = false;
1930 })
1931 .Case<cir::EhFilterAttr>([&](cir::EhFilterAttr ehFilter) {
1932 assert(!filterAttr && "multiple filter handlers");
1933 filterAttr = ehFilter;
1934 filterUnwindDest = handlerBlock;
1935 })
1936 .Case<cir::EhUnexpectedAttr>([&](auto) {
1937 assert(!filterClauseDest && "multiple unexpected handlers");
1938 filterClauseDest = handlerBlock;
1939 })
1940 .Default([&](mlir::Attribute attr) {
1941 // Typed catch handler (GlobalViewAttr with type info).
1942 catchTypeAttrs.push_back(attr);
1943 catchDests.push_back(handlerBlock);
1944 });
1945 }
1946
1947 if (filterAttr) {
1948 assert(filterUnwindDest && filterClauseDest &&
1949 "filter handler requires an unexpected handler");
1950 assert(!defaultDest &&
1951 "filter handler cannot share a dispatch with catch_all or unwind");
1952 catchTypeAttrs.push_back(filterAttr);
1953 catchDests.push_back(filterClauseDest);
1954 defaultDest = filterUnwindDest;
1955 defaultIsCatchAll = false;
1956 }
1957
1958 assert(defaultDest && "dispatch must have a catch_all or unwind handler");
1959
1960 mlir::ArrayAttr catchTypesArrayAttr;
1961 if (!catchTypeAttrs.empty())
1962 catchTypesArrayAttr = rewriter.getArrayAttr(catchTypeAttrs);
1963
1964 cir::EhDispatchOp::create(rewriter, loc, ehToken, catchTypesArrayAttr,
1965 defaultIsCatchAll, defaultDest, catchDests);
1966
1967 return dispatchBlock;
1968 }
1969
1970 // Flatten a single catch handler region. Each handler region has an
1971 // !cir.eh_token argument and starts with cir.begin_catch, followed by
1972 // a cir.cleanup.scope containing the handler body (with cir.end_catch in
1973 // its cleanup region), and ending with cir.yield.
1974 //
1975 // After flattening, the handler region becomes a block that receives the
1976 // eh_token, calls begin_catch, runs the handler body inline, calls
1977 // end_catch, and branches to the continue block.
1978 //
1979 // The cleanup scope inside the catch handler is expected to have been
1980 // flattened before we get here, so what we see in the handler region is
1981 // already flat code with begin_catch at the top and end_catch in any place
1982 // that we would exit the catch handler. We just need to inline the region
1983 // and fix up terminators.
1984 mlir::Block *flattenCatchHandler(mlir::Region &handlerRegion,
1985 mlir::Block *continueBlock,
1986 mlir::Location loc,
1987 mlir::Block *insertBefore,
1988 mlir::PatternRewriter &rewriter) const {
1989 // The handler region entry block has the !cir.eh_token argument.
1990 mlir::Block *handlerEntry = &handlerRegion.front();
1991
1992 // Inline the handler region before insertBefore.
1993 rewriter.inlineRegionBefore(handlerRegion, insertBefore);
1994
1995 // Replace yield terminators in the handler with branches to continue.
1996 for (mlir::Block &block : llvm::make_range(handlerEntry->getIterator(),
1997 insertBefore->getIterator())) {
1998 if (auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator())) {
1999 // Verify that end_catch is the last non-branch operation before
2000 // this yield. After cleanup scope flattening, end_catch may be
2001 // in a predecessor block rather than immediately before the yield.
2002 // Walk back through predecessors (including multi-predecessor
2003 // blocks), verifying that each intermediate block contains only a
2004 // branch terminator, until we find end_catch as the last
2005 // non-terminator in some block.
2006 // Verify that end_catch is reachable on some predecessor path
2007 // before this yield. After cleanup scope flattening, end_catch
2008 // may be separated from yield by conditional branches (e.g.,
2009 // from flattened cir.if inside the catch body).
2010 assert(([&]() {
2011 if (mlir::Operation *prev = yieldOp->getPrevNode())
2012 return isa<cir::EndCatchOp>(prev);
2013 llvm::SmallPtrSet<mlir::Block *, 8> visited;
2014 llvm::SmallVector<mlir::Block *, 4> worklist;
2015 for (mlir::Block *pred : block.getPredecessors())
2016 worklist.push_back(pred);
2017 while (!worklist.empty()) {
2018 mlir::Block *b = worklist.pop_back_val();
2019 if (!visited.insert(b).second)
2020 continue;
2021 mlir::Operation *term = b->getTerminator();
2022 if (mlir::Operation *prev = term->getPrevNode()) {
2023 if (isa<cir::EndCatchOp>(prev))
2024 return true;
2025 }
2026 for (mlir::Block *pred : b->getPredecessors())
2027 worklist.push_back(pred);
2028 }
2029 return false;
2030 }()) &&
2031 "expected end_catch reachable before yield "
2032 "in catch handler");
2033 rewriter.setInsertionPoint(yieldOp);
2034 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, continueBlock);
2035 }
2036 }
2037
2038 return handlerEntry;
2039 }
2040
2041 // Flatten an unwind, filter, or unexpected handler region. These regions
2042 // do not catch the exception. They resume, are unreachable, or call
2043 // cir.eh.unexpected. We inline them and leave the terminator in place. If
2044 // this try op is nested inside an EH cleanup or another try op, the
2045 // enclosing op will rewrite a resume as a branch to its cleanup or dispatch
2046 // block when it is flattened. Otherwise, a resume will unwind to the caller.
2047 mlir::Block *flattenUnwindHandler(mlir::Region &unwindRegion,
2048 mlir::Location loc,
2049 mlir::Block *insertBefore,
2050 mlir::PatternRewriter &rewriter) const {
2051 mlir::Block *unwindEntry = &unwindRegion.front();
2052 rewriter.inlineRegionBefore(unwindRegion, insertBefore);
2053 return unwindEntry;
2054 }
2055
2056 mlir::LogicalResult
2057 matchAndRewrite(cir::TryOp tryOp,
2058 mlir::PatternRewriter &rewriter) const override {
2059 // All nested structured CIR ops must be flattened before the try op.
2060 // Cleanup scopes and nested try ops need to be flat so EH cleanup is
2061 // properly handled. Other structured ops (scopes, ifs, loops, switches,
2062 // ternaries) must be flat because replaceCallWithTryCall creates try_call
2063 // ops whose unwind destination is outside the structured op's region,
2064 // which would be an invalid cross-region reference.
2065 for (mlir::Region &region : tryOp->getRegions())
2066 if (hasNestedOpsToFlatten(region))
2067 return mlir::failure();
2068
2069 mlir::OpBuilder::InsertionGuard guard(rewriter);
2070 mlir::Location loc = tryOp.getLoc();
2071
2072 mlir::ArrayAttr handlerTypes = tryOp.getHandlerTypesAttr();
2073 mlir::MutableArrayRef<mlir::Region> handlerRegions =
2074 tryOp.getHandlerRegions();
2075
2076 // Collect throwing calls and throws in the try body.
2077 llvm::SmallVector<cir::CallOp> callsToRewrite;
2078 collectThrowingCalls(tryOp.getTryRegion(), callsToRewrite);
2079 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
2080 collectThrows(tryOp.getTryRegion(), throwsToRewrite);
2081
2082 // Collect resume ops from already-flattened cleanup scopes in the try body.
2083 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
2084 collectResumeOps(tryOp.getTryRegion(), resumeOpsToChain);
2085
2086 // Split the current block and inline the try body.
2087 mlir::Block *currentBlock = rewriter.getInsertionBlock();
2088 mlir::Block *continueBlock =
2089 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
2090
2091 // Get references to try body blocks before inlining.
2092 mlir::Block *bodyEntry = &tryOp.getTryRegion().front();
2093 mlir::Block *bodyExit = &tryOp.getTryRegion().back();
2094
2095 // Inline the try body region before the continue block.
2096 rewriter.inlineRegionBefore(tryOp.getTryRegion(), continueBlock);
2097
2098 // Branch from the current block to the body entry.
2099 rewriter.setInsertionPointToEnd(currentBlock);
2100 cir::BrOp::create(rewriter, loc, bodyEntry);
2101
2102 // Replace the try body's yield terminator with a branch to continue.
2103 if (auto bodyYield = dyn_cast<cir::YieldOp>(bodyExit->getTerminator())) {
2104 rewriter.setInsertionPoint(bodyYield);
2105 rewriter.replaceOpWithNewOp<cir::BrOp>(bodyYield, continueBlock);
2106 }
2107
2108 // If there are no handlers, we're done.
2109 if (!handlerTypes || handlerTypes.empty()) {
2110 rewriter.eraseOp(tryOp);
2111 return mlir::success();
2112 }
2113
2114 // If there are no throwing calls, no throws, and no resume ops from
2115 // inner cleanup scopes, exceptions cannot reach the catch handlers.
2116 // Drop all uses from the (unreachable) handler regions before erasing
2117 // the try op, since handler ops may reference values that were inlined
2118 // from the try body into the parent block.
2119 if (callsToRewrite.empty() && throwsToRewrite.empty() &&
2120 resumeOpsToChain.empty()) {
2121 for (mlir::Region &handlerRegion : handlerRegions)
2122 for (mlir::Block &block : handlerRegion)
2123 block.dropAllDefinedValueUses();
2124 rewriter.eraseOp(tryOp);
2125 return mlir::success();
2126 }
2127
2128 // Build the catch handler blocks.
2129
2130 // First, flatten all handler regions and collect the entry blocks.
2131 llvm::SmallVector<mlir::Block *> catchHandlerBlocks;
2132
2133 for (const auto &[idx, typeAttr] : llvm::enumerate(handlerTypes)) {
2134 mlir::Region &handlerRegion = handlerRegions[idx];
2135
2136 if (mlir::isa<cir::UnwindAttr, cir::EhFilterAttr, cir::EhUnexpectedAttr>(
2137 typeAttr)) {
2138 mlir::Block *unwindEntry =
2139 flattenUnwindHandler(handlerRegion, loc, continueBlock, rewriter);
2140 catchHandlerBlocks.push_back(unwindEntry);
2141 } else {
2142 mlir::Block *handlerEntry = flattenCatchHandler(
2143 handlerRegion, continueBlock, loc, continueBlock, rewriter);
2144 catchHandlerBlocks.push_back(handlerEntry);
2145 }
2146 }
2147
2148 // Build the catch dispatch block.
2149 mlir::Block *dispatchBlock =
2150 buildCatchDispatchBlock(tryOp, handlerTypes, catchHandlerBlocks, loc,
2151 catchHandlerBlocks.front(), rewriter);
2152
2153 // Check whether the try has a catch-all handler. When catch-all is
2154 // present, the personality function will always stop unwinding at this
2155 // frame (because catch-all matches every exception type). The LLVM
2156 // landingpad therefore needs "catch ptr null" rather than "cleanup".
2157 // The downstream pipeline (EHABILowering + LowerToLLVM) emits
2158 // "catch ptr null" when the EhInitiateOp has neither cleanup nor typed
2159 // catch types, so we clear the cleanup flag on every EhInitiateOp that
2160 // feeds into a dispatch with a catch-all handler.
2161 bool hasCatchAll =
2162 handlerTypes && llvm::any_of(handlerTypes, [](mlir::Attribute attr) {
2163 return mlir::isa<cir::CatchAllAttr>(attr);
2164 });
2165
2166 // Build a block to be the unwind desination for throwing calls/throws
2167 // and replace the calls/throws with try_call/try_throw ops. Note that
2168 // the unwind block created here is something different than the unwind
2169 // handler that we may have created above. The unwind handler continues
2170 // unwinding after uncaught exceptions. This is the block that will
2171 // eventually become the landing pad for invoke instructions.
2172 bool isCleanupOnly = tryOp.getCleanup() && !hasCatchAll;
2173 if (!callsToRewrite.empty() || !throwsToRewrite.empty()) {
2174 // Create a shared unwind block for all throwing calls/throws.
2175 mlir::Block *unwindBlock = buildUnwindBlock(dispatchBlock, isCleanupOnly,
2176 loc, dispatchBlock, rewriter);
2177
2178 for (cir::CallOp callOp : callsToRewrite)
2179 replaceCallWithTryCall(callOp, unwindBlock, loc, rewriter);
2180 for (cir::ThrowOp throwOp : throwsToRewrite)
2181 replaceThrowWithTryThrow(throwOp, unwindBlock, loc, rewriter);
2182 }
2183
2184 // Chain resume ops from inner cleanup scopes.
2185 // Resume ops from already-flattened cleanup scopes within the try body
2186 // should branch to the catch dispatch block instead of unwinding directly.
2187 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
2188 // When there is a catch-all handler, clear the cleanup flag on the
2189 // cir.eh.initiate that produced this token. With catch-all, the LLVM
2190 // landingpad needs "catch ptr null" instead of "cleanup".
2191 if (hasCatchAll) {
2192 if (auto ehInitiate = traceToEhInitiate(resumeOp.getEhToken())) {
2193 rewriter.modifyOpInPlace(ehInitiate,
2194 [&] { ehInitiate.removeCleanupAttr(); });
2195 }
2196 }
2197
2198 mlir::Value ehToken = resumeOp.getEhToken();
2199 rewriter.setInsertionPoint(resumeOp);
2200 rewriter.replaceOpWithNewOp<cir::BrOp>(
2201 resumeOp, mlir::ValueRange{ehToken}, /*loop_id=*/nullptr,
2202 /*loop_hints=*/nullptr, dispatchBlock);
2203 }
2204
2205 // Finally, erase the original try op ----
2206 rewriter.eraseOp(tryOp);
2207
2208 return mlir::success();
2209 }
2210};
2211
2212static void
2213collectCoReturnsOps(mlir::Region &region,
2215 region.walk(
2216 [&](cir::CoReturnOp coReturnOp) { coReturnOps.push_back(coReturnOp); });
2217}
2218
2219// Flatten `cir.coroutine`. This runs after every nested op (awaits, cir.scope,
2220// cleanup scopes, ...) has been flattened. The regions are inlined in order,
2221// the same layout classic codegen produces:
2222//
2223// initialSuspend ---> body ---> finalSuspend ---> destroy ---> exit
2224// | ^ ^ ^
2225// +-------------+ | |
2226// cir.co_return | |
2227// await destroy case (cir.coro.cleanup) -------------+ |
2228// await suspended case (cir.coro.exit) -------------------------+
2229//
2230// Completing the final suspend and an await's destroy case both free the frame
2231// (the destroy region, cir.coro.intrinsic.free) and then continue to the exit
2232// region. A suspended coroutine (cir.coro.exit) must keep its frame, so it
2233// branches straight to the exit region.
2234class CIRCoroutineFlattening : public mlir::OpRewritePattern<cir::CoroutineOp> {
2235 // cir.coro.exit and cir.coro.cleanup are placeholders produced by flattening
2236 // a cir.await, which can only appear in the initialSuspend, body and
2237 // finalSuspend regions.
2238 template <class PlaceholderOp>
2239 void
2240 collectAwaitPlaceholders(cir::CoroutineOp coroOp,
2241 llvm::SmallVectorImpl<PlaceholderOp> &ops) const {
2242 auto collect = [&](PlaceholderOp op) { ops.push_back(op); };
2243 coroOp.getInitialSuspend().walk(collect);
2244 coroOp.getBody().walk(collect);
2245 coroOp.getFinalSuspend().walk(collect);
2246 }
2247
2248 // Replace the cir.yield that ends `region` with a branch to `dest`.
2249 void replaceYieldWithBr(mlir::PatternRewriter &rewriter, mlir::Region &region,
2250 mlir::Block *dest) const {
2251 auto yieldOp = cast<cir::YieldOp>(region.back().getTerminator());
2252 rewriter.setInsertionPoint(yieldOp);
2253 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, dest, yieldOp.getArgs());
2254 }
2255
2256 // initialSuspend ends in a cir.yield once the init await is done. Replace it
2257 // with a branch to the body.
2258 void inlineInitialSuspend(mlir::PatternRewriter &rewriter,
2259 cir::CoroutineOp coroOp, mlir::Block *insertBefore,
2260 mlir::Block *beforeBody) const {
2261 mlir::Region &initialRegion = coroOp.getInitialSuspend();
2262 replaceYieldWithBr(rewriter, initialRegion, beforeBody);
2263 rewriter.inlineRegionBefore(initialRegion, insertBefore);
2264 }
2265
2266 // The body either falls off the end (cir.yield) or ends in a
2267 // cir.co_return. Both, like every other cir.co_return in the body, branch
2268 // to the final suspend.
2269 void inlineBody(mlir::PatternRewriter &rewriter, cir::CoroutineOp coroOp,
2270 mlir::Block *insertBefore, mlir::Block *beforeFinal) const {
2271 mlir::Region &bodyRegion = coroOp.getBody();
2272
2273 llvm::SmallVector<cir::CoReturnOp> coReturnsOps;
2274 collectCoReturnsOps(bodyRegion, coReturnsOps);
2275
2276 mlir::Operation *bodyTerminator = bodyRegion.back().getTerminator();
2277 if (auto bodyYield = dyn_cast<cir::YieldOp>(bodyTerminator)) {
2278 rewriter.setInsertionPoint(bodyYield);
2279 rewriter.replaceOpWithNewOp<cir::BrOp>(bodyYield, beforeFinal,
2280 mlir::ValueRange{});
2281 }
2282
2283 for (auto &coReturn : coReturnsOps) {
2284 rewriter.setInsertionPoint(coReturn);
2285 rewriter.replaceOpWithNewOp<cir::BrOp>(coReturn, beforeFinal,
2286 mlir::ValueRange{});
2287 }
2288
2289 rewriter.inlineRegionBefore(bodyRegion, insertBefore);
2290 }
2291
2292 // finalSuspend ends in a cir.yield once the final await completes. The
2293 // coroutine is done, so branch to the destroy region to free the frame.
2294 void inlineFinalSuspend(mlir::PatternRewriter &rewriter,
2295 cir::CoroutineOp coroOp, mlir::Block *insertBefore,
2296 mlir::Block *beforeDestroy) const {
2297 mlir::Region &finalRegion = coroOp.getFinalSuspend();
2298 replaceYieldWithBr(rewriter, finalRegion, beforeDestroy);
2299 rewriter.inlineRegionBefore(finalRegion, insertBefore);
2300 }
2301
2302 // The destroy region frees the frame (cir.coro.intrinsic.free) and always
2303 // continues to the exit region.
2304 void inlineDestroy(mlir::PatternRewriter &rewriter, cir::CoroutineOp coroOp,
2305 mlir::Block *insertBefore, mlir::Block *beforeExit) const {
2306 mlir::Region &destroyRegion = coroOp.getDestroy();
2307 replaceYieldWithBr(rewriter, destroyRegion, beforeExit);
2308 rewriter.inlineRegionBefore(destroyRegion, insertBefore);
2309 }
2310
2311 // The exit region ends in a cir.return, so nothing falls through it.
2312 void inlineExit(mlir::PatternRewriter &rewriter, cir::CoroutineOp coroOp,
2313 mlir::Block *insertBefore) const {
2314 rewriter.inlineRegionBefore(coroOp.getExit(), insertBefore);
2315 }
2316
2317 // A suspended coroutine keeps its frame, so each cir.coro.exit branches
2318 // straight to the exit region without running the destroy region.
2319 void lowerCoroExits(mlir::PatternRewriter &rewriter,
2320 llvm::ArrayRef<cir::CoroExitOp> coroExitsOps,
2321 mlir::Block *beforeExit) const {
2322 for (cir::CoroExitOp coroExit : coroExitsOps) {
2323 // TODO(cir): once the GRO region is supported, this may need to branch
2324 // there instead of to the exit region.
2326 rewriter.setInsertionPoint(coroExit);
2327 rewriter.replaceOpWithNewOp<cir::BrOp>(coroExit, beforeExit,
2328 mlir::ValueRange{});
2329 }
2330 }
2331
2332 // An await's destroy case: by now each cir.coro.cleanup has already gone
2333 // through the enclosing cleanup scopes (running their cleanups) and sits
2334 // directly in the coroutine. Replace it with a branch to the destroy region,
2335 // which frees the frame and then reaches the exit region.
2336 void lowerCoroCleanups(mlir::PatternRewriter &rewriter,
2337 llvm::ArrayRef<cir::CoroCleanupOp> coroCleanupOps,
2338 mlir::Block *beforeDestroy) const {
2339 for (cir::CoroCleanupOp coroCleanup : coroCleanupOps) {
2340 rewriter.setInsertionPoint(coroCleanup);
2341 rewriter.replaceOpWithNewOp<cir::BrOp>(coroCleanup, beforeDestroy,
2342 mlir::ValueRange{});
2343 }
2344 }
2345
2346public:
2347 using OpRewritePattern<cir::CoroutineOp>::OpRewritePattern;
2348
2349 mlir::LogicalResult
2350 matchAndRewrite(cir::CoroutineOp coroOp,
2351 mlir::PatternRewriter &rewriter) const override {
2352
2354 for (mlir::Region &region : coroOp->getRegions())
2355 if (hasNestedOpsToFlatten(region))
2356 return mlir::failure();
2357
2358 // Collect the await placeholders before the regions are moved. Each
2359 // cir.coro.exit becomes a branch to the exit region, and each
2360 // cir.coro.cleanup a branch to the destroy region.
2361 llvm::SmallVector<cir::CoroExitOp> coroExitsOps;
2362 collectAwaitPlaceholders(coroOp, coroExitsOps);
2363 llvm::SmallVector<cir::CoroCleanupOp> coroCleanupOps;
2364 collectAwaitPlaceholders(coroOp, coroCleanupOps);
2365
2366 // Take the entry blocks before the regions are moved.
2367 mlir::Block *beforeInitial = &coroOp.getInitialSuspend().front();
2368 mlir::Block *beforeBody = &coroOp.getBody().front();
2369 mlir::Block *beforeFinal = &coroOp.getFinalSuspend().front();
2370 mlir::Block *beforeDestroy = &coroOp.getDestroy().front();
2371 mlir::Block *beforeExit = &coroOp.getExit().front();
2372
2373 mlir::Block *coroBlock = rewriter.getInsertionBlock();
2374 // Split the current block before the CoroutineOp to create the inlining
2375 // point.
2376 mlir::Block *remainingOpsBlock =
2377 rewriter.splitBlock(coroBlock, rewriter.getInsertionPoint());
2378
2379 lowerCoroExits(rewriter, coroExitsOps, beforeExit);
2380 lowerCoroCleanups(rewriter, coroCleanupOps, beforeDestroy);
2381
2382 inlineInitialSuspend(rewriter, coroOp, remainingOpsBlock, beforeBody);
2383 inlineBody(rewriter, coroOp, remainingOpsBlock, beforeFinal);
2384 inlineFinalSuspend(rewriter, coroOp, remainingOpsBlock, beforeDestroy);
2385 inlineDestroy(rewriter, coroOp, remainingOpsBlock, beforeExit);
2386 inlineExit(rewriter, coroOp, remainingOpsBlock);
2387
2388 rewriter.setInsertionPointToEnd(coroBlock);
2389 cir::BrOp::create(rewriter, coroOp.getLoc(), beforeInitial,
2390 mlir::ValueRange{});
2391
2392 auto func = coroOp->getParentOfType<cir::FuncOp>();
2393 // The coroutine regions have been flattened, so the original coroutine
2394 // attribute no longer verifies. Preserve the information that this function
2395 // originated from a coroutine for LLVM lowering.
2396 func.setCoroutineKind(cir::CoroutineKind::FlattenedCoroutine);
2397
2398 rewriter.eraseOp(coroOp);
2399 return mlir::success();
2400 }
2401};
2402
2403class CIRAwaitOpFlattening : public mlir::OpRewritePattern<cir::AwaitOp> {
2404 // The ready region ends in a cir.condition that holds the result of
2405 // `await_ready()`. Replace it with a cir.brcond: if the awaiter is already
2406 // ready, skip the suspension and go straight to the resume region
2407 // otherwise go to the suspend region.
2408 void flattenReadyRegion(mlir::PatternRewriter &rewriter, cir::AwaitOp awaitOp,
2409 mlir::Block *resumeEntry, mlir::Block *suspendEntry,
2410 mlir::Block *remainingOpsBlock) const {
2411 mlir::Region &readyRegion = awaitOp.getReady();
2412 auto conditionOp =
2413 cast<cir::ConditionOp>(readyRegion.back().getTerminator());
2414 rewriter.setInsertionPoint(conditionOp);
2415 rewriter.replaceOpWithNewOp<cir::BrCondOp>(
2416 conditionOp, conditionOp.getCondition(), resumeEntry, suspendEntry);
2417 rewriter.inlineRegionBefore(readyRegion, remainingOpsBlock);
2418 }
2419
2420 // The suspend region runs `await_suspend()` and ends in a
2421 // cir.coro.suspend_point. Emit cir.coro.intrinsic.save and
2422 // cir.coro.intrinsic.suspend around it, and replace the suspend point with a
2423 // cir.switch.flat on the suspend result, which decides whether the coroutine
2424 // resumes, is destroyed or stays suspended.
2425 void flattenSuspendRegion(mlir::PatternRewriter &rewriter,
2426 cir::AwaitOp awaitOp, mlir::Block *resumeEntry,
2427 mlir::Block *remainingOpsBlock) const {
2428 mlir::Region &suspendRegion = awaitOp.getSuspend();
2429 auto suspendPoint =
2430 cast<cir::CoroSuspendPoint>(suspendRegion.back().getTerminator());
2431 cir::CoroSuspendOp coroSuspendIntri =
2432 emitCoroSuspend(rewriter, awaitOp, suspendPoint);
2433
2434 // Inline the suspend region before creating the destroy and suspended
2435 // blocks, so they are placed right after it, in front of the continuation.
2436 rewriter.inlineRegionBefore(suspendRegion, remainingOpsBlock);
2437
2438 mlir::Location loc = awaitOp.getLoc();
2439 mlir::Block *cleanupBlock =
2440 createDestroyBlock(rewriter, loc, remainingOpsBlock);
2441 mlir::Block *retBlock =
2442 createSuspendedBlock(rewriter, loc, remainingOpsBlock);
2443
2444 // 0 resumes, 1 destroys and the default (-1) stays suspended.
2445 llvm::SmallVector<mlir::APInt> caseValues{mlir::APInt(8, 0),
2446 mlir::APInt(8, 1)};
2447 llvm::SmallVector<mlir::Block *> caseDestinations{resumeEntry,
2448 cleanupBlock};
2449 llvm::SmallVector<mlir::ValueRange> caseOperands{caseValues.size()};
2450
2451 // Dispatch to the appropriate coroutine path based on the result of
2452 // `cir.coro.intrinsic.suspend`: resume, destroy, or suspend.
2453 rewriter.setInsertionPoint(suspendPoint);
2454 rewriter.replaceOpWithNewOp<cir::SwitchFlatOp>(
2455 suspendPoint, coroSuspendIntri.getResult(), retBlock,
2456 mlir::ValueRange{}, caseValues, caseDestinations, caseOperands);
2457 }
2458
2459 // Emit cir.coro.intrinsic.save at the start of the suspend region and
2460 // cir.coro.intrinsic.suspend right before its cir.coro.suspend_point.
2461 cir::CoroSuspendOp emitCoroSuspend(mlir::PatternRewriter &rewriter,
2462 cir::AwaitOp awaitOp,
2463 cir::CoroSuspendPoint suspendPoint) const {
2464 mlir::Location loc = awaitOp.getLoc();
2465
2466 // cir.coro.intrinsic.suspend takes the token produced by
2467 // cir.coro.intrinsic.save as its first argument, so emit the save first.
2468 rewriter.setInsertionPointToStart(&awaitOp.getSuspend().front());
2469
2470 // The save goes first in the suspend region, before await_suspend()
2471 // runs, so the coroutine is already considered suspended (and can be
2472 // resumed) from that point.
2473 auto voidPtrTy = cir::PointerType::get(cir::VoidType::get(getContext()));
2474 auto nullPtr = cir::ConstantOp::create(
2475 rewriter, loc,
2476 cir::ConstPtrAttr::get(voidPtrTy, rewriter.getI64IntegerAttr(0)));
2477 auto coroSave = cir::CoroSaveOp::create(rewriter, loc, nullPtr);
2478 rewriter.setInsertionPoint(suspendPoint);
2479 if (suspendPoint.getCond() != nullptr) {
2480 auto *oldinsertpoint = rewriter.getInsertionBlock();
2481 mlir::Block *suspendBlock = rewriter.splitBlock(
2482 rewriter.getInsertionBlock(), rewriter.getInsertionPoint());
2483 mlir::OpBuilder::InsertionGuard guard(rewriter);
2484 rewriter.setInsertionPointToEnd(oldinsertpoint);
2485 cir::BrCondOp::create(rewriter, loc, suspendPoint.getCond(), suspendBlock,
2486 &awaitOp.getResume().front(), mlir::ValueRange{},
2487 mlir::ValueRange{});
2488 }
2489 rewriter.setInsertionPoint(suspendPoint);
2490
2491 // The second argument to `cir.coro.intrinsic.suspend` indicates whether
2492 // this is the final suspend point. Coroutines suspended at a final suspend
2493 // point are considered done (`cir.coro.intrinsic.done` returns true) and
2494 // may only be destroyed; resuming them is undefined behavior.
2495 bool isFinalSuspend = awaitOp.getKind() == cir::AwaitKind::Final;
2496 auto isFinalCoroSuspend = cir::ConstantOp::create(
2497 rewriter, loc, cir::BoolAttr::get(getContext(), isFinalSuspend));
2498
2499 // cir.coro.intrinsic.suspend returns:
2500 // -1 : coroutine suspended
2501 // 0 : coroutine resumed
2502 // 1 : coroutine destroyed
2503 return cir::CoroSuspendOp::create(
2504 rewriter, loc,
2505 mlir::ValueRange{coroSave.getResult(), isFinalCoroSuspend});
2506 }
2507
2508 // Destroy case. Classic codegen uses EmitBranchThroughCleanup() so every
2509 // enclosing cleanup runs before the frame is freed. Here the destroy block
2510 // ends in a cir.coro.cleanup which, like cir.co_return, leaves every
2511 // enclosing cir.cleanup.scope (and loop) through its cleanup. Once it reaches
2512 // the coroutine, CIRCoroutineFlattening turns it into a branch to the
2513 // destroy region, which frees the frame (cir.coro.intrinsic.free) and then
2514 // reaches the exit region.
2515 mlir::Block *createDestroyBlock(mlir::PatternRewriter &rewriter,
2516 mlir::Location loc,
2517 mlir::Block *insertBefore) const {
2518 mlir::OpBuilder::InsertionGuard guard(rewriter);
2519 mlir::Block *cleanupBlock = rewriter.createBlock(insertBefore);
2520 cir::CoroCleanupOp::create(rewriter, loc);
2521 return cleanupBlock;
2522 }
2523
2524 // Suspended case: cir.coro.exit, which CIRCoroutineFlattening turns into
2525 // a branch to the exit region.
2526 mlir::Block *createSuspendedBlock(mlir::PatternRewriter &rewriter,
2527 mlir::Location loc,
2528 mlir::Block *insertBefore) const {
2529 mlir::OpBuilder::InsertionGuard guard(rewriter);
2531 mlir::Block *retBlock = rewriter.createBlock(insertBefore);
2532 cir::CoroExitOp::create(rewriter, loc);
2533 return retBlock;
2534 }
2535
2536 void flattenResumeRegion(mlir::PatternRewriter &rewriter,
2537 cir::AwaitOp awaitOp,
2538 mlir::Block *remainingOpsBlock) const {
2539 mlir::Region &resumeRegion = awaitOp.getResume();
2540 auto resumeYield = cast<cir::YieldOp>(resumeRegion.back().getTerminator());
2541 rewriter.setInsertionPoint(resumeYield);
2542 // Once the coroutine resumes, continue with the operations that
2543 // originally followed the await.
2544 rewriter.replaceOpWithNewOp<cir::BrOp>(resumeYield, remainingOpsBlock);
2545 rewriter.inlineRegionBefore(resumeRegion, remainingOpsBlock);
2546 }
2547
2548public:
2549 using OpRewritePattern<cir::AwaitOp>::OpRewritePattern;
2550
2551 // Flatten `cir.await` into the following control flow:
2552 //
2553 // awaitBlock
2554 // |
2555 // v
2556 // ready await_ready()
2557 // true / \ false
2558 // | v
2559 // | suspend await_suspend(), with
2560 // | / | \ cir.coro.intrinsic.save/suspend
2561 // | 0/ 1| \-1 (default)
2562 // v v v v
2563 // resume destroy suspended
2564 // | cir.coro cir.coro.exit
2565 // | .cleanup
2566 // v
2567 // continuation ops after the await
2568 //
2569 // `destroy` leaves through the enclosing cleanups to the coroutine's destroy
2570 // region (see createDestroyBlock), and `suspended` goes straight to its exit
2571 // region (see CIRCoroutineFlattening).
2572 mlir::LogicalResult
2573 matchAndRewrite(cir::AwaitOp awaitOp,
2574 mlir::PatternRewriter &rewriter) const override {
2575 // Nested ops (cir.if, cir.scope, cir.try, cleanup scopes, ...) must be
2576 // flattened first. Fail here so the rewriter processes them before
2577 // flattening this op.
2578 for (mlir::Region &region : awaitOp->getRegions())
2579 if (hasNestedOpsToFlatten(region))
2580 return mlir::failure();
2581
2582 mlir::Block *awaitBlock = rewriter.getInsertionBlock();
2583 // Split the current block before the AwaitOp to create the inlining
2584 // point.
2585 mlir::Block *remainingOpsBlock =
2586 rewriter.splitBlock(awaitBlock, rewriter.getInsertionPoint());
2587
2588 // Take the entry blocks before the regions are inlined.
2589 mlir::Block *readyEntry = &awaitOp.getReady().front();
2590 mlir::Block *suspendEntry = &awaitOp.getSuspend().front();
2591 mlir::Block *resumeEntry = &awaitOp.getResume().front();
2592
2593 flattenReadyRegion(rewriter, awaitOp, resumeEntry, suspendEntry,
2594 remainingOpsBlock);
2595
2596 // After inlining the ready region, branch from the original await block
2597 // to the beginning of the inlined ready region.
2598 rewriter.setInsertionPointToEnd(awaitBlock);
2599 cir::BrOp::create(rewriter, awaitOp.getLoc(), readyEntry);
2600
2601 flattenSuspendRegion(rewriter, awaitOp, resumeEntry, remainingOpsBlock);
2602 flattenResumeRegion(rewriter, awaitOp, remainingOpsBlock);
2603
2604 rewriter.eraseOp(awaitOp);
2605 return mlir::success();
2606 }
2607};
2608
2609void populateFlattenCFGPatterns(RewritePatternSet &patterns) {
2610 patterns
2611 .add<CIRIfFlattening, CIRLoopOpInterfaceFlattening, CIRScopeOpFlattening,
2612 CIRSwitchOpFlattening, CIRTernaryOpFlattening,
2613 CIRCleanupScopeOpFlattening, CIRTryOpFlattening,
2614 CIRAwaitOpFlattening, CIRCoroutineFlattening>(patterns.getContext());
2615}
2616
2617namespace {
2618// An implementation of RewriterBase::Listener that determines whether the IR
2619// has been modified since the last time it was 'reset'. At the moment, this is
2620// the only use for something like this, but we might wish to move this
2621// somewhere if someone else needs similar functionality in the future.
2622class MLIRChangedListener final : public mlir::RewriterBase::Listener {
2623 bool hasChanged = false;
2624
2625public:
2626 void reset() { hasChanged = false; }
2627
2628 bool changed() const { return hasChanged; }
2629
2630 void notifyBlockErased(Block *) override { hasChanged = true; }
2631 void notifyOperationModified(Operation *) override { hasChanged = true; }
2632 void notifyOperationReplaced(Operation *, Operation *) override {
2633 hasChanged = true;
2634 }
2635 void notifyOperationReplaced(Operation *, ValueRange) override {
2636 hasChanged = true;
2637 }
2638 void notifyOperationErased(Operation *) override { hasChanged = true; }
2639
2640 // notifyPatternBegin, notifyPatternEnd, notifyMatchFailure all skipped, since
2641 // they don't modify.
2642 void notifyOperationInserted(Operation *,
2643 mlir::IRRewriter::InsertPoint) override {
2644 hasChanged = true;
2645 }
2646 void notifyBlockInserted(Block *, Region *, Region::iterator) override {
2647 hasChanged = true;
2648 }
2649};
2650} // namespace
2651
2652void CIRFlattenCFGPass::runOnOperation() {
2653 RewritePatternSet patternList(&getContext());
2654 populateFlattenCFGPatterns(patternList);
2655 FrozenRewritePatternSet patterns(std::move(patternList));
2656
2657 PatternApplicator applicator(patterns);
2658 // We need _A_ cost model, and everything here is the same cost-model, so this
2659 // is effectively a no-op, but necessary to use the PatternApplicator.
2660 applicator.applyDefaultCostModel();
2661
2662 mlir::PatternRewriter rewriter(&getContext());
2663 MLIRChangedListener changedListener;
2664 rewriter.setListener(&changedListener);
2665
2666 do {
2667 changedListener.reset();
2668
2669 // Collect flatten candidates post-order so an inner op is handled before
2670 // its parent; op pointers stay valid across the block splits / region
2671 // inlines the patterns perform (a pattern only erases the matched op and
2672 // its descendants, which are visited first), so the list can be iterated
2673 // directly.
2674 llvm::SmallVector<Operation *, 16> ops;
2675 getOperation()->walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
2676 if (isa<IfOp, ScopeOp, SwitchOp, LoopOpInterface, TernaryOp,
2677 CleanupScopeOp, TryOp, AwaitOp, CoroutineOp>(op))
2678 ops.push_back(op);
2679 });
2680
2681 for (mlir::Operation *op : ops) {
2682 rewriter.setInsertionPoint(op);
2683 (void)applicator.matchAndRewrite(op, rewriter);
2684 }
2685 } while (changedListener.changed());
2686}
2687
2688} // namespace
2689
2690namespace mlir {
2691
2692std::unique_ptr<Pass> createCIRFlattenCFGPass() {
2693 return std::make_unique<CIRFlattenCFGPass>();
2694}
2695
2696} // namespace mlir
if(__y==0) return __x
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.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition Format.cpp:4564
llvm::APInt APInt
Definition FixedPoint.h:19
ASTEdit insertBefore(RangeSelector S, TextGenerator Replacement)
Inserts Replacement before S, leaving the source selected by \S unchanged.
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCIRFlattenCFGPass()
int const char * function
Definition c++config.h:31
float __ovld __cnfn step(float, float)
Returns 0.0 if x < edge, otherwise it returns 1.0.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool stackSaveOp()
static bool coroGetRetObjManager()
static bool coroUnwindRegion()