xref: /llvm-project/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp (revision 039b969b32b64b64123dce30dd28ec4e343d893f)
1 //===-- BoxedProcedure.cpp ------------------------------------------------===//
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 "PassDetail.h"
10 #include "flang/Optimizer/Builder/FIRBuilder.h"
11 #include "flang/Optimizer/Builder/LowLevelIntrinsics.h"
12 #include "flang/Optimizer/CodeGen/CodeGen.h"
13 #include "flang/Optimizer/Dialect/FIRDialect.h"
14 #include "flang/Optimizer/Dialect/FIROps.h"
15 #include "flang/Optimizer/Dialect/FIRType.h"
16 #include "flang/Optimizer/Support/FIRContext.h"
17 #include "flang/Optimizer/Support/FatalError.h"
18 #include "mlir/IR/PatternMatch.h"
19 #include "mlir/Pass/Pass.h"
20 #include "mlir/Transforms/DialectConversion.h"
21 
22 #define DEBUG_TYPE "flang-procedure-pointer"
23 
24 using namespace fir;
25 
26 namespace {
27 /// Options to the procedure pointer pass.
28 struct BoxedProcedureOptions {
29   // Lower the boxproc abstraction to function pointers and thunks where
30   // required.
31   bool useThunks = true;
32 };
33 
34 /// This type converter rewrites all `!fir.boxproc<Func>` types to `Func` types.
35 class BoxprocTypeRewriter : public mlir::TypeConverter {
36 public:
37   using mlir::TypeConverter::convertType;
38 
39   /// Does the type \p ty need to be converted?
40   /// Any type that is a `!fir.boxproc` in whole or in part will need to be
41   /// converted to a function type to lower the IR to function pointer form in
42   /// the default implementation performed in this pass. Other implementations
43   /// are possible, so those may convert `!fir.boxproc` to some other type or
44   /// not at all depending on the implementation target's characteristics and
45   /// preference.
46   bool needsConversion(mlir::Type ty) {
47     if (ty.isa<BoxProcType>())
48       return true;
49     if (auto funcTy = ty.dyn_cast<mlir::FunctionType>()) {
50       for (auto t : funcTy.getInputs())
51         if (needsConversion(t))
52           return true;
53       for (auto t : funcTy.getResults())
54         if (needsConversion(t))
55           return true;
56       return false;
57     }
58     if (auto tupleTy = ty.dyn_cast<mlir::TupleType>()) {
59       for (auto t : tupleTy.getTypes())
60         if (needsConversion(t))
61           return true;
62       return false;
63     }
64     if (auto recTy = ty.dyn_cast<RecordType>()) {
65       if (llvm::is_contained(visitedTypes, recTy))
66         return false;
67       bool result = false;
68       visitedTypes.push_back(recTy);
69       for (auto t : recTy.getTypeList()) {
70         if (needsConversion(t.second)) {
71           result = true;
72           break;
73         }
74       }
75       visitedTypes.pop_back();
76       return result;
77     }
78     if (auto boxTy = ty.dyn_cast<BoxType>())
79       return needsConversion(boxTy.getEleTy());
80     if (isa_ref_type(ty))
81       return needsConversion(unwrapRefType(ty));
82     if (auto t = ty.dyn_cast<SequenceType>())
83       return needsConversion(unwrapSequenceType(ty));
84     return false;
85   }
86 
87   BoxprocTypeRewriter(mlir::Location location) : loc{location} {
88     addConversion([](mlir::Type ty) { return ty; });
89     addConversion(
90         [&](BoxProcType boxproc) { return convertType(boxproc.getEleTy()); });
91     addConversion([&](mlir::TupleType tupTy) {
92       llvm::SmallVector<mlir::Type> memTys;
93       for (auto ty : tupTy.getTypes())
94         memTys.push_back(convertType(ty));
95       return mlir::TupleType::get(tupTy.getContext(), memTys);
96     });
97     addConversion([&](mlir::FunctionType funcTy) {
98       llvm::SmallVector<mlir::Type> inTys;
99       llvm::SmallVector<mlir::Type> resTys;
100       for (auto ty : funcTy.getInputs())
101         inTys.push_back(convertType(ty));
102       for (auto ty : funcTy.getResults())
103         resTys.push_back(convertType(ty));
104       return mlir::FunctionType::get(funcTy.getContext(), inTys, resTys);
105     });
106     addConversion([&](ReferenceType ty) {
107       return ReferenceType::get(convertType(ty.getEleTy()));
108     });
109     addConversion([&](PointerType ty) {
110       return PointerType::get(convertType(ty.getEleTy()));
111     });
112     addConversion(
113         [&](HeapType ty) { return HeapType::get(convertType(ty.getEleTy())); });
114     addConversion(
115         [&](BoxType ty) { return BoxType::get(convertType(ty.getEleTy())); });
116     addConversion([&](SequenceType ty) {
117       // TODO: add ty.getLayoutMap() as needed.
118       return SequenceType::get(ty.getShape(), convertType(ty.getEleTy()));
119     });
120     addConversion([&](RecordType ty) -> mlir::Type {
121       if (!needsConversion(ty))
122         return ty;
123       // FIR record types can have recursive references, so conversion is a bit
124       // more complex than the other types. This conversion is not needed
125       // presently, so just emit a TODO message. Need to consider the uniqued
126       // name of the record, etc. Also, fir::RecordType::get returns the
127       // existing type being translated. So finalize() will not change it, and
128       // the translation would not do anything. So the type needs to be mutated,
129       // and this might require special care to comply with MLIR infrastructure.
130 
131       // TODO: this will be needed to support derived type containing procedure
132       // pointer components.
133       fir::emitFatalError(
134           loc, "not yet implemented: record type with a boxproc type");
135       return RecordType::get(ty.getContext(), "*fixme*");
136     });
137     addArgumentMaterialization(materializeProcedure);
138     addSourceMaterialization(materializeProcedure);
139     addTargetMaterialization(materializeProcedure);
140   }
141 
142   static mlir::Value materializeProcedure(mlir::OpBuilder &builder,
143                                           BoxProcType type,
144                                           mlir::ValueRange inputs,
145                                           mlir::Location loc) {
146     assert(inputs.size() == 1);
147     return builder.create<ConvertOp>(loc, unwrapRefType(type.getEleTy()),
148                                      inputs[0]);
149   }
150 
151   void setLocation(mlir::Location location) { loc = location; }
152 
153 private:
154   llvm::SmallVector<mlir::Type> visitedTypes;
155   mlir::Location loc;
156 };
157 
158 /// A `boxproc` is an abstraction for a Fortran procedure reference. Typically,
159 /// Fortran procedures can be referenced directly through a function pointer.
160 /// However, Fortran has one-level dynamic scoping between a host procedure and
161 /// its internal procedures. This allows internal procedures to directly access
162 /// and modify the state of the host procedure's variables.
163 ///
164 /// There are any number of possible implementations possible.
165 ///
166 /// The implementation used here is to convert `boxproc` values to function
167 /// pointers everywhere. If a `boxproc` value includes a frame pointer to the
168 /// host procedure's data, then a thunk will be created at runtime to capture
169 /// the frame pointer during execution. In LLVM IR, the frame pointer is
170 /// designated with the `nest` attribute. The thunk's address will then be used
171 /// as the call target instead of the original function's address directly.
172 class BoxedProcedurePass : public BoxedProcedurePassBase<BoxedProcedurePass> {
173 public:
174   BoxedProcedurePass() { options = {true}; }
175   BoxedProcedurePass(bool useThunks) { options = {useThunks}; }
176 
177   inline mlir::ModuleOp getModule() { return getOperation(); }
178 
179   void runOnOperation() override final {
180     if (options.useThunks) {
181       auto *context = &getContext();
182       mlir::IRRewriter rewriter(context);
183       BoxprocTypeRewriter typeConverter(mlir::UnknownLoc::get(context));
184       mlir::Dialect *firDialect = context->getLoadedDialect("fir");
185       getModule().walk([&](mlir::Operation *op) {
186         typeConverter.setLocation(op->getLoc());
187         if (auto addr = mlir::dyn_cast<BoxAddrOp>(op)) {
188           auto ty = addr.getVal().getType();
189           if (typeConverter.needsConversion(ty) ||
190               ty.isa<mlir::FunctionType>()) {
191             // Rewrite all `fir.box_addr` ops on values of type `!fir.boxproc`
192             // or function type to be `fir.convert` ops.
193             rewriter.setInsertionPoint(addr);
194             rewriter.replaceOpWithNewOp<ConvertOp>(
195                 addr, typeConverter.convertType(addr.getType()), addr.getVal());
196           }
197         } else if (auto func = mlir::dyn_cast<mlir::func::FuncOp>(op)) {
198           mlir::FunctionType ty = func.getFunctionType();
199           if (typeConverter.needsConversion(ty)) {
200             rewriter.startRootUpdate(func);
201             auto toTy =
202                 typeConverter.convertType(ty).cast<mlir::FunctionType>();
203             if (!func.empty())
204               for (auto e : llvm::enumerate(toTy.getInputs())) {
205                 unsigned i = e.index();
206                 auto &block = func.front();
207                 block.insertArgument(i, e.value(), func.getLoc());
208                 block.getArgument(i + 1).replaceAllUsesWith(
209                     block.getArgument(i));
210                 block.eraseArgument(i + 1);
211               }
212             func.setType(toTy);
213             rewriter.finalizeRootUpdate(func);
214           }
215         } else if (auto embox = mlir::dyn_cast<EmboxProcOp>(op)) {
216           // Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk
217           // as required.
218           mlir::Type toTy = embox.getType().cast<BoxProcType>().getEleTy();
219           rewriter.setInsertionPoint(embox);
220           if (embox.getHost()) {
221             // Create the thunk.
222             auto module = embox->getParentOfType<mlir::ModuleOp>();
223             fir::KindMapping kindMap = getKindMapping(module);
224             FirOpBuilder builder(rewriter, kindMap);
225             auto loc = embox.getLoc();
226             mlir::Type i8Ty = builder.getI8Type();
227             mlir::Type i8Ptr = builder.getRefType(i8Ty);
228             mlir::Type buffTy = SequenceType::get({32}, i8Ty);
229             auto buffer = builder.create<AllocaOp>(loc, buffTy);
230             mlir::Value closure =
231                 builder.createConvert(loc, i8Ptr, embox.getHost());
232             mlir::Value tramp = builder.createConvert(loc, i8Ptr, buffer);
233             mlir::Value func =
234                 builder.createConvert(loc, i8Ptr, embox.getFunc());
235             builder.create<fir::CallOp>(
236                 loc, factory::getLlvmInitTrampoline(builder),
237                 llvm::ArrayRef<mlir::Value>{tramp, func, closure});
238             auto adjustCall = builder.create<fir::CallOp>(
239                 loc, factory::getLlvmAdjustTrampoline(builder),
240                 llvm::ArrayRef<mlir::Value>{tramp});
241             rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy,
242                                                    adjustCall.getResult(0));
243           } else {
244             // Just forward the function as a pointer.
245             rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy,
246                                                    embox.getFunc());
247           }
248         } else if (auto mem = mlir::dyn_cast<AllocaOp>(op)) {
249           auto ty = mem.getType();
250           if (typeConverter.needsConversion(ty)) {
251             rewriter.setInsertionPoint(mem);
252             auto toTy = typeConverter.convertType(unwrapRefType(ty));
253             bool isPinned = mem.getPinned();
254             llvm::StringRef uniqName =
255                 mem.getUniqName().value_or(llvm::StringRef());
256             llvm::StringRef bindcName =
257                 mem.getBindcName().value_or(llvm::StringRef());
258             rewriter.replaceOpWithNewOp<AllocaOp>(
259                 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(),
260                 mem.getShape());
261           }
262         } else if (auto mem = mlir::dyn_cast<AllocMemOp>(op)) {
263           auto ty = mem.getType();
264           if (typeConverter.needsConversion(ty)) {
265             rewriter.setInsertionPoint(mem);
266             auto toTy = typeConverter.convertType(unwrapRefType(ty));
267             llvm::StringRef uniqName =
268                 mem.getUniqName().value_or(llvm::StringRef());
269             llvm::StringRef bindcName =
270                 mem.getBindcName().value_or(llvm::StringRef());
271             rewriter.replaceOpWithNewOp<AllocMemOp>(
272                 mem, toTy, uniqName, bindcName, mem.getTypeparams(),
273                 mem.getShape());
274           }
275         } else if (auto coor = mlir::dyn_cast<CoordinateOp>(op)) {
276           auto ty = coor.getType();
277           mlir::Type baseTy = coor.getBaseType();
278           if (typeConverter.needsConversion(ty) ||
279               typeConverter.needsConversion(baseTy)) {
280             rewriter.setInsertionPoint(coor);
281             auto toTy = typeConverter.convertType(ty);
282             auto toBaseTy = typeConverter.convertType(baseTy);
283             rewriter.replaceOpWithNewOp<CoordinateOp>(coor, toTy, coor.getRef(),
284                                                       coor.getCoor(), toBaseTy);
285           }
286         } else if (auto index = mlir::dyn_cast<FieldIndexOp>(op)) {
287           auto ty = index.getType();
288           mlir::Type onTy = index.getOnType();
289           if (typeConverter.needsConversion(ty) ||
290               typeConverter.needsConversion(onTy)) {
291             rewriter.setInsertionPoint(index);
292             auto toTy = typeConverter.convertType(ty);
293             auto toOnTy = typeConverter.convertType(onTy);
294             rewriter.replaceOpWithNewOp<FieldIndexOp>(
295                 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams());
296           }
297         } else if (auto index = mlir::dyn_cast<LenParamIndexOp>(op)) {
298           auto ty = index.getType();
299           mlir::Type onTy = index.getOnType();
300           if (typeConverter.needsConversion(ty) ||
301               typeConverter.needsConversion(onTy)) {
302             rewriter.setInsertionPoint(index);
303             auto toTy = typeConverter.convertType(ty);
304             auto toOnTy = typeConverter.convertType(onTy);
305             rewriter.replaceOpWithNewOp<LenParamIndexOp>(
306                 mem, toTy, index.getFieldId(), toOnTy, index.getTypeparams());
307           }
308         } else if (op->getDialect() == firDialect) {
309           rewriter.startRootUpdate(op);
310           for (auto i : llvm::enumerate(op->getResultTypes()))
311             if (typeConverter.needsConversion(i.value())) {
312               auto toTy = typeConverter.convertType(i.value());
313               op->getResult(i.index()).setType(toTy);
314             }
315           rewriter.finalizeRootUpdate(op);
316         }
317       });
318     }
319     // TODO: any alternative implementation. Note: currently, the default code
320     // gen will not be able to handle boxproc and will give an error.
321   }
322 
323 private:
324   BoxedProcedureOptions options;
325 };
326 } // namespace
327 
328 std::unique_ptr<mlir::Pass> fir::createBoxedProcedurePass() {
329   return std::make_unique<BoxedProcedurePass>();
330 }
331 
332 std::unique_ptr<mlir::Pass> fir::createBoxedProcedurePass(bool useThunks) {
333   return std::make_unique<BoxedProcedurePass>(useThunks);
334 }
335