|
| 1 | +//===- StackReclaim.cpp -- Insert stacksave/stackrestore in region --------===// |
| 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 | +#include "flang/Common/Fortran.h" |
| 10 | +#include "flang/Optimizer/Dialect/FIRDialect.h" |
| 11 | +#include "flang/Optimizer/Dialect/FIROps.h" |
| 12 | +#include "flang/Optimizer/Transforms/Passes.h" |
| 13 | +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" |
| 14 | +#include "mlir/IR/Matchers.h" |
| 15 | +#include "mlir/Pass/Pass.h" |
| 16 | + |
| 17 | +namespace fir { |
| 18 | +#define GEN_PASS_DEF_STACKRECLAIM |
| 19 | +#include "flang/Optimizer/Transforms/Passes.h.inc" |
| 20 | +} // namespace fir |
| 21 | + |
| 22 | +using namespace mlir; |
| 23 | + |
| 24 | +namespace { |
| 25 | + |
| 26 | +class StackReclaimPass : public fir::impl::StackReclaimBase<StackReclaimPass> { |
| 27 | +public: |
| 28 | + using StackReclaimBase<StackReclaimPass>::StackReclaimBase; |
| 29 | + |
| 30 | + void runOnOperation() override; |
| 31 | +}; |
| 32 | +} // namespace |
| 33 | + |
| 34 | +void StackReclaimPass::runOnOperation() { |
| 35 | + auto *op = getOperation(); |
| 36 | + auto *context = &getContext(); |
| 37 | + mlir::OpBuilder builder(context); |
| 38 | + mlir::Type voidPtr = mlir::LLVM::LLVMPointerType::get(context); |
| 39 | + |
| 40 | + op->walk([&](fir::DoLoopOp loopOp) { |
| 41 | + mlir::Location loc = loopOp.getLoc(); |
| 42 | + |
| 43 | + if (!loopOp.getRegion().getOps<fir::AllocaOp>().empty()) { |
| 44 | + builder.setInsertionPointToStart(&loopOp.getRegion().front()); |
| 45 | + auto stackSaveOp = builder.create<LLVM::StackSaveOp>(loc, voidPtr); |
| 46 | + |
| 47 | + auto *terminator = loopOp.getRegion().back().getTerminator(); |
| 48 | + builder.setInsertionPoint(terminator); |
| 49 | + builder.create<LLVM::StackRestoreOp>(loc, stackSaveOp); |
| 50 | + } |
| 51 | + }); |
| 52 | +} |
0 commit comments