xref: /llvm-project/flang/lib/Optimizer/Transforms/PolymorphicOpConversion.cpp (revision 17a4fcecf40ee5191ab05b27a58ac37e5f57261d)
1 //===-- PolymorphicOpConversion.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 "flang/Lower/BuiltinModules.h"
10 #include "flang/Optimizer/Builder/Todo.h"
11 #include "flang/Optimizer/Dialect/FIRDialect.h"
12 #include "flang/Optimizer/Dialect/FIROps.h"
13 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
14 #include "flang/Optimizer/Dialect/FIRType.h"
15 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
16 #include "flang/Optimizer/Dialect/Support/KindMapping.h"
17 #include "flang/Optimizer/Support/InternalNames.h"
18 #include "flang/Optimizer/Support/TypeCode.h"
19 #include "flang/Optimizer/Support/Utils.h"
20 #include "flang/Optimizer/Transforms/Passes.h"
21 #include "flang/Runtime/derived-api.h"
22 #include "flang/Semantics/runtime-type-info.h"
23 #include "mlir/Dialect/Affine/IR/AffineOps.h"
24 #include "mlir/Dialect/Arith/IR/Arith.h"
25 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
26 #include "mlir/Dialect/Func/IR/FuncOps.h"
27 #include "mlir/IR/BuiltinOps.h"
28 #include "mlir/Pass/Pass.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/Support/CommandLine.h"
32 #include <mutex>
33 
34 namespace fir {
35 #define GEN_PASS_DEF_POLYMORPHICOPCONVERSION
36 #include "flang/Optimizer/Transforms/Passes.h.inc"
37 } // namespace fir
38 
39 using namespace fir;
40 using namespace mlir;
41 
42 namespace {
43 
44 /// SelectTypeOp converted to an if-then-else chain
45 ///
46 /// This lowers the test conditions to calls into the runtime.
47 class SelectTypeConv : public OpConversionPattern<fir::SelectTypeOp> {
48 public:
49   using OpConversionPattern<fir::SelectTypeOp>::OpConversionPattern;
50 
51   SelectTypeConv(mlir::MLIRContext *ctx, std::mutex *moduleMutex)
52       : mlir::OpConversionPattern<fir::SelectTypeOp>(ctx),
53         moduleMutex(moduleMutex) {}
54 
55   mlir::LogicalResult
56   matchAndRewrite(fir::SelectTypeOp selectType, OpAdaptor adaptor,
57                   mlir::ConversionPatternRewriter &rewriter) const override;
58 
59 private:
60   // Generate comparison of type descriptor addresses.
61   mlir::Value genTypeDescCompare(mlir::Location loc, mlir::Value selector,
62                                  mlir::Type ty, mlir::ModuleOp mod,
63                                  mlir::PatternRewriter &rewriter) const;
64 
65   mlir::LogicalResult genTypeLadderStep(mlir::Location loc,
66                                         mlir::Value selector,
67                                         mlir::Attribute attr, mlir::Block *dest,
68                                         std::optional<mlir::ValueRange> destOps,
69                                         mlir::ModuleOp mod,
70                                         mlir::PatternRewriter &rewriter,
71                                         fir::KindMapping &kindMap) const;
72 
73   llvm::SmallSet<llvm::StringRef, 4> collectAncestors(fir::DispatchTableOp dt,
74                                                       mlir::ModuleOp mod) const;
75 
76   // Mutex used to guard insertion of mlir::func::FuncOp in the module.
77   std::mutex *moduleMutex;
78 };
79 
80 /// Lower `fir.dispatch` operation. A virtual call to a method in a dispatch
81 /// table.
82 struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {
83   using OpConversionPattern<fir::DispatchOp>::OpConversionPattern;
84 
85   DispatchOpConv(mlir::MLIRContext *ctx, const BindingTables &bindingTables)
86       : mlir::OpConversionPattern<fir::DispatchOp>(ctx),
87         bindingTables(bindingTables) {}
88 
89   mlir::LogicalResult
90   matchAndRewrite(fir::DispatchOp dispatch, OpAdaptor adaptor,
91                   mlir::ConversionPatternRewriter &rewriter) const override {
92     mlir::Location loc = dispatch.getLoc();
93 
94     if (bindingTables.empty())
95       return emitError(loc) << "no binding tables found";
96 
97     // Get derived type information.
98     mlir::Type declaredType =
99         fir::getDerivedType(dispatch.getObject().getType().getEleTy());
100     assert(declaredType.isa<fir::RecordType>() && "expecting fir.type");
101     auto recordType = declaredType.dyn_cast<fir::RecordType>();
102 
103     // Lookup for the binding table.
104     auto bindingsIter = bindingTables.find(recordType.getName());
105     if (bindingsIter == bindingTables.end())
106       return emitError(loc)
107              << "cannot find binding table for " << recordType.getName();
108 
109     // Lookup for the binding.
110     const BindingTable &bindingTable = bindingsIter->second;
111     auto bindingIter = bindingTable.find(dispatch.getMethod());
112     if (bindingIter == bindingTable.end())
113       return emitError(loc)
114              << "cannot find binding for " << dispatch.getMethod();
115     unsigned bindingIdx = bindingIter->second;
116 
117     mlir::Value passedObject = dispatch.getObject();
118 
119     auto module = dispatch.getOperation()->getParentOfType<mlir::ModuleOp>();
120     Type typeDescTy;
121     std::string typeDescName =
122         NameUniquer::getTypeDescriptorName(recordType.getName());
123     if (auto global = module.lookupSymbol<fir::GlobalOp>(typeDescName)) {
124       typeDescTy = global.getType();
125     }
126 
127     // clang-format off
128     // Before:
129     //   fir.dispatch "proc1"(%11 :
130     //   !fir.class<!fir.heap<!fir.type<_QMpolyTp1{a:i32,b:i32}>>>)
131 
132     // After:
133     //   %12 = fir.box_tdesc %11 : (!fir.class<!fir.heap<!fir.type<_QMpolyTp1{a:i32,b:i32}>>>) -> !fir.tdesc<none>
134     //   %13 = fir.convert %12 : (!fir.tdesc<none>) -> !fir.ref<!fir.type<_QM__fortran_type_infoTderivedtype>>
135     //   %14 = fir.field_index binding, !fir.type<_QM__fortran_type_infoTderivedtype>
136     //   %15 = fir.coordinate_of %13, %14 : (!fir.ref<!fir.type<_QM__fortran_type_infoTderivedtype>>, !fir.field) -> !fir.ref<!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>>
137     //   %bindings = fir.load %15 : !fir.ref<!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>>
138     //   %16 = fir.box_addr %bindings : (!fir.box<!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>>) -> !fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>
139     //   %17 = fir.coordinate_of %16, %c0 : (!fir.ptr<!fir.array<?x!fir.type<_QM__fortran_type_infoTbinding>>>, index) -> !fir.ref<!fir.type<_QM__fortran_type_infoTbinding>>
140     //   %18 = fir.field_index proc, !fir.type<_QM__fortran_type_infoTbinding>
141     //   %19 = fir.coordinate_of %17, %18 : (!fir.ref<!fir.type<_QM__fortran_type_infoTbinding>>, !fir.field) -> !fir.ref<!fir.type<_QM__fortran_builtinsT__builtin_c_funptr>>
142     //   %20 = fir.field_index __address, !fir.type<_QM__fortran_builtinsT__builtin_c_funptr>
143     //   %21 = fir.coordinate_of %19, %20 : (!fir.ref<!fir.type<_QM__fortran_builtinsT__builtin_c_funptr>>, !fir.field) -> !fir.ref<i64>
144     //   %22 = fir.load %21 : !fir.ref<i64>
145     //   %23 = fir.convert %22 : (i64) -> (() -> ())
146     //   fir.call %23()  : () -> ()
147     // clang-format on
148 
149     // Load the descriptor.
150     mlir::Type fieldTy = fir::FieldType::get(rewriter.getContext());
151     mlir::Type tdescType =
152         fir::TypeDescType::get(mlir::NoneType::get(rewriter.getContext()));
153     mlir::Value boxDesc =
154         rewriter.create<fir::BoxTypeDescOp>(loc, tdescType, passedObject);
155     boxDesc = rewriter.create<fir::ConvertOp>(
156         loc, fir::ReferenceType::get(typeDescTy), boxDesc);
157 
158     // Load the bindings descriptor.
159     auto bindingsCompName = Fortran::semantics::bindingDescCompName;
160     fir::RecordType typeDescRecTy = typeDescTy.cast<fir::RecordType>();
161     mlir::Value field = rewriter.create<fir::FieldIndexOp>(
162         loc, fieldTy, bindingsCompName, typeDescRecTy, mlir::ValueRange{});
163     mlir::Type coorTy =
164         fir::ReferenceType::get(typeDescRecTy.getType(bindingsCompName));
165     mlir::Value bindingBoxAddr =
166         rewriter.create<fir::CoordinateOp>(loc, coorTy, boxDesc, field);
167     mlir::Value bindingBox = rewriter.create<fir::LoadOp>(loc, bindingBoxAddr);
168 
169     // Load the correct binding.
170     mlir::Value bindings = rewriter.create<fir::BoxAddrOp>(loc, bindingBox);
171     fir::RecordType bindingTy =
172         fir::unwrapIfDerived(bindingBox.getType().cast<fir::BaseBoxType>());
173     mlir::Type bindingAddrTy = fir::ReferenceType::get(bindingTy);
174     mlir::Value bindingIdxVal = rewriter.create<mlir::arith::ConstantOp>(
175         loc, rewriter.getIndexType(), rewriter.getIndexAttr(bindingIdx));
176     mlir::Value bindingAddr = rewriter.create<fir::CoordinateOp>(
177         loc, bindingAddrTy, bindings, bindingIdxVal);
178 
179     // Get the function pointer.
180     auto procCompName = Fortran::semantics::procCompName;
181     mlir::Value procField = rewriter.create<fir::FieldIndexOp>(
182         loc, fieldTy, procCompName, bindingTy, mlir::ValueRange{});
183     fir::RecordType procTy =
184         bindingTy.getType(procCompName).cast<fir::RecordType>();
185     mlir::Type procRefTy = fir::ReferenceType::get(procTy);
186     mlir::Value procRef = rewriter.create<fir::CoordinateOp>(
187         loc, procRefTy, bindingAddr, procField);
188 
189     auto addressFieldName = Fortran::lower::builtin::cptrFieldName;
190     mlir::Value addressField = rewriter.create<fir::FieldIndexOp>(
191         loc, fieldTy, addressFieldName, procTy, mlir::ValueRange{});
192     mlir::Type addressTy = procTy.getType(addressFieldName);
193     mlir::Type addressRefTy = fir::ReferenceType::get(addressTy);
194     mlir::Value addressRef = rewriter.create<fir::CoordinateOp>(
195         loc, addressRefTy, procRef, addressField);
196     mlir::Value address = rewriter.create<fir::LoadOp>(loc, addressRef);
197 
198     // Get the function type.
199     llvm::SmallVector<mlir::Type> argTypes;
200     for (mlir::Value operand : dispatch.getArgs())
201       argTypes.push_back(operand.getType());
202     llvm::SmallVector<mlir::Type> resTypes;
203     if (!dispatch.getResults().empty())
204       resTypes.push_back(dispatch.getResults()[0].getType());
205 
206     mlir::Type funTy =
207         mlir::FunctionType::get(rewriter.getContext(), argTypes, resTypes);
208     mlir::Value funcPtr = rewriter.create<fir::ConvertOp>(loc, funTy, address);
209 
210     // Make the call.
211     llvm::SmallVector<mlir::Value> args{funcPtr};
212     args.append(dispatch.getArgs().begin(), dispatch.getArgs().end());
213     rewriter.replaceOpWithNewOp<fir::CallOp>(dispatch, resTypes, nullptr, args);
214     return mlir::success();
215   }
216 
217 private:
218   BindingTables bindingTables;
219 };
220 
221 /// Convert FIR structured control flow ops to CFG ops.
222 class PolymorphicOpConversion
223     : public fir::impl::PolymorphicOpConversionBase<PolymorphicOpConversion> {
224 public:
225   mlir::LogicalResult initialize(mlir::MLIRContext *ctx) override {
226     moduleMutex = new std::mutex();
227     return mlir::success();
228   }
229 
230   void runOnOperation() override {
231     auto *context = &getContext();
232     auto mod = getOperation()->getParentOfType<ModuleOp>();
233     mlir::RewritePatternSet patterns(context);
234 
235     BindingTables bindingTables;
236     buildBindingTables(bindingTables, mod);
237 
238     patterns.insert<SelectTypeConv>(context, moduleMutex);
239     patterns.insert<DispatchOpConv>(context, bindingTables);
240     mlir::ConversionTarget target(*context);
241     target.addLegalDialect<mlir::AffineDialect, mlir::cf::ControlFlowDialect,
242                            FIROpsDialect, mlir::func::FuncDialect>();
243 
244     // apply the patterns
245     target.addIllegalOp<SelectTypeOp>();
246     target.addIllegalOp<DispatchOp>();
247     target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
248     if (mlir::failed(mlir::applyPartialConversion(getOperation(), target,
249                                                   std::move(patterns)))) {
250       mlir::emitError(mlir::UnknownLoc::get(context),
251                       "error in converting to CFG\n");
252       signalPassFailure();
253     }
254   }
255 
256 private:
257   std::mutex *moduleMutex;
258 };
259 } // namespace
260 
261 mlir::LogicalResult SelectTypeConv::matchAndRewrite(
262     fir::SelectTypeOp selectType, OpAdaptor adaptor,
263     mlir::ConversionPatternRewriter &rewriter) const {
264   auto operands = adaptor.getOperands();
265   auto typeGuards = selectType.getCases();
266   unsigned typeGuardNum = typeGuards.size();
267   auto selector = selectType.getSelector();
268   auto loc = selectType.getLoc();
269   auto mod = selectType.getOperation()->getParentOfType<mlir::ModuleOp>();
270   fir::KindMapping kindMap = fir::getKindMapping(mod);
271 
272   // Order type guards so the condition and branches are done to respect the
273   // Execution of SELECT TYPE construct as described in the Fortran 2018
274   // standard 11.1.11.2 point 4.
275   // 1. If a TYPE IS type guard statement matches the selector, the block
276   //    following that statement is executed.
277   // 2. Otherwise, if exactly one CLASS IS type guard statement matches the
278   //    selector, the block following that statement is executed.
279   // 3. Otherwise, if several CLASS IS type guard statements match the
280   //    selector, one of these statements will inevitably specify a type that
281   //    is an extension of all the types specified in the others; the block
282   //    following that statement is executed.
283   // 4. Otherwise, if there is a CLASS DEFAULT type guard statement, the block
284   //    following that statement is executed.
285   // 5. Otherwise, no block is executed.
286 
287   llvm::SmallVector<unsigned> orderedTypeGuards;
288   llvm::SmallVector<unsigned> orderedClassIsGuards;
289   unsigned defaultGuard = typeGuardNum - 1;
290 
291   // The following loop go through the type guards in the fir.select_type
292   // operation and sort them into two lists.
293   // - All the TYPE IS type guard are added in order to the orderedTypeGuards
294   //   list. This list is used at the end to generate the if-then-else ladder.
295   // - CLASS IS type guard are added in a separate list. If a CLASS IS type
296   //   guard type extends a type already present, the type guard is inserted
297   //   before in the list to respect point 3. above. Otherwise it is just
298   //   added in order at the end.
299   for (unsigned t = 0; t < typeGuardNum; ++t) {
300     if (auto a = typeGuards[t].dyn_cast<fir::ExactTypeAttr>()) {
301       orderedTypeGuards.push_back(t);
302       continue;
303     }
304 
305     if (auto a = typeGuards[t].dyn_cast<fir::SubclassAttr>()) {
306       if (auto recTy = a.getType().dyn_cast<fir::RecordType>()) {
307         auto dt = mod.lookupSymbol<fir::DispatchTableOp>(recTy.getName());
308         assert(dt && "dispatch table not found");
309         llvm::SmallSet<llvm::StringRef, 4> ancestors =
310             collectAncestors(dt, mod);
311         if (!ancestors.empty()) {
312           auto it = orderedClassIsGuards.begin();
313           while (it != orderedClassIsGuards.end()) {
314             fir::SubclassAttr sAttr =
315                 typeGuards[*it].dyn_cast<fir::SubclassAttr>();
316             if (auto ty = sAttr.getType().dyn_cast<fir::RecordType>()) {
317               if (ancestors.contains(ty.getName()))
318                 break;
319             }
320             ++it;
321           }
322           if (it != orderedClassIsGuards.end()) {
323             // Parent type is present so place it before.
324             orderedClassIsGuards.insert(it, t);
325             continue;
326           }
327         }
328       }
329       orderedClassIsGuards.push_back(t);
330     }
331   }
332   orderedTypeGuards.append(orderedClassIsGuards);
333   orderedTypeGuards.push_back(defaultGuard);
334   assert(orderedTypeGuards.size() == typeGuardNum &&
335          "ordered type guard size doesn't match number of type guards");
336 
337   for (unsigned idx : orderedTypeGuards) {
338     auto *dest = selectType.getSuccessor(idx);
339     std::optional<mlir::ValueRange> destOps =
340         selectType.getSuccessorOperands(operands, idx);
341     if (typeGuards[idx].dyn_cast<mlir::UnitAttr>())
342       rewriter.replaceOpWithNewOp<mlir::cf::BranchOp>(selectType, dest);
343     else if (mlir::failed(genTypeLadderStep(loc, selector, typeGuards[idx],
344                                             dest, destOps, mod, rewriter,
345                                             kindMap)))
346       return mlir::failure();
347   }
348   return mlir::success();
349 }
350 
351 mlir::LogicalResult SelectTypeConv::genTypeLadderStep(
352     mlir::Location loc, mlir::Value selector, mlir::Attribute attr,
353     mlir::Block *dest, std::optional<mlir::ValueRange> destOps,
354     mlir::ModuleOp mod, mlir::PatternRewriter &rewriter,
355     fir::KindMapping &kindMap) const {
356   mlir::Value cmp;
357   // TYPE IS type guard comparison are all done inlined.
358   if (auto a = attr.dyn_cast<fir::ExactTypeAttr>()) {
359     if (fir::isa_trivial(a.getType()) ||
360         a.getType().isa<fir::CharacterType>()) {
361       // For type guard statement with Intrinsic type spec the type code of
362       // the descriptor is compared.
363       int code = fir::getTypeCode(a.getType(), kindMap);
364       if (code == 0)
365         return mlir::emitError(loc)
366                << "type code unavailable for " << a.getType();
367       mlir::Value typeCode = rewriter.create<mlir::arith::ConstantOp>(
368           loc, rewriter.getI8IntegerAttr(code));
369       mlir::Value selectorTypeCode = rewriter.create<fir::BoxTypeCodeOp>(
370           loc, rewriter.getI8Type(), selector);
371       cmp = rewriter.create<mlir::arith::CmpIOp>(
372           loc, mlir::arith::CmpIPredicate::eq, selectorTypeCode, typeCode);
373     } else {
374       // Flang inline the kind parameter in the type descriptor so we can
375       // directly check if the type descriptor addresses are identical for
376       // the TYPE IS type guard statement.
377       mlir::Value res =
378           genTypeDescCompare(loc, selector, a.getType(), mod, rewriter);
379       if (!res)
380         return mlir::failure();
381       cmp = res;
382     }
383     // CLASS IS type guard statement is done with a runtime call.
384   } else if (auto a = attr.dyn_cast<fir::SubclassAttr>()) {
385     // Retrieve the type descriptor from the type guard statement record type.
386     assert(a.getType().isa<fir::RecordType>() && "expect fir.record type");
387     fir::RecordType recTy = a.getType().dyn_cast<fir::RecordType>();
388     std::string typeDescName =
389         fir::NameUniquer::getTypeDescriptorName(recTy.getName());
390     auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
391     auto typeDescAddr = rewriter.create<fir::AddrOfOp>(
392         loc, fir::ReferenceType::get(typeDescGlobal.getType()),
393         typeDescGlobal.getSymbol());
394     mlir::Type typeDescTy = ReferenceType::get(rewriter.getNoneType());
395     mlir::Value typeDesc =
396         rewriter.create<ConvertOp>(loc, typeDescTy, typeDescAddr);
397 
398     // Prepare the selector descriptor for the runtime call.
399     mlir::Type descNoneTy = fir::BoxType::get(rewriter.getNoneType());
400     mlir::Value descSelector =
401         rewriter.create<ConvertOp>(loc, descNoneTy, selector);
402 
403     // Generate runtime call.
404     llvm::StringRef fctName = RTNAME_STRING(ClassIs);
405     mlir::func::FuncOp callee;
406     {
407       // Since conversion is done in parallel for each fir.select_type
408       // operation, the runtime function insertion must be threadsafe.
409       std::lock_guard<std::mutex> lock(*moduleMutex);
410       callee =
411           fir::createFuncOp(rewriter.getUnknownLoc(), mod, fctName,
412                             rewriter.getFunctionType({descNoneTy, typeDescTy},
413                                                      rewriter.getI1Type()));
414     }
415     cmp = rewriter
416               .create<fir::CallOp>(loc, callee,
417                                    mlir::ValueRange{descSelector, typeDesc})
418               .getResult(0);
419   }
420 
421   auto *thisBlock = rewriter.getInsertionBlock();
422   auto *newBlock =
423       rewriter.createBlock(dest->getParent(), mlir::Region::iterator(dest));
424   rewriter.setInsertionPointToEnd(thisBlock);
425   if (destOps.has_value())
426     rewriter.create<mlir::cf::CondBranchOp>(loc, cmp, dest, destOps.value(),
427                                             newBlock, std::nullopt);
428   else
429     rewriter.create<mlir::cf::CondBranchOp>(loc, cmp, dest, newBlock);
430   rewriter.setInsertionPointToEnd(newBlock);
431   return mlir::success();
432 }
433 
434 // Generate comparison of type descriptor addresses.
435 mlir::Value
436 SelectTypeConv::genTypeDescCompare(mlir::Location loc, mlir::Value selector,
437                                    mlir::Type ty, mlir::ModuleOp mod,
438                                    mlir::PatternRewriter &rewriter) const {
439   assert(ty.isa<fir::RecordType>() && "expect fir.record type");
440   fir::RecordType recTy = ty.dyn_cast<fir::RecordType>();
441   std::string typeDescName =
442       fir::NameUniquer::getTypeDescriptorName(recTy.getName());
443   auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
444   if (!typeDescGlobal)
445     return {};
446   auto typeDescAddr = rewriter.create<fir::AddrOfOp>(
447       loc, fir::ReferenceType::get(typeDescGlobal.getType()),
448       typeDescGlobal.getSymbol());
449   auto intPtrTy = rewriter.getIndexType();
450   mlir::Type tdescType =
451       fir::TypeDescType::get(mlir::NoneType::get(rewriter.getContext()));
452   mlir::Value selectorTdescAddr =
453       rewriter.create<fir::BoxTypeDescOp>(loc, tdescType, selector);
454   auto typeDescInt =
455       rewriter.create<fir::ConvertOp>(loc, intPtrTy, typeDescAddr);
456   auto selectorTdescInt =
457       rewriter.create<fir::ConvertOp>(loc, intPtrTy, selectorTdescAddr);
458   return rewriter.create<mlir::arith::CmpIOp>(
459       loc, mlir::arith::CmpIPredicate::eq, typeDescInt, selectorTdescInt);
460 }
461 
462 llvm::SmallSet<llvm::StringRef, 4>
463 SelectTypeConv::collectAncestors(fir::DispatchTableOp dt,
464                                  mlir::ModuleOp mod) const {
465   llvm::SmallSet<llvm::StringRef, 4> ancestors;
466   if (!dt.getParent().has_value())
467     return ancestors;
468   while (dt.getParent().has_value()) {
469     ancestors.insert(*dt.getParent());
470     dt = mod.lookupSymbol<fir::DispatchTableOp>(*dt.getParent());
471   }
472   return ancestors;
473 }
474 
475 std::unique_ptr<mlir::Pass> fir::createPolymorphicOpConversionPass() {
476   return std::make_unique<PolymorphicOpConversion>();
477 }
478