xref: /llvm-project/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp (revision b33166472c17b51b0b70a72424c2387e95f11b2d)
1fe252f8eSValentin Clement //===-- BoxedProcedure.cpp ------------------------------------------------===//
2fe252f8eSValentin Clement //
3fe252f8eSValentin Clement // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe252f8eSValentin Clement // See https://llvm.org/LICENSE.txt for license information.
5fe252f8eSValentin Clement // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe252f8eSValentin Clement //
7fe252f8eSValentin Clement //===----------------------------------------------------------------------===//
8fe252f8eSValentin Clement 
967d0d7acSMichele Scuttari #include "flang/Optimizer/CodeGen/CodeGen.h"
1067d0d7acSMichele Scuttari 
11fe252f8eSValentin Clement #include "flang/Optimizer/Builder/FIRBuilder.h"
12fe252f8eSValentin Clement #include "flang/Optimizer/Builder/LowLevelIntrinsics.h"
13fe252f8eSValentin Clement #include "flang/Optimizer/Dialect/FIRDialect.h"
14fe252f8eSValentin Clement #include "flang/Optimizer/Dialect/FIROps.h"
15fe252f8eSValentin Clement #include "flang/Optimizer/Dialect/FIRType.h"
16b07ef9e7SRenaud-K #include "flang/Optimizer/Dialect/Support/FIRContext.h"
17fe252f8eSValentin Clement #include "flang/Optimizer/Support/FatalError.h"
187de3c03eSPeixin Qiao #include "flang/Optimizer/Support/InternalNames.h"
19fe252f8eSValentin Clement #include "mlir/IR/PatternMatch.h"
20fe252f8eSValentin Clement #include "mlir/Pass/Pass.h"
21fe252f8eSValentin Clement #include "mlir/Transforms/DialectConversion.h"
22df3f0eeeSjeanPerier #include "llvm/ADT/DenseMap.h"
23fe252f8eSValentin Clement 
2467d0d7acSMichele Scuttari namespace fir {
2567d0d7acSMichele Scuttari #define GEN_PASS_DEF_BOXEDPROCEDUREPASS
2667d0d7acSMichele Scuttari #include "flang/Optimizer/CodeGen/CGPasses.h.inc"
2767d0d7acSMichele Scuttari } // namespace fir
2867d0d7acSMichele Scuttari 
29fe252f8eSValentin Clement #define DEBUG_TYPE "flang-procedure-pointer"
30fe252f8eSValentin Clement 
31fe252f8eSValentin Clement using namespace fir;
32fe252f8eSValentin Clement 
33fe252f8eSValentin Clement namespace {
34fe252f8eSValentin Clement /// Options to the procedure pointer pass.
35fe252f8eSValentin Clement struct BoxedProcedureOptions {
36fe252f8eSValentin Clement   // Lower the boxproc abstraction to function pointers and thunks where
37fe252f8eSValentin Clement   // required.
38fe252f8eSValentin Clement   bool useThunks = true;
39fe252f8eSValentin Clement };
40fe252f8eSValentin Clement 
41fe252f8eSValentin Clement /// This type converter rewrites all `!fir.boxproc<Func>` types to `Func` types.
42fe252f8eSValentin Clement class BoxprocTypeRewriter : public mlir::TypeConverter {
43fe252f8eSValentin Clement public:
44fe252f8eSValentin Clement   using mlir::TypeConverter::convertType;
45fe252f8eSValentin Clement 
46fe252f8eSValentin Clement   /// Does the type \p ty need to be converted?
47fe252f8eSValentin Clement   /// Any type that is a `!fir.boxproc` in whole or in part will need to be
48fe252f8eSValentin Clement   /// converted to a function type to lower the IR to function pointer form in
49fe252f8eSValentin Clement   /// the default implementation performed in this pass. Other implementations
50fe252f8eSValentin Clement   /// are possible, so those may convert `!fir.boxproc` to some other type or
51fe252f8eSValentin Clement   /// not at all depending on the implementation target's characteristics and
52fe252f8eSValentin Clement   /// preference.
53fe252f8eSValentin Clement   bool needsConversion(mlir::Type ty) {
54fe252f8eSValentin Clement     if (ty.isa<BoxProcType>())
55fe252f8eSValentin Clement       return true;
56fe252f8eSValentin Clement     if (auto funcTy = ty.dyn_cast<mlir::FunctionType>()) {
57fe252f8eSValentin Clement       for (auto t : funcTy.getInputs())
58fe252f8eSValentin Clement         if (needsConversion(t))
59fe252f8eSValentin Clement           return true;
60fe252f8eSValentin Clement       for (auto t : funcTy.getResults())
61fe252f8eSValentin Clement         if (needsConversion(t))
62fe252f8eSValentin Clement           return true;
63fe252f8eSValentin Clement       return false;
64fe252f8eSValentin Clement     }
65fe252f8eSValentin Clement     if (auto tupleTy = ty.dyn_cast<mlir::TupleType>()) {
66fe252f8eSValentin Clement       for (auto t : tupleTy.getTypes())
67fe252f8eSValentin Clement         if (needsConversion(t))
68fe252f8eSValentin Clement           return true;
69fe252f8eSValentin Clement       return false;
70fe252f8eSValentin Clement     }
71fe252f8eSValentin Clement     if (auto recTy = ty.dyn_cast<RecordType>()) {
72a0e9a8daSjeanPerier       auto visited = visitedTypes.find(ty);
73a0e9a8daSjeanPerier       if (visited != visitedTypes.end())
74a0e9a8daSjeanPerier         return visited->second;
75a0e9a8daSjeanPerier       [[maybe_unused]] auto newIt = visitedTypes.try_emplace(ty, false);
76a0e9a8daSjeanPerier       assert(newIt.second && "expected ty to not be in the map");
77a0e9a8daSjeanPerier       bool wasAlreadyVisitingRecordType = needConversionIsVisitingRecordType;
78a0e9a8daSjeanPerier       needConversionIsVisitingRecordType = true;
79fe252f8eSValentin Clement       bool result = false;
80fe252f8eSValentin Clement       for (auto t : recTy.getTypeList()) {
81fe252f8eSValentin Clement         if (needsConversion(t.second)) {
82fe252f8eSValentin Clement           result = true;
83fe252f8eSValentin Clement           break;
84fe252f8eSValentin Clement         }
85fe252f8eSValentin Clement       }
86a0e9a8daSjeanPerier       // Only keep the result cached if the fir.type visited was a "top-level
87a0e9a8daSjeanPerier       // type". Nested types with a recursive reference to the "top-level type"
88a0e9a8daSjeanPerier       // may incorrectly have been resolved as not needed conversions because it
89a0e9a8daSjeanPerier       // had not been determined yet if the "top-level type" needed conversion.
90a0e9a8daSjeanPerier       // This is not an issue to determine the "top-level type" need of
91a0e9a8daSjeanPerier       // conversion, but the result should not be kept and later used in other
92a0e9a8daSjeanPerier       // contexts.
93a0e9a8daSjeanPerier       needConversionIsVisitingRecordType = wasAlreadyVisitingRecordType;
94a0e9a8daSjeanPerier       if (needConversionIsVisitingRecordType)
95a0e9a8daSjeanPerier         visitedTypes.erase(ty);
96a0e9a8daSjeanPerier       else
97a0e9a8daSjeanPerier         visitedTypes.find(ty)->second = result;
98fe252f8eSValentin Clement       return result;
99fe252f8eSValentin Clement     }
100c373f581SjeanPerier     if (auto boxTy = ty.dyn_cast<BaseBoxType>())
101fe252f8eSValentin Clement       return needsConversion(boxTy.getEleTy());
102fe252f8eSValentin Clement     if (isa_ref_type(ty))
103fe252f8eSValentin Clement       return needsConversion(unwrapRefType(ty));
104fe252f8eSValentin Clement     if (auto t = ty.dyn_cast<SequenceType>())
105fe252f8eSValentin Clement       return needsConversion(unwrapSequenceType(ty));
106fe252f8eSValentin Clement     return false;
107fe252f8eSValentin Clement   }
108fe252f8eSValentin Clement 
109a370a4ffSjeanPerier   BoxprocTypeRewriter(mlir::Location location) : loc{location} {
110fe252f8eSValentin Clement     addConversion([](mlir::Type ty) { return ty; });
111a370a4ffSjeanPerier     addConversion(
112a370a4ffSjeanPerier         [&](BoxProcType boxproc) { return convertType(boxproc.getEleTy()); });
113fe252f8eSValentin Clement     addConversion([&](mlir::TupleType tupTy) {
114fe252f8eSValentin Clement       llvm::SmallVector<mlir::Type> memTys;
115fe252f8eSValentin Clement       for (auto ty : tupTy.getTypes())
116fe252f8eSValentin Clement         memTys.push_back(convertType(ty));
117fe252f8eSValentin Clement       return mlir::TupleType::get(tupTy.getContext(), memTys);
118fe252f8eSValentin Clement     });
119fe252f8eSValentin Clement     addConversion([&](mlir::FunctionType funcTy) {
120fe252f8eSValentin Clement       llvm::SmallVector<mlir::Type> inTys;
121fe252f8eSValentin Clement       llvm::SmallVector<mlir::Type> resTys;
122fe252f8eSValentin Clement       for (auto ty : funcTy.getInputs())
123fe252f8eSValentin Clement         inTys.push_back(convertType(ty));
124fe252f8eSValentin Clement       for (auto ty : funcTy.getResults())
125fe252f8eSValentin Clement         resTys.push_back(convertType(ty));
126fe252f8eSValentin Clement       return mlir::FunctionType::get(funcTy.getContext(), inTys, resTys);
127fe252f8eSValentin Clement     });
128fe252f8eSValentin Clement     addConversion([&](ReferenceType ty) {
129fe252f8eSValentin Clement       return ReferenceType::get(convertType(ty.getEleTy()));
130fe252f8eSValentin Clement     });
131fe252f8eSValentin Clement     addConversion([&](PointerType ty) {
132fe252f8eSValentin Clement       return PointerType::get(convertType(ty.getEleTy()));
133fe252f8eSValentin Clement     });
134fe252f8eSValentin Clement     addConversion(
135fe252f8eSValentin Clement         [&](HeapType ty) { return HeapType::get(convertType(ty.getEleTy())); });
136c373f581SjeanPerier     addConversion([&](fir::LLVMPointerType ty) {
137c373f581SjeanPerier       return fir::LLVMPointerType::get(convertType(ty.getEleTy()));
138c373f581SjeanPerier     });
139fe252f8eSValentin Clement     addConversion(
140fe252f8eSValentin Clement         [&](BoxType ty) { return BoxType::get(convertType(ty.getEleTy())); });
141c373f581SjeanPerier     addConversion([&](ClassType ty) {
142c373f581SjeanPerier       return ClassType::get(convertType(ty.getEleTy()));
143c373f581SjeanPerier     });
144fe252f8eSValentin Clement     addConversion([&](SequenceType ty) {
145fe252f8eSValentin Clement       // TODO: add ty.getLayoutMap() as needed.
146fe252f8eSValentin Clement       return SequenceType::get(ty.getShape(), convertType(ty.getEleTy()));
147fe252f8eSValentin Clement     });
148a370a4ffSjeanPerier     addConversion([&](RecordType ty) -> mlir::Type {
149a370a4ffSjeanPerier       if (!needsConversion(ty))
150a370a4ffSjeanPerier         return ty;
151df3f0eeeSjeanPerier       if (auto converted = convertedTypes.lookup(ty))
152c373f581SjeanPerier         return converted;
1537de3c03eSPeixin Qiao       auto rec = RecordType::get(ty.getContext(),
1547de3c03eSPeixin Qiao                                  ty.getName().str() + boxprocSuffix.str());
1557de3c03eSPeixin Qiao       if (rec.isFinalized())
1567de3c03eSPeixin Qiao         return rec;
157*b3316647SJie Fu       [[maybe_unused]] auto it = convertedTypes.try_emplace(ty, rec);
158a0e9a8daSjeanPerier       assert(it.second && "expected ty to not be in the map");
1597de3c03eSPeixin Qiao       std::vector<RecordType::TypePair> ps = ty.getLenParamList();
1607de3c03eSPeixin Qiao       std::vector<RecordType::TypePair> cs;
1617de3c03eSPeixin Qiao       for (auto t : ty.getTypeList()) {
1627de3c03eSPeixin Qiao         if (needsConversion(t.second))
1637de3c03eSPeixin Qiao           cs.emplace_back(t.first, convertType(t.second));
1647de3c03eSPeixin Qiao         else
1657de3c03eSPeixin Qiao           cs.emplace_back(t.first, t.second);
1667de3c03eSPeixin Qiao       }
1677de3c03eSPeixin Qiao       rec.finalize(ps, cs);
1687de3c03eSPeixin Qiao       return rec;
169fe252f8eSValentin Clement     });
170fe252f8eSValentin Clement     addArgumentMaterialization(materializeProcedure);
171fe252f8eSValentin Clement     addSourceMaterialization(materializeProcedure);
172fe252f8eSValentin Clement     addTargetMaterialization(materializeProcedure);
173fe252f8eSValentin Clement   }
174fe252f8eSValentin Clement 
175fe252f8eSValentin Clement   static mlir::Value materializeProcedure(mlir::OpBuilder &builder,
176fe252f8eSValentin Clement                                           BoxProcType type,
177fe252f8eSValentin Clement                                           mlir::ValueRange inputs,
178fe252f8eSValentin Clement                                           mlir::Location loc) {
179fe252f8eSValentin Clement     assert(inputs.size() == 1);
180fe252f8eSValentin Clement     return builder.create<ConvertOp>(loc, unwrapRefType(type.getEleTy()),
181fe252f8eSValentin Clement                                      inputs[0]);
182fe252f8eSValentin Clement   }
183fe252f8eSValentin Clement 
184a370a4ffSjeanPerier   void setLocation(mlir::Location location) { loc = location; }
185a370a4ffSjeanPerier 
186fe252f8eSValentin Clement private:
187a0e9a8daSjeanPerier   // Maps to deal with recursive derived types (avoid infinite loops).
188df3f0eeeSjeanPerier   // Caching is also beneficial for apps with big types (dozens of
189df3f0eeeSjeanPerier   // components and or parent types), so the lifetime of the cache
190df3f0eeeSjeanPerier   // is the whole pass.
191a0e9a8daSjeanPerier   llvm::DenseMap<mlir::Type, bool> visitedTypes;
192a0e9a8daSjeanPerier   bool needConversionIsVisitingRecordType = false;
193df3f0eeeSjeanPerier   llvm::DenseMap<mlir::Type, mlir::Type> convertedTypes;
194a370a4ffSjeanPerier   mlir::Location loc;
195fe252f8eSValentin Clement };
196fe252f8eSValentin Clement 
197fe252f8eSValentin Clement /// A `boxproc` is an abstraction for a Fortran procedure reference. Typically,
198fe252f8eSValentin Clement /// Fortran procedures can be referenced directly through a function pointer.
199fe252f8eSValentin Clement /// However, Fortran has one-level dynamic scoping between a host procedure and
200fe252f8eSValentin Clement /// its internal procedures. This allows internal procedures to directly access
201fe252f8eSValentin Clement /// and modify the state of the host procedure's variables.
202fe252f8eSValentin Clement ///
203fe252f8eSValentin Clement /// There are any number of possible implementations possible.
204fe252f8eSValentin Clement ///
205fe252f8eSValentin Clement /// The implementation used here is to convert `boxproc` values to function
206fe252f8eSValentin Clement /// pointers everywhere. If a `boxproc` value includes a frame pointer to the
207fe252f8eSValentin Clement /// host procedure's data, then a thunk will be created at runtime to capture
208fe252f8eSValentin Clement /// the frame pointer during execution. In LLVM IR, the frame pointer is
209fe252f8eSValentin Clement /// designated with the `nest` attribute. The thunk's address will then be used
210fe252f8eSValentin Clement /// as the call target instead of the original function's address directly.
21167d0d7acSMichele Scuttari class BoxedProcedurePass
21267d0d7acSMichele Scuttari     : public fir::impl::BoxedProcedurePassBase<BoxedProcedurePass> {
213fe252f8eSValentin Clement public:
214fe252f8eSValentin Clement   BoxedProcedurePass() { options = {true}; }
215fe252f8eSValentin Clement   BoxedProcedurePass(bool useThunks) { options = {useThunks}; }
216fe252f8eSValentin Clement 
217fe252f8eSValentin Clement   inline mlir::ModuleOp getModule() { return getOperation(); }
218fe252f8eSValentin Clement 
219fe252f8eSValentin Clement   void runOnOperation() override final {
220fe252f8eSValentin Clement     if (options.useThunks) {
221fe252f8eSValentin Clement       auto *context = &getContext();
222fe252f8eSValentin Clement       mlir::IRRewriter rewriter(context);
223a370a4ffSjeanPerier       BoxprocTypeRewriter typeConverter(mlir::UnknownLoc::get(context));
224fe252f8eSValentin Clement       mlir::Dialect *firDialect = context->getLoadedDialect("fir");
225fe252f8eSValentin Clement       getModule().walk([&](mlir::Operation *op) {
226546f32dfSKrzysztof Parzyszek         bool opIsValid = true;
227a370a4ffSjeanPerier         typeConverter.setLocation(op->getLoc());
228fe252f8eSValentin Clement         if (auto addr = mlir::dyn_cast<BoxAddrOp>(op)) {
229c373f581SjeanPerier           mlir::Type ty = addr.getVal().getType();
230c373f581SjeanPerier           mlir::Type resTy = addr.getResult().getType();
231a15ebe02SjeanPerier           if (llvm::isa<mlir::FunctionType>(ty) ||
232a15ebe02SjeanPerier               llvm::isa<fir::BoxProcType>(ty)) {
233fe252f8eSValentin Clement             // Rewrite all `fir.box_addr` ops on values of type `!fir.boxproc`
234fe252f8eSValentin Clement             // or function type to be `fir.convert` ops.
235fe252f8eSValentin Clement             rewriter.setInsertionPoint(addr);
236fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<ConvertOp>(
237fe252f8eSValentin Clement                 addr, typeConverter.convertType(addr.getType()), addr.getVal());
238546f32dfSKrzysztof Parzyszek             opIsValid = false;
239c373f581SjeanPerier           } else if (typeConverter.needsConversion(resTy)) {
2405fcf907bSMatthias Springer             rewriter.startOpModification(op);
241c373f581SjeanPerier             op->getResult(0).setType(typeConverter.convertType(resTy));
2425fcf907bSMatthias Springer             rewriter.finalizeOpModification(op);
243fe252f8eSValentin Clement           }
24458ceae95SRiver Riddle         } else if (auto func = mlir::dyn_cast<mlir::func::FuncOp>(op)) {
245fe252f8eSValentin Clement           mlir::FunctionType ty = func.getFunctionType();
246fe252f8eSValentin Clement           if (typeConverter.needsConversion(ty)) {
2475fcf907bSMatthias Springer             rewriter.startOpModification(func);
248fe252f8eSValentin Clement             auto toTy =
249fe252f8eSValentin Clement                 typeConverter.convertType(ty).cast<mlir::FunctionType>();
250fe252f8eSValentin Clement             if (!func.empty())
251fe252f8eSValentin Clement               for (auto e : llvm::enumerate(toTy.getInputs())) {
252fe252f8eSValentin Clement                 unsigned i = e.index();
253fe252f8eSValentin Clement                 auto &block = func.front();
254fe252f8eSValentin Clement                 block.insertArgument(i, e.value(), func.getLoc());
255fe252f8eSValentin Clement                 block.getArgument(i + 1).replaceAllUsesWith(
256fe252f8eSValentin Clement                     block.getArgument(i));
257fe252f8eSValentin Clement                 block.eraseArgument(i + 1);
258fe252f8eSValentin Clement               }
259fe252f8eSValentin Clement             func.setType(toTy);
2605fcf907bSMatthias Springer             rewriter.finalizeOpModification(func);
261fe252f8eSValentin Clement           }
262fe252f8eSValentin Clement         } else if (auto embox = mlir::dyn_cast<EmboxProcOp>(op)) {
263fe252f8eSValentin Clement           // Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk
264fe252f8eSValentin Clement           // as required.
265c373f581SjeanPerier           mlir::Type toTy = typeConverter.convertType(
266c373f581SjeanPerier               embox.getType().cast<BoxProcType>().getEleTy());
267fe252f8eSValentin Clement           rewriter.setInsertionPoint(embox);
268fe252f8eSValentin Clement           if (embox.getHost()) {
269fe252f8eSValentin Clement             // Create the thunk.
270fe252f8eSValentin Clement             auto module = embox->getParentOfType<mlir::ModuleOp>();
27153cc33b0STom Eccles             FirOpBuilder builder(rewriter, module);
272fe252f8eSValentin Clement             auto loc = embox.getLoc();
273fe252f8eSValentin Clement             mlir::Type i8Ty = builder.getI8Type();
274fe252f8eSValentin Clement             mlir::Type i8Ptr = builder.getRefType(i8Ty);
275fe252f8eSValentin Clement             mlir::Type buffTy = SequenceType::get({32}, i8Ty);
276fe252f8eSValentin Clement             auto buffer = builder.create<AllocaOp>(loc, buffTy);
277fe252f8eSValentin Clement             mlir::Value closure =
278fe252f8eSValentin Clement                 builder.createConvert(loc, i8Ptr, embox.getHost());
279fe252f8eSValentin Clement             mlir::Value tramp = builder.createConvert(loc, i8Ptr, buffer);
280fe252f8eSValentin Clement             mlir::Value func =
281fe252f8eSValentin Clement                 builder.createConvert(loc, i8Ptr, embox.getFunc());
282fe252f8eSValentin Clement             builder.create<fir::CallOp>(
283fe252f8eSValentin Clement                 loc, factory::getLlvmInitTrampoline(builder),
284fe252f8eSValentin Clement                 llvm::ArrayRef<mlir::Value>{tramp, func, closure});
285fe252f8eSValentin Clement             auto adjustCall = builder.create<fir::CallOp>(
286fe252f8eSValentin Clement                 loc, factory::getLlvmAdjustTrampoline(builder),
287fe252f8eSValentin Clement                 llvm::ArrayRef<mlir::Value>{tramp});
288fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy,
289fe252f8eSValentin Clement                                                    adjustCall.getResult(0));
290546f32dfSKrzysztof Parzyszek             opIsValid = false;
291fe252f8eSValentin Clement           } else {
292fe252f8eSValentin Clement             // Just forward the function as a pointer.
293fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy,
294fe252f8eSValentin Clement                                                    embox.getFunc());
295546f32dfSKrzysztof Parzyszek             opIsValid = false;
296fe252f8eSValentin Clement           }
297feb9d33aSPeixin Qiao         } else if (auto global = mlir::dyn_cast<GlobalOp>(op)) {
298feb9d33aSPeixin Qiao           auto ty = global.getType();
299feb9d33aSPeixin Qiao           if (typeConverter.needsConversion(ty)) {
3005fcf907bSMatthias Springer             rewriter.startOpModification(global);
301feb9d33aSPeixin Qiao             auto toTy = typeConverter.convertType(ty);
302feb9d33aSPeixin Qiao             global.setType(toTy);
3035fcf907bSMatthias Springer             rewriter.finalizeOpModification(global);
304feb9d33aSPeixin Qiao           }
305fe252f8eSValentin Clement         } else if (auto mem = mlir::dyn_cast<AllocaOp>(op)) {
306fe252f8eSValentin Clement           auto ty = mem.getType();
307fe252f8eSValentin Clement           if (typeConverter.needsConversion(ty)) {
308fe252f8eSValentin Clement             rewriter.setInsertionPoint(mem);
309fe252f8eSValentin Clement             auto toTy = typeConverter.convertType(unwrapRefType(ty));
310fe252f8eSValentin Clement             bool isPinned = mem.getPinned();
311c715e2ffSKazu Hirata             llvm::StringRef uniqName =
312c715e2ffSKazu Hirata                 mem.getUniqName().value_or(llvm::StringRef());
313c715e2ffSKazu Hirata             llvm::StringRef bindcName =
314c715e2ffSKazu Hirata                 mem.getBindcName().value_or(llvm::StringRef());
315fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<AllocaOp>(
316fe252f8eSValentin Clement                 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(),
317fe252f8eSValentin Clement                 mem.getShape());
318546f32dfSKrzysztof Parzyszek             opIsValid = false;
319fe252f8eSValentin Clement           }
320fe252f8eSValentin Clement         } else if (auto mem = mlir::dyn_cast<AllocMemOp>(op)) {
321fe252f8eSValentin Clement           auto ty = mem.getType();
322fe252f8eSValentin Clement           if (typeConverter.needsConversion(ty)) {
323fe252f8eSValentin Clement             rewriter.setInsertionPoint(mem);
324fe252f8eSValentin Clement             auto toTy = typeConverter.convertType(unwrapRefType(ty));
325c715e2ffSKazu Hirata             llvm::StringRef uniqName =
326c715e2ffSKazu Hirata                 mem.getUniqName().value_or(llvm::StringRef());
327c715e2ffSKazu Hirata             llvm::StringRef bindcName =
328c715e2ffSKazu Hirata                 mem.getBindcName().value_or(llvm::StringRef());
329fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<AllocMemOp>(
330fe252f8eSValentin Clement                 mem, toTy, uniqName, bindcName, mem.getTypeparams(),
331fe252f8eSValentin Clement                 mem.getShape());
332546f32dfSKrzysztof Parzyszek             opIsValid = false;
333fe252f8eSValentin Clement           }
334fe252f8eSValentin Clement         } else if (auto coor = mlir::dyn_cast<CoordinateOp>(op)) {
335fe252f8eSValentin Clement           auto ty = coor.getType();
336fe252f8eSValentin Clement           mlir::Type baseTy = coor.getBaseType();
337fe252f8eSValentin Clement           if (typeConverter.needsConversion(ty) ||
338fe252f8eSValentin Clement               typeConverter.needsConversion(baseTy)) {
339fe252f8eSValentin Clement             rewriter.setInsertionPoint(coor);
340fe252f8eSValentin Clement             auto toTy = typeConverter.convertType(ty);
341fe252f8eSValentin Clement             auto toBaseTy = typeConverter.convertType(baseTy);
342fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<CoordinateOp>(coor, toTy, coor.getRef(),
343fe252f8eSValentin Clement                                                       coor.getCoor(), toBaseTy);
344546f32dfSKrzysztof Parzyszek             opIsValid = false;
345fe252f8eSValentin Clement           }
346fe252f8eSValentin Clement         } else if (auto index = mlir::dyn_cast<FieldIndexOp>(op)) {
347fe252f8eSValentin Clement           auto ty = index.getType();
348fe252f8eSValentin Clement           mlir::Type onTy = index.getOnType();
349fe252f8eSValentin Clement           if (typeConverter.needsConversion(ty) ||
350fe252f8eSValentin Clement               typeConverter.needsConversion(onTy)) {
351fe252f8eSValentin Clement             rewriter.setInsertionPoint(index);
352fe252f8eSValentin Clement             auto toTy = typeConverter.convertType(ty);
353fe252f8eSValentin Clement             auto toOnTy = typeConverter.convertType(onTy);
354fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<FieldIndexOp>(
355fe252f8eSValentin Clement                 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams());
356546f32dfSKrzysztof Parzyszek             opIsValid = false;
357fe252f8eSValentin Clement           }
358fe252f8eSValentin Clement         } else if (auto index = mlir::dyn_cast<LenParamIndexOp>(op)) {
359fe252f8eSValentin Clement           auto ty = index.getType();
360fe252f8eSValentin Clement           mlir::Type onTy = index.getOnType();
361fe252f8eSValentin Clement           if (typeConverter.needsConversion(ty) ||
362fe252f8eSValentin Clement               typeConverter.needsConversion(onTy)) {
363fe252f8eSValentin Clement             rewriter.setInsertionPoint(index);
364fe252f8eSValentin Clement             auto toTy = typeConverter.convertType(ty);
365fe252f8eSValentin Clement             auto toOnTy = typeConverter.convertType(onTy);
366fe252f8eSValentin Clement             rewriter.replaceOpWithNewOp<LenParamIndexOp>(
36765524fcbSKrzysztof Parzyszek                 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams());
368546f32dfSKrzysztof Parzyszek             opIsValid = false;
369fe252f8eSValentin Clement           }
370fe252f8eSValentin Clement         } else if (op->getDialect() == firDialect) {
3715fcf907bSMatthias Springer           rewriter.startOpModification(op);
372fe252f8eSValentin Clement           for (auto i : llvm::enumerate(op->getResultTypes()))
373fe252f8eSValentin Clement             if (typeConverter.needsConversion(i.value())) {
374fe252f8eSValentin Clement               auto toTy = typeConverter.convertType(i.value());
375fe252f8eSValentin Clement               op->getResult(i.index()).setType(toTy);
376fe252f8eSValentin Clement             }
3775fcf907bSMatthias Springer           rewriter.finalizeOpModification(op);
378fe252f8eSValentin Clement         }
37908e4386aSjeanPerier         // Ensure block arguments are updated if needed.
380546f32dfSKrzysztof Parzyszek         if (opIsValid && op->getNumRegions() != 0) {
3815fcf907bSMatthias Springer           rewriter.startOpModification(op);
38208e4386aSjeanPerier           for (mlir::Region &region : op->getRegions())
38308e4386aSjeanPerier             for (mlir::Block &block : region.getBlocks())
38408e4386aSjeanPerier               for (mlir::BlockArgument blockArg : block.getArguments())
38508e4386aSjeanPerier                 if (typeConverter.needsConversion(blockArg.getType())) {
38608e4386aSjeanPerier                   mlir::Type toTy =
38708e4386aSjeanPerier                       typeConverter.convertType(blockArg.getType());
38808e4386aSjeanPerier                   blockArg.setType(toTy);
38908e4386aSjeanPerier                 }
3905fcf907bSMatthias Springer           rewriter.finalizeOpModification(op);
39108e4386aSjeanPerier         }
392fe252f8eSValentin Clement       });
393fe252f8eSValentin Clement     }
394fe252f8eSValentin Clement   }
395fe252f8eSValentin Clement 
396fe252f8eSValentin Clement private:
397fe252f8eSValentin Clement   BoxedProcedureOptions options;
398fe252f8eSValentin Clement };
399fe252f8eSValentin Clement } // namespace
400fe252f8eSValentin Clement 
401fe252f8eSValentin Clement std::unique_ptr<mlir::Pass> fir::createBoxedProcedurePass() {
402fe252f8eSValentin Clement   return std::make_unique<BoxedProcedurePass>();
403fe252f8eSValentin Clement }
404fe252f8eSValentin Clement 
405fe252f8eSValentin Clement std::unique_ptr<mlir::Pass> fir::createBoxedProcedurePass(bool useThunks) {
406fe252f8eSValentin Clement   return std::make_unique<BoxedProcedurePass>(useThunks);
407fe252f8eSValentin Clement }
408