xref: /llvm-project/flang/lib/Optimizer/Transforms/PolymorphicOpConversion.cpp (revision fac349a169976f822fb27f03e623fa0d28aec1f3)
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::TypeInfoOp 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(mlir::isa<fir::RecordType>(declaredType) && "expecting fir.type");
101     auto recordType = mlir::dyn_cast<fir::RecordType>(declaredType);
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 = mlir::cast<fir::RecordType>(typeDescTy);
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 = fir::unwrapIfDerived(
172         mlir::cast<fir::BaseBoxType>(bindingBox.getType()));
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         mlir::cast<fir::RecordType>(bindingTy.getType(procCompName));
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::affine::AffineDialect,
242                            mlir::cf::ControlFlowDialect, FIROpsDialect,
243                            mlir::func::FuncDialect>();
244 
245     // apply the patterns
246     target.addIllegalOp<SelectTypeOp>();
247     target.addIllegalOp<DispatchOp>();
248     target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
249     if (mlir::failed(mlir::applyPartialConversion(getOperation(), target,
250                                                   std::move(patterns)))) {
251       mlir::emitError(mlir::UnknownLoc::get(context),
252                       "error in converting to CFG\n");
253       signalPassFailure();
254     }
255   }
256 
257 private:
258   std::mutex *moduleMutex;
259 };
260 } // namespace
261 
262 mlir::LogicalResult SelectTypeConv::matchAndRewrite(
263     fir::SelectTypeOp selectType, OpAdaptor adaptor,
264     mlir::ConversionPatternRewriter &rewriter) const {
265   auto operands = adaptor.getOperands();
266   auto typeGuards = selectType.getCases();
267   unsigned typeGuardNum = typeGuards.size();
268   auto selector = selectType.getSelector();
269   auto loc = selectType.getLoc();
270   auto mod = selectType.getOperation()->getParentOfType<mlir::ModuleOp>();
271   fir::KindMapping kindMap = fir::getKindMapping(mod);
272 
273   // Order type guards so the condition and branches are done to respect the
274   // Execution of SELECT TYPE construct as described in the Fortran 2018
275   // standard 11.1.11.2 point 4.
276   // 1. If a TYPE IS type guard statement matches the selector, the block
277   //    following that statement is executed.
278   // 2. Otherwise, if exactly one CLASS IS type guard statement matches the
279   //    selector, the block following that statement is executed.
280   // 3. Otherwise, if several CLASS IS type guard statements match the
281   //    selector, one of these statements will inevitably specify a type that
282   //    is an extension of all the types specified in the others; the block
283   //    following that statement is executed.
284   // 4. Otherwise, if there is a CLASS DEFAULT type guard statement, the block
285   //    following that statement is executed.
286   // 5. Otherwise, no block is executed.
287 
288   llvm::SmallVector<unsigned> orderedTypeGuards;
289   llvm::SmallVector<unsigned> orderedClassIsGuards;
290   unsigned defaultGuard = typeGuardNum - 1;
291 
292   // The following loop go through the type guards in the fir.select_type
293   // operation and sort them into two lists.
294   // - All the TYPE IS type guard are added in order to the orderedTypeGuards
295   //   list. This list is used at the end to generate the if-then-else ladder.
296   // - CLASS IS type guard are added in a separate list. If a CLASS IS type
297   //   guard type extends a type already present, the type guard is inserted
298   //   before in the list to respect point 3. above. Otherwise it is just
299   //   added in order at the end.
300   for (unsigned t = 0; t < typeGuardNum; ++t) {
301     if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(typeGuards[t])) {
302       orderedTypeGuards.push_back(t);
303       continue;
304     }
305 
306     if (auto a = mlir::dyn_cast<fir::SubclassAttr>(typeGuards[t])) {
307       if (auto recTy = mlir::dyn_cast<fir::RecordType>(a.getType())) {
308         auto dt = mod.lookupSymbol<fir::TypeInfoOp>(recTy.getName());
309         assert(dt && "dispatch table not found");
310         llvm::SmallSet<llvm::StringRef, 4> ancestors =
311             collectAncestors(dt, mod);
312         if (!ancestors.empty()) {
313           auto it = orderedClassIsGuards.begin();
314           while (it != orderedClassIsGuards.end()) {
315             fir::SubclassAttr sAttr =
316                 mlir::dyn_cast<fir::SubclassAttr>(typeGuards[*it]);
317             if (auto ty = mlir::dyn_cast<fir::RecordType>(sAttr.getType())) {
318               if (ancestors.contains(ty.getName()))
319                 break;
320             }
321             ++it;
322           }
323           if (it != orderedClassIsGuards.end()) {
324             // Parent type is present so place it before.
325             orderedClassIsGuards.insert(it, t);
326             continue;
327           }
328         }
329       }
330       orderedClassIsGuards.push_back(t);
331     }
332   }
333   orderedTypeGuards.append(orderedClassIsGuards);
334   orderedTypeGuards.push_back(defaultGuard);
335   assert(orderedTypeGuards.size() == typeGuardNum &&
336          "ordered type guard size doesn't match number of type guards");
337 
338   for (unsigned idx : orderedTypeGuards) {
339     auto *dest = selectType.getSuccessor(idx);
340     std::optional<mlir::ValueRange> destOps =
341         selectType.getSuccessorOperands(operands, idx);
342     if (mlir::dyn_cast<mlir::UnitAttr>(typeGuards[idx]))
343       rewriter.replaceOpWithNewOp<mlir::cf::BranchOp>(
344           selectType, dest, destOps.value_or(mlir::ValueRange{}));
345     else if (mlir::failed(genTypeLadderStep(loc, selector, typeGuards[idx],
346                                             dest, destOps, mod, rewriter,
347                                             kindMap)))
348       return mlir::failure();
349   }
350   return mlir::success();
351 }
352 
353 mlir::LogicalResult SelectTypeConv::genTypeLadderStep(
354     mlir::Location loc, mlir::Value selector, mlir::Attribute attr,
355     mlir::Block *dest, std::optional<mlir::ValueRange> destOps,
356     mlir::ModuleOp mod, mlir::PatternRewriter &rewriter,
357     fir::KindMapping &kindMap) const {
358   mlir::Value cmp;
359   // TYPE IS type guard comparison are all done inlined.
360   if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(attr)) {
361     if (fir::isa_trivial(a.getType()) ||
362         mlir::isa<fir::CharacterType>(a.getType())) {
363       // For type guard statement with Intrinsic type spec the type code of
364       // the descriptor is compared.
365       int code = fir::getTypeCode(a.getType(), kindMap);
366       if (code == 0)
367         return mlir::emitError(loc)
368                << "type code unavailable for " << a.getType();
369       mlir::Value typeCode = rewriter.create<mlir::arith::ConstantOp>(
370           loc, rewriter.getI8IntegerAttr(code));
371       mlir::Value selectorTypeCode = rewriter.create<fir::BoxTypeCodeOp>(
372           loc, rewriter.getI8Type(), selector);
373       cmp = rewriter.create<mlir::arith::CmpIOp>(
374           loc, mlir::arith::CmpIPredicate::eq, selectorTypeCode, typeCode);
375     } else {
376       // Flang inline the kind parameter in the type descriptor so we can
377       // directly check if the type descriptor addresses are identical for
378       // the TYPE IS type guard statement.
379       mlir::Value res =
380           genTypeDescCompare(loc, selector, a.getType(), mod, rewriter);
381       if (!res)
382         return mlir::failure();
383       cmp = res;
384     }
385     // CLASS IS type guard statement is done with a runtime call.
386   } else if (auto a = mlir::dyn_cast<fir::SubclassAttr>(attr)) {
387     // Retrieve the type descriptor from the type guard statement record type.
388     assert(mlir::isa<fir::RecordType>(a.getType()) && "expect fir.record type");
389     fir::RecordType recTy = mlir::dyn_cast<fir::RecordType>(a.getType());
390     std::string typeDescName =
391         fir::NameUniquer::getTypeDescriptorName(recTy.getName());
392     auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
393     auto typeDescAddr = rewriter.create<fir::AddrOfOp>(
394         loc, fir::ReferenceType::get(typeDescGlobal.getType()),
395         typeDescGlobal.getSymbol());
396     mlir::Type typeDescTy = ReferenceType::get(rewriter.getNoneType());
397     mlir::Value typeDesc =
398         rewriter.create<ConvertOp>(loc, typeDescTy, typeDescAddr);
399 
400     // Prepare the selector descriptor for the runtime call.
401     mlir::Type descNoneTy = fir::BoxType::get(rewriter.getNoneType());
402     mlir::Value descSelector =
403         rewriter.create<ConvertOp>(loc, descNoneTy, selector);
404 
405     // Generate runtime call.
406     llvm::StringRef fctName = RTNAME_STRING(ClassIs);
407     mlir::func::FuncOp callee;
408     {
409       // Since conversion is done in parallel for each fir.select_type
410       // operation, the runtime function insertion must be threadsafe.
411       std::lock_guard<std::mutex> lock(*moduleMutex);
412       callee =
413           fir::createFuncOp(rewriter.getUnknownLoc(), mod, fctName,
414                             rewriter.getFunctionType({descNoneTy, typeDescTy},
415                                                      rewriter.getI1Type()));
416     }
417     cmp = rewriter
418               .create<fir::CallOp>(loc, callee,
419                                    mlir::ValueRange{descSelector, typeDesc})
420               .getResult(0);
421   }
422 
423   auto *thisBlock = rewriter.getInsertionBlock();
424   auto *newBlock =
425       rewriter.createBlock(dest->getParent(), mlir::Region::iterator(dest));
426   rewriter.setInsertionPointToEnd(thisBlock);
427   if (destOps.has_value())
428     rewriter.create<mlir::cf::CondBranchOp>(loc, cmp, dest, destOps.value(),
429                                             newBlock, std::nullopt);
430   else
431     rewriter.create<mlir::cf::CondBranchOp>(loc, cmp, dest, newBlock);
432   rewriter.setInsertionPointToEnd(newBlock);
433   return mlir::success();
434 }
435 
436 // Generate comparison of type descriptor addresses.
437 mlir::Value
438 SelectTypeConv::genTypeDescCompare(mlir::Location loc, mlir::Value selector,
439                                    mlir::Type ty, mlir::ModuleOp mod,
440                                    mlir::PatternRewriter &rewriter) const {
441   assert(mlir::isa<fir::RecordType>(ty) && "expect fir.record type");
442   fir::RecordType recTy = mlir::dyn_cast<fir::RecordType>(ty);
443   std::string typeDescName =
444       fir::NameUniquer::getTypeDescriptorName(recTy.getName());
445   auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
446   if (!typeDescGlobal)
447     return {};
448   auto typeDescAddr = rewriter.create<fir::AddrOfOp>(
449       loc, fir::ReferenceType::get(typeDescGlobal.getType()),
450       typeDescGlobal.getSymbol());
451   auto intPtrTy = rewriter.getIndexType();
452   mlir::Type tdescType =
453       fir::TypeDescType::get(mlir::NoneType::get(rewriter.getContext()));
454   mlir::Value selectorTdescAddr =
455       rewriter.create<fir::BoxTypeDescOp>(loc, tdescType, selector);
456   auto typeDescInt =
457       rewriter.create<fir::ConvertOp>(loc, intPtrTy, typeDescAddr);
458   auto selectorTdescInt =
459       rewriter.create<fir::ConvertOp>(loc, intPtrTy, selectorTdescAddr);
460   return rewriter.create<mlir::arith::CmpIOp>(
461       loc, mlir::arith::CmpIPredicate::eq, typeDescInt, selectorTdescInt);
462 }
463 
464 llvm::SmallSet<llvm::StringRef, 4>
465 SelectTypeConv::collectAncestors(fir::TypeInfoOp dt, mlir::ModuleOp mod) const {
466   llvm::SmallSet<llvm::StringRef, 4> ancestors;
467   while (auto parentName = dt.getIfParentName()) {
468     ancestors.insert(*parentName);
469     dt = mod.lookupSymbol<fir::TypeInfoOp>(*parentName);
470     assert(dt && "parent type info not generated");
471   }
472   return ancestors;
473 }
474 
475 std::unique_ptr<mlir::Pass> fir::createPolymorphicOpConversionPass() {
476   return std::make_unique<PolymorphicOpConversion>();
477 }
478