xref: /llvm-project/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp (revision fe252f8ed6369acdb13d4e290d3b9dfe2ec4eb8e)
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       bool result = false;
66       visitedTypes.push_back(recTy);
67       for (auto t : recTy.getTypeList()) {
68         if (llvm::any_of(visitedTypes,
69                          [&](mlir::Type rt) { return rt == recTy; }))
70           continue;
71         if (needsConversion(t.second)) {
72           result = true;
73           break;
74         }
75       }
76       visitedTypes.pop_back();
77       return result;
78     }
79     if (auto boxTy = ty.dyn_cast<BoxType>())
80       return needsConversion(boxTy.getEleTy());
81     if (isa_ref_type(ty))
82       return needsConversion(unwrapRefType(ty));
83     if (auto t = ty.dyn_cast<SequenceType>())
84       return needsConversion(unwrapSequenceType(ty));
85     return false;
86   }
87 
88   BoxprocTypeRewriter() {
89     addConversion([](mlir::Type ty) { return ty; });
90     addConversion([](BoxProcType boxproc) { return 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) {
121       // FIR record types can have recursive references, so conversion is a bit
122       // more complex than the other types. This conversion is not needed
123       // presently, so just emit a TODO message. Need to consider the uniqued
124       // name of the record, etc.
125       fir::emitFatalError(
126           mlir::UnknownLoc::get(ty.getContext()),
127           "not yet implemented: record type with a boxproc type");
128       return RecordType::get(ty.getContext(), "*fixme*");
129     });
130     addArgumentMaterialization(materializeProcedure);
131     addSourceMaterialization(materializeProcedure);
132     addTargetMaterialization(materializeProcedure);
133   }
134 
135   static mlir::Value materializeProcedure(mlir::OpBuilder &builder,
136                                           BoxProcType type,
137                                           mlir::ValueRange inputs,
138                                           mlir::Location loc) {
139     assert(inputs.size() == 1);
140     return builder.create<ConvertOp>(loc, unwrapRefType(type.getEleTy()),
141                                      inputs[0]);
142   }
143 
144 private:
145   llvm::SmallVector<mlir::Type> visitedTypes;
146 };
147 
148 /// A `boxproc` is an abstraction for a Fortran procedure reference. Typically,
149 /// Fortran procedures can be referenced directly through a function pointer.
150 /// However, Fortran has one-level dynamic scoping between a host procedure and
151 /// its internal procedures. This allows internal procedures to directly access
152 /// and modify the state of the host procedure's variables.
153 ///
154 /// There are any number of possible implementations possible.
155 ///
156 /// The implementation used here is to convert `boxproc` values to function
157 /// pointers everywhere. If a `boxproc` value includes a frame pointer to the
158 /// host procedure's data, then a thunk will be created at runtime to capture
159 /// the frame pointer during execution. In LLVM IR, the frame pointer is
160 /// designated with the `nest` attribute. The thunk's address will then be used
161 /// as the call target instead of the original function's address directly.
162 class BoxedProcedurePass : public BoxedProcedurePassBase<BoxedProcedurePass> {
163 public:
164   BoxedProcedurePass() { options = {true}; }
165   BoxedProcedurePass(bool useThunks) { options = {useThunks}; }
166 
167   inline mlir::ModuleOp getModule() { return getOperation(); }
168 
169   void runOnOperation() override final {
170     if (options.useThunks) {
171       auto *context = &getContext();
172       mlir::IRRewriter rewriter(context);
173       BoxprocTypeRewriter typeConverter;
174       mlir::Dialect *firDialect = context->getLoadedDialect("fir");
175       getModule().walk([&](mlir::Operation *op) {
176         if (auto addr = mlir::dyn_cast<BoxAddrOp>(op)) {
177           auto ty = addr.getVal().getType();
178           if (typeConverter.needsConversion(ty) ||
179               ty.isa<mlir::FunctionType>()) {
180             // Rewrite all `fir.box_addr` ops on values of type `!fir.boxproc`
181             // or function type to be `fir.convert` ops.
182             rewriter.setInsertionPoint(addr);
183             rewriter.replaceOpWithNewOp<ConvertOp>(
184                 addr, typeConverter.convertType(addr.getType()), addr.getVal());
185           }
186         } else if (auto func = mlir::dyn_cast<mlir::FuncOp>(op)) {
187           mlir::FunctionType ty = func.getFunctionType();
188           if (typeConverter.needsConversion(ty)) {
189             rewriter.startRootUpdate(func);
190             auto toTy =
191                 typeConverter.convertType(ty).cast<mlir::FunctionType>();
192             if (!func.empty())
193               for (auto e : llvm::enumerate(toTy.getInputs())) {
194                 unsigned i = e.index();
195                 auto &block = func.front();
196                 block.insertArgument(i, e.value(), func.getLoc());
197                 block.getArgument(i + 1).replaceAllUsesWith(
198                     block.getArgument(i));
199                 block.eraseArgument(i + 1);
200               }
201             func.setType(toTy);
202             rewriter.finalizeRootUpdate(func);
203           }
204         } else if (auto embox = mlir::dyn_cast<EmboxProcOp>(op)) {
205           // Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk
206           // as required.
207           mlir::Type toTy = embox.getType().cast<BoxProcType>().getEleTy();
208           rewriter.setInsertionPoint(embox);
209           if (embox.getHost()) {
210             // Create the thunk.
211             auto module = embox->getParentOfType<mlir::ModuleOp>();
212             FirOpBuilder builder(rewriter, getKindMapping(module));
213             auto loc = embox.getLoc();
214             mlir::Type i8Ty = builder.getI8Type();
215             mlir::Type i8Ptr = builder.getRefType(i8Ty);
216             mlir::Type buffTy = SequenceType::get({32}, i8Ty);
217             auto buffer = builder.create<AllocaOp>(loc, buffTy);
218             mlir::Value closure =
219                 builder.createConvert(loc, i8Ptr, embox.getHost());
220             mlir::Value tramp = builder.createConvert(loc, i8Ptr, buffer);
221             mlir::Value func =
222                 builder.createConvert(loc, i8Ptr, embox.getFunc());
223             builder.create<fir::CallOp>(
224                 loc, factory::getLlvmInitTrampoline(builder),
225                 llvm::ArrayRef<mlir::Value>{tramp, func, closure});
226             auto adjustCall = builder.create<fir::CallOp>(
227                 loc, factory::getLlvmAdjustTrampoline(builder),
228                 llvm::ArrayRef<mlir::Value>{tramp});
229             rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy,
230                                                    adjustCall.getResult(0));
231           } else {
232             // Just forward the function as a pointer.
233             rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy,
234                                                    embox.getFunc());
235           }
236         } else if (auto mem = mlir::dyn_cast<AllocaOp>(op)) {
237           auto ty = mem.getType();
238           if (typeConverter.needsConversion(ty)) {
239             rewriter.setInsertionPoint(mem);
240             auto toTy = typeConverter.convertType(unwrapRefType(ty));
241             bool isPinned = mem.getPinned();
242             llvm::StringRef uniqName;
243             if (mem.getUniqName().hasValue())
244               uniqName = mem.getUniqName().getValue();
245             llvm::StringRef bindcName;
246             if (mem.getBindcName().hasValue())
247               bindcName = mem.getBindcName().getValue();
248             rewriter.replaceOpWithNewOp<AllocaOp>(
249                 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(),
250                 mem.getShape());
251           }
252         } else if (auto mem = mlir::dyn_cast<AllocMemOp>(op)) {
253           auto ty = mem.getType();
254           if (typeConverter.needsConversion(ty)) {
255             rewriter.setInsertionPoint(mem);
256             auto toTy = typeConverter.convertType(unwrapRefType(ty));
257             llvm::StringRef uniqName;
258             if (mem.getUniqName().hasValue())
259               uniqName = mem.getUniqName().getValue();
260             llvm::StringRef bindcName;
261             if (mem.getBindcName().hasValue())
262               bindcName = mem.getBindcName().getValue();
263             rewriter.replaceOpWithNewOp<AllocMemOp>(
264                 mem, toTy, uniqName, bindcName, mem.getTypeparams(),
265                 mem.getShape());
266           }
267         } else if (auto coor = mlir::dyn_cast<CoordinateOp>(op)) {
268           auto ty = coor.getType();
269           mlir::Type baseTy = coor.getBaseType();
270           if (typeConverter.needsConversion(ty) ||
271               typeConverter.needsConversion(baseTy)) {
272             rewriter.setInsertionPoint(coor);
273             auto toTy = typeConverter.convertType(ty);
274             auto toBaseTy = typeConverter.convertType(baseTy);
275             rewriter.replaceOpWithNewOp<CoordinateOp>(coor, toTy, coor.getRef(),
276                                                       coor.getCoor(), toBaseTy);
277           }
278         } else if (auto index = mlir::dyn_cast<FieldIndexOp>(op)) {
279           auto ty = index.getType();
280           mlir::Type onTy = index.getOnType();
281           if (typeConverter.needsConversion(ty) ||
282               typeConverter.needsConversion(onTy)) {
283             rewriter.setInsertionPoint(index);
284             auto toTy = typeConverter.convertType(ty);
285             auto toOnTy = typeConverter.convertType(onTy);
286             rewriter.replaceOpWithNewOp<FieldIndexOp>(
287                 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams());
288           }
289         } else if (auto index = mlir::dyn_cast<LenParamIndexOp>(op)) {
290           auto ty = index.getType();
291           mlir::Type onTy = index.getOnType();
292           if (typeConverter.needsConversion(ty) ||
293               typeConverter.needsConversion(onTy)) {
294             rewriter.setInsertionPoint(index);
295             auto toTy = typeConverter.convertType(ty);
296             auto toOnTy = typeConverter.convertType(onTy);
297             rewriter.replaceOpWithNewOp<LenParamIndexOp>(
298                 mem, toTy, index.getFieldId(), toOnTy);
299           }
300         } else if (op->getDialect() == firDialect) {
301           rewriter.startRootUpdate(op);
302           for (auto i : llvm::enumerate(op->getResultTypes()))
303             if (typeConverter.needsConversion(i.value())) {
304               auto toTy = typeConverter.convertType(i.value());
305               op->getResult(i.index()).setType(toTy);
306             }
307           rewriter.finalizeRootUpdate(op);
308         }
309       });
310     }
311     // TODO: any alternative implementation. Note: currently, the default code
312     // gen will not be able to handle boxproc and will give an error.
313   }
314 
315 private:
316   BoxedProcedureOptions options;
317 };
318 } // namespace
319 
320 std::unique_ptr<mlir::Pass> fir::createBoxedProcedurePass() {
321   return std::make_unique<BoxedProcedurePass>();
322 }
323 
324 std::unique_ptr<mlir::Pass> fir::createBoxedProcedurePass(bool useThunks) {
325   return std::make_unique<BoxedProcedurePass>(useThunks);
326 }
327