1 //===-- FIROps.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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Optimizer/Dialect/FIROps.h"
14 #include "flang/Optimizer/Dialect/FIRAttr.h"
15 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
16 #include "flang/Optimizer/Dialect/FIRType.h"
17 #include "flang/Optimizer/Support/Utils.h"
18 #include "mlir/Dialect/CommonFolders.h"
19 #include "mlir/Dialect/StandardOps/IR/Ops.h"
20 #include "mlir/IR/BuiltinOps.h"
21 #include "mlir/IR/Diagnostics.h"
22 #include "mlir/IR/Matchers.h"
23 #include "mlir/IR/PatternMatch.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/TypeSwitch.h"
26 
27 namespace {
28 #include "flang/Optimizer/Transforms/RewritePatterns.inc"
29 } // namespace
30 using namespace fir;
31 
32 /// Return true if a sequence type is of some incomplete size or a record type
33 /// is malformed or contains an incomplete sequence type. An incomplete sequence
34 /// type is one with more unknown extents in the type than have been provided
35 /// via `dynamicExtents`. Sequence types with an unknown rank are incomplete by
36 /// definition.
37 static bool verifyInType(mlir::Type inType,
38                          llvm::SmallVectorImpl<llvm::StringRef> &visited,
39                          unsigned dynamicExtents = 0) {
40   if (auto st = inType.dyn_cast<fir::SequenceType>()) {
41     auto shape = st.getShape();
42     if (shape.size() == 0)
43       return true;
44     for (std::size_t i = 0, end{shape.size()}; i < end; ++i) {
45       if (shape[i] != fir::SequenceType::getUnknownExtent())
46         continue;
47       if (dynamicExtents-- == 0)
48         return true;
49     }
50   } else if (auto rt = inType.dyn_cast<fir::RecordType>()) {
51     // don't recurse if we're already visiting this one
52     if (llvm::is_contained(visited, rt.getName()))
53       return false;
54     // keep track of record types currently being visited
55     visited.push_back(rt.getName());
56     for (auto &field : rt.getTypeList())
57       if (verifyInType(field.second, visited))
58         return true;
59     visited.pop_back();
60   } else if (auto rt = inType.dyn_cast<fir::PointerType>()) {
61     return verifyInType(rt.getEleTy(), visited);
62   }
63   return false;
64 }
65 
66 static bool verifyTypeParamCount(mlir::Type inType, unsigned numParams) {
67   auto ty = fir::unwrapSequenceType(inType);
68   if (numParams > 0) {
69     if (auto recTy = ty.dyn_cast<fir::RecordType>())
70       return numParams != recTy.getNumLenParams();
71     if (auto chrTy = ty.dyn_cast<fir::CharacterType>())
72       return !(numParams == 1 && chrTy.hasDynamicLen());
73     return true;
74   }
75   if (auto chrTy = ty.dyn_cast<fir::CharacterType>())
76     return !chrTy.hasConstantLen();
77   return false;
78 }
79 
80 /// Parser shared by Alloca and Allocmem
81 ///
82 /// operation ::= %res = (`fir.alloca` | `fir.allocmem`) $in_type
83 ///                      ( `(` $typeparams `)` )? ( `,` $shape )?
84 ///                      attr-dict-without-keyword
85 template <typename FN>
86 static mlir::ParseResult parseAllocatableOp(FN wrapResultType,
87                                             mlir::OpAsmParser &parser,
88                                             mlir::OperationState &result) {
89   mlir::Type intype;
90   if (parser.parseType(intype))
91     return mlir::failure();
92   auto &builder = parser.getBuilder();
93   result.addAttribute("in_type", mlir::TypeAttr::get(intype));
94   llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
95   llvm::SmallVector<mlir::Type> typeVec;
96   bool hasOperands = false;
97   std::int32_t typeparamsSize = 0;
98   if (!parser.parseOptionalLParen()) {
99     // parse the LEN params of the derived type. (<params> : <types>)
100     if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) ||
101         parser.parseColonTypeList(typeVec) || parser.parseRParen())
102       return mlir::failure();
103     typeparamsSize = operands.size();
104     hasOperands = true;
105   }
106   std::int32_t shapeSize = 0;
107   if (!parser.parseOptionalComma()) {
108     // parse size to scale by, vector of n dimensions of type index
109     if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None))
110       return mlir::failure();
111     shapeSize = operands.size() - typeparamsSize;
112     auto idxTy = builder.getIndexType();
113     for (std::int32_t i = typeparamsSize, end = operands.size(); i != end; ++i)
114       typeVec.push_back(idxTy);
115     hasOperands = true;
116   }
117   if (hasOperands &&
118       parser.resolveOperands(operands, typeVec, parser.getNameLoc(),
119                              result.operands))
120     return mlir::failure();
121   mlir::Type restype = wrapResultType(intype);
122   if (!restype) {
123     parser.emitError(parser.getNameLoc(), "invalid allocate type: ") << intype;
124     return mlir::failure();
125   }
126   result.addAttribute("operand_segment_sizes",
127                       builder.getI32VectorAttr({typeparamsSize, shapeSize}));
128   if (parser.parseOptionalAttrDict(result.attributes) ||
129       parser.addTypeToList(restype, result.types))
130     return mlir::failure();
131   return mlir::success();
132 }
133 
134 template <typename OP>
135 static void printAllocatableOp(mlir::OpAsmPrinter &p, OP &op) {
136   p << ' ' << op.in_type();
137   if (!op.typeparams().empty()) {
138     p << '(' << op.typeparams() << " : " << op.typeparams().getTypes() << ')';
139   }
140   // print the shape of the allocation (if any); all must be index type
141   for (auto sh : op.shape()) {
142     p << ", ";
143     p.printOperand(sh);
144   }
145   p.printOptionalAttrDict(op->getAttrs(), {"in_type", "operand_segment_sizes"});
146 }
147 
148 //===----------------------------------------------------------------------===//
149 // AllocaOp
150 //===----------------------------------------------------------------------===//
151 
152 /// Create a legal memory reference as return type
153 static mlir::Type wrapAllocaResultType(mlir::Type intype) {
154   // FIR semantics: memory references to memory references are disallowed
155   if (intype.isa<ReferenceType>())
156     return {};
157   return ReferenceType::get(intype);
158 }
159 
160 mlir::Type fir::AllocaOp::getAllocatedType() {
161   return getType().cast<ReferenceType>().getEleTy();
162 }
163 
164 mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) {
165   return ReferenceType::get(ty);
166 }
167 
168 void fir::AllocaOp::build(mlir::OpBuilder &builder,
169                           mlir::OperationState &result, mlir::Type inType,
170                           llvm::StringRef uniqName, mlir::ValueRange typeparams,
171                           mlir::ValueRange shape,
172                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
173   auto nameAttr = builder.getStringAttr(uniqName);
174   build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, {},
175         /*pinned=*/false, typeparams, shape);
176   result.addAttributes(attributes);
177 }
178 
179 void fir::AllocaOp::build(mlir::OpBuilder &builder,
180                           mlir::OperationState &result, mlir::Type inType,
181                           llvm::StringRef uniqName, bool pinned,
182                           mlir::ValueRange typeparams, mlir::ValueRange shape,
183                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
184   auto nameAttr = builder.getStringAttr(uniqName);
185   build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, {},
186         pinned, typeparams, shape);
187   result.addAttributes(attributes);
188 }
189 
190 void fir::AllocaOp::build(mlir::OpBuilder &builder,
191                           mlir::OperationState &result, mlir::Type inType,
192                           llvm::StringRef uniqName, llvm::StringRef bindcName,
193                           mlir::ValueRange typeparams, mlir::ValueRange shape,
194                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
195   auto nameAttr =
196       uniqName.empty() ? mlir::StringAttr{} : builder.getStringAttr(uniqName);
197   auto bindcAttr =
198       bindcName.empty() ? mlir::StringAttr{} : builder.getStringAttr(bindcName);
199   build(builder, result, wrapAllocaResultType(inType), inType, nameAttr,
200         bindcAttr, /*pinned=*/false, typeparams, shape);
201   result.addAttributes(attributes);
202 }
203 
204 void fir::AllocaOp::build(mlir::OpBuilder &builder,
205                           mlir::OperationState &result, mlir::Type inType,
206                           llvm::StringRef uniqName, llvm::StringRef bindcName,
207                           bool pinned, mlir::ValueRange typeparams,
208                           mlir::ValueRange shape,
209                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
210   auto nameAttr =
211       uniqName.empty() ? mlir::StringAttr{} : builder.getStringAttr(uniqName);
212   auto bindcAttr =
213       bindcName.empty() ? mlir::StringAttr{} : builder.getStringAttr(bindcName);
214   build(builder, result, wrapAllocaResultType(inType), inType, nameAttr,
215         bindcAttr, pinned, typeparams, shape);
216   result.addAttributes(attributes);
217 }
218 
219 void fir::AllocaOp::build(mlir::OpBuilder &builder,
220                           mlir::OperationState &result, mlir::Type inType,
221                           mlir::ValueRange typeparams, mlir::ValueRange shape,
222                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
223   build(builder, result, wrapAllocaResultType(inType), inType, {}, {},
224         /*pinned=*/false, typeparams, shape);
225   result.addAttributes(attributes);
226 }
227 
228 void fir::AllocaOp::build(mlir::OpBuilder &builder,
229                           mlir::OperationState &result, mlir::Type inType,
230                           bool pinned, mlir::ValueRange typeparams,
231                           mlir::ValueRange shape,
232                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
233   build(builder, result, wrapAllocaResultType(inType), inType, {}, {}, pinned,
234         typeparams, shape);
235   result.addAttributes(attributes);
236 }
237 
238 static mlir::LogicalResult verify(fir::AllocaOp &op) {
239   llvm::SmallVector<llvm::StringRef> visited;
240   if (verifyInType(op.getInType(), visited, op.numShapeOperands()))
241     return op.emitOpError("invalid type for allocation");
242   if (verifyTypeParamCount(op.getInType(), op.numLenParams()))
243     return op.emitOpError("LEN params do not correspond to type");
244   mlir::Type outType = op.getType();
245   if (!outType.isa<fir::ReferenceType>())
246     return op.emitOpError("must be a !fir.ref type");
247   if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType)))
248     return op.emitOpError("cannot allocate !fir.box of unknown rank or type");
249   return mlir::success();
250 }
251 
252 //===----------------------------------------------------------------------===//
253 // AllocMemOp
254 //===----------------------------------------------------------------------===//
255 
256 /// Create a legal heap reference as return type
257 static mlir::Type wrapAllocMemResultType(mlir::Type intype) {
258   // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER
259   // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well
260   // FIR semantics: one may not allocate a memory reference value
261   if (intype.isa<ReferenceType>() || intype.isa<HeapType>() ||
262       intype.isa<PointerType>() || intype.isa<FunctionType>())
263     return {};
264   return HeapType::get(intype);
265 }
266 
267 mlir::Type fir::AllocMemOp::getAllocatedType() {
268   return getType().cast<HeapType>().getEleTy();
269 }
270 
271 mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) {
272   return HeapType::get(ty);
273 }
274 
275 void fir::AllocMemOp::build(mlir::OpBuilder &builder,
276                             mlir::OperationState &result, mlir::Type inType,
277                             llvm::StringRef uniqName,
278                             mlir::ValueRange typeparams, mlir::ValueRange shape,
279                             llvm::ArrayRef<mlir::NamedAttribute> attributes) {
280   auto nameAttr = builder.getStringAttr(uniqName);
281   build(builder, result, wrapAllocMemResultType(inType), inType, nameAttr, {},
282         typeparams, shape);
283   result.addAttributes(attributes);
284 }
285 
286 void fir::AllocMemOp::build(mlir::OpBuilder &builder,
287                             mlir::OperationState &result, mlir::Type inType,
288                             llvm::StringRef uniqName, llvm::StringRef bindcName,
289                             mlir::ValueRange typeparams, mlir::ValueRange shape,
290                             llvm::ArrayRef<mlir::NamedAttribute> attributes) {
291   auto nameAttr = builder.getStringAttr(uniqName);
292   auto bindcAttr = builder.getStringAttr(bindcName);
293   build(builder, result, wrapAllocMemResultType(inType), inType, nameAttr,
294         bindcAttr, typeparams, shape);
295   result.addAttributes(attributes);
296 }
297 
298 void fir::AllocMemOp::build(mlir::OpBuilder &builder,
299                             mlir::OperationState &result, mlir::Type inType,
300                             mlir::ValueRange typeparams, mlir::ValueRange shape,
301                             llvm::ArrayRef<mlir::NamedAttribute> attributes) {
302   build(builder, result, wrapAllocMemResultType(inType), inType, {}, {},
303         typeparams, shape);
304   result.addAttributes(attributes);
305 }
306 
307 static mlir::LogicalResult verify(fir::AllocMemOp op) {
308   llvm::SmallVector<llvm::StringRef> visited;
309   if (verifyInType(op.getInType(), visited, op.numShapeOperands()))
310     return op.emitOpError("invalid type for allocation");
311   if (verifyTypeParamCount(op.getInType(), op.numLenParams()))
312     return op.emitOpError("LEN params do not correspond to type");
313   mlir::Type outType = op.getType();
314   if (!outType.dyn_cast<fir::HeapType>())
315     return op.emitOpError("must be a !fir.heap type");
316   if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType)))
317     return op.emitOpError("cannot allocate !fir.box of unknown rank or type");
318   return mlir::success();
319 }
320 
321 //===----------------------------------------------------------------------===//
322 // ArrayCoorOp
323 //===----------------------------------------------------------------------===//
324 
325 static mlir::LogicalResult verify(fir::ArrayCoorOp op) {
326   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
327   auto arrTy = eleTy.dyn_cast<fir::SequenceType>();
328   if (!arrTy)
329     return op.emitOpError("must be a reference to an array");
330   auto arrDim = arrTy.getDimension();
331 
332   if (auto shapeOp = op.shape()) {
333     auto shapeTy = shapeOp.getType();
334     unsigned shapeTyRank = 0;
335     if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) {
336       shapeTyRank = s.getRank();
337     } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) {
338       shapeTyRank = ss.getRank();
339     } else {
340       auto s = shapeTy.cast<fir::ShiftType>();
341       shapeTyRank = s.getRank();
342       if (!op.memref().getType().isa<fir::BoxType>())
343         return op.emitOpError("shift can only be provided with fir.box memref");
344     }
345     if (arrDim && arrDim != shapeTyRank)
346       return op.emitOpError("rank of dimension mismatched");
347     if (shapeTyRank != op.indices().size())
348       return op.emitOpError("number of indices do not match dim rank");
349   }
350 
351   if (auto sliceOp = op.slice())
352     if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>())
353       if (sliceTy.getRank() != arrDim)
354         return op.emitOpError("rank of dimension in slice mismatched");
355 
356   return mlir::success();
357 }
358 
359 //===----------------------------------------------------------------------===//
360 // ArrayLoadOp
361 //===----------------------------------------------------------------------===//
362 
363 static mlir::Type adjustedElementType(mlir::Type t) {
364   if (auto ty = t.dyn_cast<fir::ReferenceType>()) {
365     auto eleTy = ty.getEleTy();
366     if (fir::isa_char(eleTy))
367       return eleTy;
368     if (fir::isa_derived(eleTy))
369       return eleTy;
370     if (eleTy.isa<fir::SequenceType>())
371       return eleTy;
372   }
373   return t;
374 }
375 
376 std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() {
377   if (auto sh = shape())
378     if (auto *op = sh.getDefiningOp()) {
379       if (auto shOp = dyn_cast<fir::ShapeOp>(op))
380         return shOp.getExtents();
381       return cast<fir::ShapeShiftOp>(op).getExtents();
382     }
383   return {};
384 }
385 
386 static mlir::LogicalResult verify(fir::ArrayLoadOp op) {
387   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
388   auto arrTy = eleTy.dyn_cast<fir::SequenceType>();
389   if (!arrTy)
390     return op.emitOpError("must be a reference to an array");
391   auto arrDim = arrTy.getDimension();
392 
393   if (auto shapeOp = op.shape()) {
394     auto shapeTy = shapeOp.getType();
395     unsigned shapeTyRank = 0;
396     if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) {
397       shapeTyRank = s.getRank();
398     } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) {
399       shapeTyRank = ss.getRank();
400     } else {
401       auto s = shapeTy.cast<fir::ShiftType>();
402       shapeTyRank = s.getRank();
403       if (!op.memref().getType().isa<fir::BoxType>())
404         return op.emitOpError("shift can only be provided with fir.box memref");
405     }
406     if (arrDim && arrDim != shapeTyRank)
407       return op.emitOpError("rank of dimension mismatched");
408   }
409 
410   if (auto sliceOp = op.slice())
411     if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>())
412       if (sliceTy.getRank() != arrDim)
413         return op.emitOpError("rank of dimension in slice mismatched");
414 
415   return mlir::success();
416 }
417 
418 //===----------------------------------------------------------------------===//
419 // ArrayMergeStoreOp
420 //===----------------------------------------------------------------------===//
421 
422 static mlir::LogicalResult verify(fir::ArrayMergeStoreOp op) {
423   if (!isa<ArrayLoadOp>(op.original().getDefiningOp()))
424     return op.emitOpError("operand #0 must be result of a fir.array_load op");
425   if (auto sl = op.slice()) {
426     if (auto *slOp = sl.getDefiningOp()) {
427       auto sliceOp = mlir::cast<fir::SliceOp>(slOp);
428       if (!sliceOp.fields().empty()) {
429         // This is an intra-object merge, where the slice is projecting the
430         // subfields that are to be overwritten by the merge operation.
431         auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
432         if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) {
433           auto projTy =
434               fir::applyPathToType(seqTy.getEleTy(), sliceOp.fields());
435           if (fir::unwrapSequenceType(op.original().getType()) != projTy)
436             return op.emitOpError(
437                 "type of origin does not match sliced memref type");
438           if (fir::unwrapSequenceType(op.sequence().getType()) != projTy)
439             return op.emitOpError(
440                 "type of sequence does not match sliced memref type");
441           return mlir::success();
442         }
443         return op.emitOpError("referenced type is not an array");
444       }
445     }
446     return mlir::success();
447   }
448   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
449   if (op.original().getType() != eleTy)
450     return op.emitOpError("type of origin does not match memref element type");
451   if (op.sequence().getType() != eleTy)
452     return op.emitOpError(
453         "type of sequence does not match memref element type");
454   return mlir::success();
455 }
456 
457 //===----------------------------------------------------------------------===//
458 // ArrayFetchOp
459 //===----------------------------------------------------------------------===//
460 
461 // Template function used for both array_fetch and array_update verification.
462 template <typename A>
463 mlir::Type validArraySubobject(A op) {
464   auto ty = op.sequence().getType();
465   return fir::applyPathToType(ty, op.indices());
466 }
467 
468 static mlir::LogicalResult verify(fir::ArrayFetchOp op) {
469   auto arrTy = op.sequence().getType().cast<fir::SequenceType>();
470   auto indSize = op.indices().size();
471   if (indSize < arrTy.getDimension())
472     return op.emitOpError("number of indices != dimension of array");
473   if (indSize == arrTy.getDimension() &&
474       ::adjustedElementType(op.element().getType()) != arrTy.getEleTy())
475     return op.emitOpError("return type does not match array");
476   auto ty = validArraySubobject(op);
477   if (!ty || ty != ::adjustedElementType(op.getType()))
478     return op.emitOpError("return type and/or indices do not type check");
479   if (!isa<fir::ArrayLoadOp>(op.sequence().getDefiningOp()))
480     return op.emitOpError("argument #0 must be result of fir.array_load");
481   return mlir::success();
482 }
483 
484 //===----------------------------------------------------------------------===//
485 // ArrayUpdateOp
486 //===----------------------------------------------------------------------===//
487 
488 static mlir::LogicalResult verify(fir::ArrayUpdateOp op) {
489   auto arrTy = op.sequence().getType().cast<fir::SequenceType>();
490   auto indSize = op.indices().size();
491   if (indSize < arrTy.getDimension())
492     return op.emitOpError("number of indices != dimension of array");
493   if (indSize == arrTy.getDimension() &&
494       ::adjustedElementType(op.merge().getType()) != arrTy.getEleTy())
495     return op.emitOpError("merged value does not have element type");
496   auto ty = validArraySubobject(op);
497   if (!ty || ty != ::adjustedElementType(op.merge().getType()))
498     return op.emitOpError("merged value and/or indices do not type check");
499   return mlir::success();
500 }
501 
502 //===----------------------------------------------------------------------===//
503 // ArrayModifyOp
504 //===----------------------------------------------------------------------===//
505 
506 static mlir::LogicalResult verify(fir::ArrayModifyOp op) {
507   auto arrTy = op.sequence().getType().cast<fir::SequenceType>();
508   auto indSize = op.indices().size();
509   if (indSize < arrTy.getDimension())
510     return op.emitOpError("number of indices must match array dimension");
511   return mlir::success();
512 }
513 
514 //===----------------------------------------------------------------------===//
515 // BoxAddrOp
516 //===----------------------------------------------------------------------===//
517 
518 mlir::OpFoldResult fir::BoxAddrOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
519   if (auto v = val().getDefiningOp()) {
520     if (auto box = dyn_cast<fir::EmboxOp>(v))
521       return box.memref();
522     if (auto box = dyn_cast<fir::EmboxCharOp>(v))
523       return box.memref();
524   }
525   return {};
526 }
527 
528 //===----------------------------------------------------------------------===//
529 // BoxCharLenOp
530 //===----------------------------------------------------------------------===//
531 
532 mlir::OpFoldResult
533 fir::BoxCharLenOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
534   if (auto v = val().getDefiningOp()) {
535     if (auto box = dyn_cast<fir::EmboxCharOp>(v))
536       return box.len();
537   }
538   return {};
539 }
540 
541 //===----------------------------------------------------------------------===//
542 // BoxDimsOp
543 //===----------------------------------------------------------------------===//
544 
545 /// Get the result types packed in a tuple tuple
546 mlir::Type fir::BoxDimsOp::getTupleType() {
547   // note: triple, but 4 is nearest power of 2
548   llvm::SmallVector<mlir::Type> triple{
549       getResult(0).getType(), getResult(1).getType(), getResult(2).getType()};
550   return mlir::TupleType::get(getContext(), triple);
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // CallOp
555 //===----------------------------------------------------------------------===//
556 
557 mlir::FunctionType fir::CallOp::getFunctionType() {
558   return mlir::FunctionType::get(getContext(), getOperandTypes(),
559                                  getResultTypes());
560 }
561 
562 static void printCallOp(mlir::OpAsmPrinter &p, fir::CallOp &op) {
563   auto callee = op.callee();
564   bool isDirect = callee.hasValue();
565   p << ' ';
566   if (isDirect)
567     p << callee.getValue();
568   else
569     p << op.getOperand(0);
570   p << '(' << op->getOperands().drop_front(isDirect ? 0 : 1) << ')';
571   p.printOptionalAttrDict(op->getAttrs(), {"callee"});
572   auto resultTypes{op.getResultTypes()};
573   llvm::SmallVector<Type> argTypes(
574       llvm::drop_begin(op.getOperandTypes(), isDirect ? 0 : 1));
575   p << " : " << FunctionType::get(op.getContext(), argTypes, resultTypes);
576 }
577 
578 static mlir::ParseResult parseCallOp(mlir::OpAsmParser &parser,
579                                      mlir::OperationState &result) {
580   llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
581   if (parser.parseOperandList(operands))
582     return mlir::failure();
583 
584   mlir::NamedAttrList attrs;
585   mlir::SymbolRefAttr funcAttr;
586   bool isDirect = operands.empty();
587   if (isDirect)
588     if (parser.parseAttribute(funcAttr, "callee", attrs))
589       return mlir::failure();
590 
591   Type type;
592   if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) ||
593       parser.parseOptionalAttrDict(attrs) || parser.parseColon() ||
594       parser.parseType(type))
595     return mlir::failure();
596 
597   auto funcType = type.dyn_cast<mlir::FunctionType>();
598   if (!funcType)
599     return parser.emitError(parser.getNameLoc(), "expected function type");
600   if (isDirect) {
601     if (parser.resolveOperands(operands, funcType.getInputs(),
602                                parser.getNameLoc(), result.operands))
603       return mlir::failure();
604   } else {
605     auto funcArgs =
606         llvm::ArrayRef<mlir::OpAsmParser::OperandType>(operands).drop_front();
607     if (parser.resolveOperand(operands[0], funcType, result.operands) ||
608         parser.resolveOperands(funcArgs, funcType.getInputs(),
609                                parser.getNameLoc(), result.operands))
610       return mlir::failure();
611   }
612   result.addTypes(funcType.getResults());
613   result.attributes = attrs;
614   return mlir::success();
615 }
616 
617 void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
618                         mlir::FuncOp callee, mlir::ValueRange operands) {
619   result.addOperands(operands);
620   result.addAttribute(getCalleeAttrName(), SymbolRefAttr::get(callee));
621   result.addTypes(callee.getType().getResults());
622 }
623 
624 void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
625                         mlir::SymbolRefAttr callee,
626                         llvm::ArrayRef<mlir::Type> results,
627                         mlir::ValueRange operands) {
628   result.addOperands(operands);
629   if (callee)
630     result.addAttribute(getCalleeAttrName(), callee);
631   result.addTypes(results);
632 }
633 
634 //===----------------------------------------------------------------------===//
635 // CmpOp
636 //===----------------------------------------------------------------------===//
637 
638 template <typename OPTY>
639 static void printCmpOp(OpAsmPrinter &p, OPTY op) {
640   p << ' ';
641   auto predSym = mlir::arith::symbolizeCmpFPredicate(
642       op->template getAttrOfType<mlir::IntegerAttr>(
643             OPTY::getPredicateAttrName())
644           .getInt());
645   assert(predSym.hasValue() && "invalid symbol value for predicate");
646   p << '"' << mlir::arith::stringifyCmpFPredicate(predSym.getValue()) << '"'
647     << ", ";
648   p.printOperand(op.lhs());
649   p << ", ";
650   p.printOperand(op.rhs());
651   p.printOptionalAttrDict(op->getAttrs(),
652                           /*elidedAttrs=*/{OPTY::getPredicateAttrName()});
653   p << " : " << op.lhs().getType();
654 }
655 
656 template <typename OPTY>
657 static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser,
658                                     mlir::OperationState &result) {
659   llvm::SmallVector<mlir::OpAsmParser::OperandType> ops;
660   mlir::NamedAttrList attrs;
661   mlir::Attribute predicateNameAttr;
662   mlir::Type type;
663   if (parser.parseAttribute(predicateNameAttr, OPTY::getPredicateAttrName(),
664                             attrs) ||
665       parser.parseComma() || parser.parseOperandList(ops, 2) ||
666       parser.parseOptionalAttrDict(attrs) || parser.parseColonType(type) ||
667       parser.resolveOperands(ops, type, result.operands))
668     return failure();
669 
670   if (!predicateNameAttr.isa<mlir::StringAttr>())
671     return parser.emitError(parser.getNameLoc(),
672                             "expected string comparison predicate attribute");
673 
674   // Rewrite string attribute to an enum value.
675   llvm::StringRef predicateName =
676       predicateNameAttr.cast<mlir::StringAttr>().getValue();
677   auto predicate = fir::CmpcOp::getPredicateByName(predicateName);
678   auto builder = parser.getBuilder();
679   mlir::Type i1Type = builder.getI1Type();
680   attrs.set(OPTY::getPredicateAttrName(),
681             builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
682   result.attributes = attrs;
683   result.addTypes({i1Type});
684   return success();
685 }
686 
687 //===----------------------------------------------------------------------===//
688 // CharConvertOp
689 //===----------------------------------------------------------------------===//
690 
691 static mlir::LogicalResult verify(fir::CharConvertOp op) {
692   auto unwrap = [&](mlir::Type t) {
693     t = fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t));
694     return t.dyn_cast<fir::CharacterType>();
695   };
696   auto inTy = unwrap(op.from().getType());
697   auto outTy = unwrap(op.to().getType());
698   if (!(inTy && outTy))
699     return op.emitOpError("not a reference to a character");
700   if (inTy.getFKind() == outTy.getFKind())
701     return op.emitOpError("buffers must have different KIND values");
702   return mlir::success();
703 }
704 
705 //===----------------------------------------------------------------------===//
706 // CmpcOp
707 //===----------------------------------------------------------------------===//
708 
709 void fir::buildCmpCOp(OpBuilder &builder, OperationState &result,
710                       arith::CmpFPredicate predicate, Value lhs, Value rhs) {
711   result.addOperands({lhs, rhs});
712   result.types.push_back(builder.getI1Type());
713   result.addAttribute(
714       fir::CmpcOp::getPredicateAttrName(),
715       builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
716 }
717 
718 mlir::arith::CmpFPredicate
719 fir::CmpcOp::getPredicateByName(llvm::StringRef name) {
720   auto pred = mlir::arith::symbolizeCmpFPredicate(name);
721   assert(pred.hasValue() && "invalid predicate name");
722   return pred.getValue();
723 }
724 
725 static void printCmpcOp(OpAsmPrinter &p, fir::CmpcOp op) { printCmpOp(p, op); }
726 
727 mlir::ParseResult fir::parseCmpcOp(mlir::OpAsmParser &parser,
728                                    mlir::OperationState &result) {
729   return parseCmpOp<fir::CmpcOp>(parser, result);
730 }
731 
732 //===----------------------------------------------------------------------===//
733 // ConstcOp
734 //===----------------------------------------------------------------------===//
735 
736 static mlir::ParseResult parseConstcOp(mlir::OpAsmParser &parser,
737                                        mlir::OperationState &result) {
738   fir::RealAttr realp;
739   fir::RealAttr imagp;
740   mlir::Type type;
741   if (parser.parseLParen() ||
742       parser.parseAttribute(realp, fir::ConstcOp::realAttrName(),
743                             result.attributes) ||
744       parser.parseComma() ||
745       parser.parseAttribute(imagp, fir::ConstcOp::imagAttrName(),
746                             result.attributes) ||
747       parser.parseRParen() || parser.parseColonType(type) ||
748       parser.addTypesToList(type, result.types))
749     return mlir::failure();
750   return mlir::success();
751 }
752 
753 static void print(mlir::OpAsmPrinter &p, fir::ConstcOp &op) {
754   p << " (0x";
755   auto f1 = op.getOperation()
756                 ->getAttr(fir::ConstcOp::realAttrName())
757                 .cast<mlir::FloatAttr>();
758   auto i1 = f1.getValue().bitcastToAPInt();
759   p.getStream().write_hex(i1.getZExtValue());
760   p << ", 0x";
761   auto f2 = op.getOperation()
762                 ->getAttr(fir::ConstcOp::imagAttrName())
763                 .cast<mlir::FloatAttr>();
764   auto i2 = f2.getValue().bitcastToAPInt();
765   p.getStream().write_hex(i2.getZExtValue());
766   p << ") : ";
767   p.printType(op.getType());
768 }
769 
770 static mlir::LogicalResult verify(fir::ConstcOp &op) {
771   if (!op.getType().isa<fir::ComplexType>())
772     return op.emitOpError("must be a !fir.complex type");
773   return mlir::success();
774 }
775 
776 //===----------------------------------------------------------------------===//
777 // ConvertOp
778 //===----------------------------------------------------------------------===//
779 
780 void fir::ConvertOp::getCanonicalizationPatterns(
781     OwningRewritePatternList &results, MLIRContext *context) {
782   results.insert<ConvertConvertOptPattern, RedundantConvertOptPattern,
783                  CombineConvertOptPattern, ForwardConstantConvertPattern>(
784       context);
785 }
786 
787 mlir::OpFoldResult fir::ConvertOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
788   if (value().getType() == getType())
789     return value();
790   if (matchPattern(value(), m_Op<fir::ConvertOp>())) {
791     auto inner = cast<fir::ConvertOp>(value().getDefiningOp());
792     // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a
793     if (auto toTy = getType().dyn_cast<fir::LogicalType>())
794       if (auto fromTy = inner.value().getType().dyn_cast<fir::LogicalType>())
795         if (inner.getType().isa<mlir::IntegerType>() && (toTy == fromTy))
796           return inner.value();
797     // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a
798     if (auto toTy = getType().dyn_cast<mlir::IntegerType>())
799       if (auto fromTy = inner.value().getType().dyn_cast<mlir::IntegerType>())
800         if (inner.getType().isa<fir::LogicalType>() && (toTy == fromTy) &&
801             (fromTy.getWidth() == 1))
802           return inner.value();
803   }
804   return {};
805 }
806 
807 bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) {
808   return ty.isa<mlir::IntegerType>() || ty.isa<mlir::IndexType>() ||
809          ty.isa<fir::IntegerType>() || ty.isa<fir::LogicalType>();
810 }
811 
812 bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) {
813   return ty.isa<mlir::FloatType>() || ty.isa<fir::RealType>();
814 }
815 
816 bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) {
817   return ty.isa<fir::ReferenceType>() || ty.isa<fir::PointerType>() ||
818          ty.isa<fir::HeapType>() || ty.isa<mlir::MemRefType>() ||
819          ty.isa<mlir::FunctionType>() || ty.isa<fir::TypeDescType>();
820 }
821 
822 static mlir::LogicalResult verify(fir::ConvertOp &op) {
823   auto inType = op.value().getType();
824   auto outType = op.getType();
825   if (inType == outType)
826     return mlir::success();
827   if ((op.isPointerCompatible(inType) && op.isPointerCompatible(outType)) ||
828       (op.isIntegerCompatible(inType) && op.isIntegerCompatible(outType)) ||
829       (op.isIntegerCompatible(inType) && op.isFloatCompatible(outType)) ||
830       (op.isFloatCompatible(inType) && op.isIntegerCompatible(outType)) ||
831       (op.isFloatCompatible(inType) && op.isFloatCompatible(outType)) ||
832       (op.isIntegerCompatible(inType) && op.isPointerCompatible(outType)) ||
833       (op.isPointerCompatible(inType) && op.isIntegerCompatible(outType)) ||
834       (inType.isa<fir::BoxType>() && outType.isa<fir::BoxType>()) ||
835       (fir::isa_complex(inType) && fir::isa_complex(outType)))
836     return mlir::success();
837   return op.emitOpError("invalid type conversion");
838 }
839 
840 //===----------------------------------------------------------------------===//
841 // CoordinateOp
842 //===----------------------------------------------------------------------===//
843 
844 static void print(mlir::OpAsmPrinter &p, fir::CoordinateOp op) {
845   p << ' ' << op.ref() << ", " << op.coor();
846   p.printOptionalAttrDict(op->getAttrs(), /*elideAttrs=*/{"baseType"});
847   p << " : ";
848   p.printFunctionalType(op.getOperandTypes(), op->getResultTypes());
849 }
850 
851 static mlir::ParseResult parseCoordinateCustom(mlir::OpAsmParser &parser,
852                                                mlir::OperationState &result) {
853   mlir::OpAsmParser::OperandType memref;
854   if (parser.parseOperand(memref) || parser.parseComma())
855     return mlir::failure();
856   llvm::SmallVector<mlir::OpAsmParser::OperandType> coorOperands;
857   if (parser.parseOperandList(coorOperands))
858     return mlir::failure();
859   llvm::SmallVector<mlir::OpAsmParser::OperandType> allOperands;
860   allOperands.push_back(memref);
861   allOperands.append(coorOperands.begin(), coorOperands.end());
862   mlir::FunctionType funcTy;
863   auto loc = parser.getCurrentLocation();
864   if (parser.parseOptionalAttrDict(result.attributes) ||
865       parser.parseColonType(funcTy) ||
866       parser.resolveOperands(allOperands, funcTy.getInputs(), loc,
867                              result.operands))
868     return failure();
869   parser.addTypesToList(funcTy.getResults(), result.types);
870   result.addAttribute("baseType", mlir::TypeAttr::get(funcTy.getInput(0)));
871   return mlir::success();
872 }
873 
874 static mlir::LogicalResult verify(fir::CoordinateOp op) {
875   auto refTy = op.ref().getType();
876   if (fir::isa_ref_type(refTy)) {
877     auto eleTy = fir::dyn_cast_ptrEleTy(refTy);
878     if (auto arrTy = eleTy.dyn_cast<fir::SequenceType>()) {
879       if (arrTy.hasUnknownShape())
880         return op.emitOpError("cannot find coordinate in unknown shape");
881       if (arrTy.getConstantRows() < arrTy.getDimension() - 1)
882         return op.emitOpError("cannot find coordinate with unknown extents");
883     }
884     if (!(fir::isa_aggregate(eleTy) || fir::isa_complex(eleTy) ||
885           fir::isa_char_string(eleTy)))
886       return op.emitOpError("cannot apply coordinate_of to this type");
887   }
888   // Recovering a LEN type parameter only makes sense from a boxed value. For a
889   // bare reference, the LEN type parameters must be passed as additional
890   // arguments to `op`.
891   for (auto co : op.coor())
892     if (dyn_cast_or_null<fir::LenParamIndexOp>(co.getDefiningOp())) {
893       if (op.getNumOperands() != 2)
894         return op.emitOpError("len_param_index must be last argument");
895       if (!op.ref().getType().isa<BoxType>())
896         return op.emitOpError("len_param_index must be used on box type");
897     }
898   return mlir::success();
899 }
900 
901 //===----------------------------------------------------------------------===//
902 // DispatchOp
903 //===----------------------------------------------------------------------===//
904 
905 mlir::FunctionType fir::DispatchOp::getFunctionType() {
906   return mlir::FunctionType::get(getContext(), getOperandTypes(),
907                                  getResultTypes());
908 }
909 
910 static mlir::ParseResult parseDispatchOp(mlir::OpAsmParser &parser,
911                                          mlir::OperationState &result) {
912   mlir::FunctionType calleeType;
913   llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
914   auto calleeLoc = parser.getNameLoc();
915   llvm::StringRef calleeName;
916   if (failed(parser.parseOptionalKeyword(&calleeName))) {
917     mlir::StringAttr calleeAttr;
918     if (parser.parseAttribute(calleeAttr, fir::DispatchOp::getMethodAttrName(),
919                               result.attributes))
920       return mlir::failure();
921   } else {
922     result.addAttribute(fir::DispatchOp::getMethodAttrName(),
923                         parser.getBuilder().getStringAttr(calleeName));
924   }
925   if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) ||
926       parser.parseOptionalAttrDict(result.attributes) ||
927       parser.parseColonType(calleeType) ||
928       parser.addTypesToList(calleeType.getResults(), result.types) ||
929       parser.resolveOperands(operands, calleeType.getInputs(), calleeLoc,
930                              result.operands))
931     return mlir::failure();
932   return mlir::success();
933 }
934 
935 static void print(mlir::OpAsmPrinter &p, fir::DispatchOp &op) {
936   p << ' ' << op.getOperation()->getAttr(fir::DispatchOp::getMethodAttrName())
937     << '(';
938   p.printOperand(op.object());
939   if (!op.args().empty()) {
940     p << ", ";
941     p.printOperands(op.args());
942   }
943   p << ") : ";
944   p.printFunctionalType(op.getOperation()->getOperandTypes(),
945                         op.getOperation()->getResultTypes());
946 }
947 
948 //===----------------------------------------------------------------------===//
949 // DispatchTableOp
950 //===----------------------------------------------------------------------===//
951 
952 void fir::DispatchTableOp::appendTableEntry(mlir::Operation *op) {
953   assert(mlir::isa<fir::DTEntryOp>(*op) && "operation must be a DTEntryOp");
954   auto &block = getBlock();
955   block.getOperations().insert(block.end(), op);
956 }
957 
958 static mlir::ParseResult parseDispatchTableOp(mlir::OpAsmParser &parser,
959                                               mlir::OperationState &result) {
960   // Parse the name as a symbol reference attribute.
961   SymbolRefAttr nameAttr;
962   if (parser.parseAttribute(nameAttr, mlir::SymbolTable::getSymbolAttrName(),
963                             result.attributes))
964     return failure();
965 
966   // Convert the parsed name attr into a string attr.
967   result.attributes.set(mlir::SymbolTable::getSymbolAttrName(),
968                         nameAttr.getRootReference());
969 
970   // Parse the optional table body.
971   mlir::Region *body = result.addRegion();
972   OptionalParseResult parseResult = parser.parseOptionalRegion(*body);
973   if (parseResult.hasValue() && failed(*parseResult))
974     return mlir::failure();
975 
976   fir::DispatchTableOp::ensureTerminator(*body, parser.getBuilder(),
977                                          result.location);
978   return mlir::success();
979 }
980 
981 static void print(mlir::OpAsmPrinter &p, fir::DispatchTableOp &op) {
982   auto tableName =
983       op.getOperation()
984           ->getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName())
985           .getValue();
986   p << " @" << tableName;
987 
988   Region &body = op.getOperation()->getRegion(0);
989   if (!body.empty())
990     p.printRegion(body, /*printEntryBlockArgs=*/false,
991                   /*printBlockTerminators=*/false);
992 }
993 
994 static mlir::LogicalResult verify(fir::DispatchTableOp &op) {
995   for (auto &op : op.getBlock())
996     if (!(isa<fir::DTEntryOp>(op) || isa<fir::FirEndOp>(op)))
997       return op.emitOpError("dispatch table must contain dt_entry");
998   return mlir::success();
999 }
1000 
1001 //===----------------------------------------------------------------------===//
1002 // EmboxOp
1003 //===----------------------------------------------------------------------===//
1004 
1005 static mlir::LogicalResult verify(fir::EmboxOp op) {
1006   auto eleTy = fir::dyn_cast_ptrEleTy(op.memref().getType());
1007   bool isArray = false;
1008   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) {
1009     eleTy = seqTy.getEleTy();
1010     isArray = true;
1011   }
1012   if (op.hasLenParams()) {
1013     auto lenPs = op.numLenParams();
1014     if (auto rt = eleTy.dyn_cast<fir::RecordType>()) {
1015       if (lenPs != rt.getNumLenParams())
1016         return op.emitOpError("number of LEN params does not correspond"
1017                               " to the !fir.type type");
1018     } else if (auto strTy = eleTy.dyn_cast<fir::CharacterType>()) {
1019       if (strTy.getLen() != fir::CharacterType::unknownLen())
1020         return op.emitOpError("CHARACTER already has static LEN");
1021     } else {
1022       return op.emitOpError("LEN parameters require CHARACTER or derived type");
1023     }
1024     for (auto lp : op.typeparams())
1025       if (!fir::isa_integer(lp.getType()))
1026         return op.emitOpError("LEN parameters must be integral type");
1027   }
1028   if (op.getShape() && !isArray)
1029     return op.emitOpError("shape must not be provided for a scalar");
1030   if (op.getSlice() && !isArray)
1031     return op.emitOpError("slice must not be provided for a scalar");
1032   return mlir::success();
1033 }
1034 
1035 //===----------------------------------------------------------------------===//
1036 // EmboxCharOp
1037 //===----------------------------------------------------------------------===//
1038 
1039 static mlir::LogicalResult verify(fir::EmboxCharOp &op) {
1040   auto eleTy = fir::dyn_cast_ptrEleTy(op.memref().getType());
1041   if (!eleTy.dyn_cast_or_null<CharacterType>())
1042     return mlir::failure();
1043   return mlir::success();
1044 }
1045 
1046 //===----------------------------------------------------------------------===//
1047 // EmboxProcOp
1048 //===----------------------------------------------------------------------===//
1049 
1050 static mlir::ParseResult parseEmboxProcOp(mlir::OpAsmParser &parser,
1051                                           mlir::OperationState &result) {
1052   mlir::SymbolRefAttr procRef;
1053   if (parser.parseAttribute(procRef, "funcname", result.attributes))
1054     return mlir::failure();
1055   bool hasTuple = false;
1056   mlir::OpAsmParser::OperandType tupleRef;
1057   if (!parser.parseOptionalComma()) {
1058     if (parser.parseOperand(tupleRef))
1059       return mlir::failure();
1060     hasTuple = true;
1061   }
1062   mlir::FunctionType type;
1063   if (parser.parseColon() || parser.parseLParen() || parser.parseType(type))
1064     return mlir::failure();
1065   result.addAttribute("functype", mlir::TypeAttr::get(type));
1066   if (hasTuple) {
1067     mlir::Type tupleType;
1068     if (parser.parseComma() || parser.parseType(tupleType) ||
1069         parser.resolveOperand(tupleRef, tupleType, result.operands))
1070       return mlir::failure();
1071   }
1072   mlir::Type boxType;
1073   if (parser.parseRParen() || parser.parseArrow() ||
1074       parser.parseType(boxType) || parser.addTypesToList(boxType, result.types))
1075     return mlir::failure();
1076   return mlir::success();
1077 }
1078 
1079 static void print(mlir::OpAsmPrinter &p, fir::EmboxProcOp &op) {
1080   p << ' ' << op.getOperation()->getAttr("funcname");
1081   auto h = op.host();
1082   if (h) {
1083     p << ", ";
1084     p.printOperand(h);
1085   }
1086   p << " : (" << op.getOperation()->getAttr("functype");
1087   if (h)
1088     p << ", " << h.getType();
1089   p << ") -> " << op.getType();
1090 }
1091 
1092 static mlir::LogicalResult verify(fir::EmboxProcOp &op) {
1093   // host bindings (optional) must be a reference to a tuple
1094   if (auto h = op.host()) {
1095     if (auto r = h.getType().dyn_cast<ReferenceType>()) {
1096       if (!r.getEleTy().dyn_cast<mlir::TupleType>())
1097         return mlir::failure();
1098     } else {
1099       return mlir::failure();
1100     }
1101   }
1102   return mlir::success();
1103 }
1104 
1105 //===----------------------------------------------------------------------===//
1106 // GenTypeDescOp
1107 //===----------------------------------------------------------------------===//
1108 
1109 void fir::GenTypeDescOp::build(OpBuilder &, OperationState &result,
1110                                mlir::TypeAttr inty) {
1111   result.addAttribute("in_type", inty);
1112   result.addTypes(TypeDescType::get(inty.getValue()));
1113 }
1114 
1115 static mlir::ParseResult parseGenTypeDescOp(mlir::OpAsmParser &parser,
1116                                             mlir::OperationState &result) {
1117   mlir::Type intype;
1118   if (parser.parseType(intype))
1119     return mlir::failure();
1120   result.addAttribute("in_type", mlir::TypeAttr::get(intype));
1121   mlir::Type restype = TypeDescType::get(intype);
1122   if (parser.addTypeToList(restype, result.types))
1123     return mlir::failure();
1124   return mlir::success();
1125 }
1126 
1127 static void print(mlir::OpAsmPrinter &p, fir::GenTypeDescOp &op) {
1128   p << ' ' << op.getOperation()->getAttr("in_type");
1129   p.printOptionalAttrDict(op.getOperation()->getAttrs(), {"in_type"});
1130 }
1131 
1132 static mlir::LogicalResult verify(fir::GenTypeDescOp &op) {
1133   mlir::Type resultTy = op.getType();
1134   if (auto tdesc = resultTy.dyn_cast<TypeDescType>()) {
1135     if (tdesc.getOfTy() != op.getInType())
1136       return op.emitOpError("wrapped type mismatched");
1137   } else {
1138     return op.emitOpError("must be !fir.tdesc type");
1139   }
1140   return mlir::success();
1141 }
1142 
1143 //===----------------------------------------------------------------------===//
1144 // GlobalOp
1145 //===----------------------------------------------------------------------===//
1146 
1147 static ParseResult parseGlobalOp(OpAsmParser &parser, OperationState &result) {
1148   // Parse the optional linkage
1149   llvm::StringRef linkage;
1150   auto &builder = parser.getBuilder();
1151   if (mlir::succeeded(parser.parseOptionalKeyword(&linkage))) {
1152     if (fir::GlobalOp::verifyValidLinkage(linkage))
1153       return mlir::failure();
1154     mlir::StringAttr linkAttr = builder.getStringAttr(linkage);
1155     result.addAttribute(fir::GlobalOp::linkageAttrName(), linkAttr);
1156   }
1157 
1158   // Parse the name as a symbol reference attribute.
1159   mlir::SymbolRefAttr nameAttr;
1160   if (parser.parseAttribute(nameAttr, fir::GlobalOp::symbolAttrName(),
1161                             result.attributes))
1162     return mlir::failure();
1163   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
1164                       nameAttr.getRootReference());
1165 
1166   bool simpleInitializer = false;
1167   if (mlir::succeeded(parser.parseOptionalLParen())) {
1168     Attribute attr;
1169     if (parser.parseAttribute(attr, "initVal", result.attributes) ||
1170         parser.parseRParen())
1171       return mlir::failure();
1172     simpleInitializer = true;
1173   }
1174 
1175   if (succeeded(parser.parseOptionalKeyword("constant"))) {
1176     // if "constant" keyword then mark this as a constant, not a variable
1177     result.addAttribute("constant", builder.getUnitAttr());
1178   }
1179 
1180   mlir::Type globalType;
1181   if (parser.parseColonType(globalType))
1182     return mlir::failure();
1183 
1184   result.addAttribute(fir::GlobalOp::typeAttrName(result.name),
1185                       mlir::TypeAttr::get(globalType));
1186 
1187   if (simpleInitializer) {
1188     result.addRegion();
1189   } else {
1190     // Parse the optional initializer body.
1191     auto parseResult = parser.parseOptionalRegion(
1192         *result.addRegion(), /*arguments=*/llvm::None, /*argTypes=*/llvm::None);
1193     if (parseResult.hasValue() && mlir::failed(*parseResult))
1194       return mlir::failure();
1195   }
1196 
1197   return mlir::success();
1198 }
1199 
1200 static void print(mlir::OpAsmPrinter &p, fir::GlobalOp &op) {
1201   if (op.linkName().hasValue())
1202     p << ' ' << op.linkName().getValue();
1203   p << ' ';
1204   p.printAttributeWithoutType(
1205       op.getOperation()->getAttr(fir::GlobalOp::symbolAttrName()));
1206   if (auto val = op.getValueOrNull())
1207     p << '(' << val << ')';
1208   if (op.getOperation()->getAttr(fir::GlobalOp::getConstantAttrName()))
1209     p << " constant";
1210   p << " : ";
1211   p.printType(op.getType());
1212   if (op.hasInitializationBody())
1213     p.printRegion(op.getOperation()->getRegion(0),
1214                   /*printEntryBlockArgs=*/false,
1215                   /*printBlockTerminators=*/true);
1216 }
1217 
1218 void fir::GlobalOp::appendInitialValue(mlir::Operation *op) {
1219   getBlock().getOperations().push_back(op);
1220 }
1221 
1222 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
1223                           StringRef name, bool isConstant, Type type,
1224                           Attribute initialVal, StringAttr linkage,
1225                           ArrayRef<NamedAttribute> attrs) {
1226   result.addRegion();
1227   result.addAttribute(typeAttrName(result.name), mlir::TypeAttr::get(type));
1228   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
1229                       builder.getStringAttr(name));
1230   result.addAttribute(symbolAttrName(),
1231                       SymbolRefAttr::get(builder.getContext(), name));
1232   if (isConstant)
1233     result.addAttribute(constantAttrName(result.name), builder.getUnitAttr());
1234   if (initialVal)
1235     result.addAttribute(initValAttrName(result.name), initialVal);
1236   if (linkage)
1237     result.addAttribute(linkageAttrName(), linkage);
1238   result.attributes.append(attrs.begin(), attrs.end());
1239 }
1240 
1241 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
1242                           StringRef name, Type type, Attribute initialVal,
1243                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
1244   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
1245 }
1246 
1247 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
1248                           StringRef name, bool isConstant, Type type,
1249                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
1250   build(builder, result, name, isConstant, type, {}, linkage, attrs);
1251 }
1252 
1253 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
1254                           StringRef name, Type type, StringAttr linkage,
1255                           ArrayRef<NamedAttribute> attrs) {
1256   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
1257 }
1258 
1259 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
1260                           StringRef name, bool isConstant, Type type,
1261                           ArrayRef<NamedAttribute> attrs) {
1262   build(builder, result, name, isConstant, type, StringAttr{}, attrs);
1263 }
1264 
1265 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
1266                           StringRef name, Type type,
1267                           ArrayRef<NamedAttribute> attrs) {
1268   build(builder, result, name, /*isConstant=*/false, type, attrs);
1269 }
1270 
1271 mlir::ParseResult fir::GlobalOp::verifyValidLinkage(StringRef linkage) {
1272   // Supporting only a subset of the LLVM linkage types for now
1273   static const char *validNames[] = {"common", "internal", "linkonce", "weak"};
1274   return mlir::success(llvm::is_contained(validNames, linkage));
1275 }
1276 
1277 template <bool AllowFields>
1278 static void appendAsAttribute(llvm::SmallVectorImpl<mlir::Attribute> &attrs,
1279                               mlir::Value val) {
1280   if (auto *op = val.getDefiningOp()) {
1281     if (auto cop = mlir::dyn_cast<mlir::arith::ConstantOp>(op)) {
1282       // append the integer constant value
1283       if (auto iattr = cop.value().dyn_cast<mlir::IntegerAttr>()) {
1284         attrs.push_back(iattr);
1285         return;
1286       }
1287     } else if (auto fld = mlir::dyn_cast<fir::FieldIndexOp>(op)) {
1288       if constexpr (AllowFields) {
1289         // append the field name and the record type
1290         attrs.push_back(fld.field_idAttr());
1291         attrs.push_back(fld.on_typeAttr());
1292         return;
1293       }
1294     }
1295   }
1296   llvm::report_fatal_error("cannot build Op with these arguments");
1297 }
1298 
1299 template <bool AllowFields = true>
1300 static mlir::ArrayAttr collectAsAttributes(mlir::MLIRContext *ctxt,
1301                                            OperationState &result,
1302                                            llvm::ArrayRef<mlir::Value> inds) {
1303   llvm::SmallVector<mlir::Attribute> attrs;
1304   for (auto v : inds)
1305     appendAsAttribute<AllowFields>(attrs, v);
1306   assert(!attrs.empty());
1307   return mlir::ArrayAttr::get(ctxt, attrs);
1308 }
1309 
1310 //===----------------------------------------------------------------------===//
1311 // GlobalLenOp
1312 //===----------------------------------------------------------------------===//
1313 
1314 static mlir::ParseResult parseGlobalLenOp(mlir::OpAsmParser &parser,
1315                                           mlir::OperationState &result) {
1316   llvm::StringRef fieldName;
1317   if (failed(parser.parseOptionalKeyword(&fieldName))) {
1318     mlir::StringAttr fieldAttr;
1319     if (parser.parseAttribute(fieldAttr, fir::GlobalLenOp::lenParamAttrName(),
1320                               result.attributes))
1321       return mlir::failure();
1322   } else {
1323     result.addAttribute(fir::GlobalLenOp::lenParamAttrName(),
1324                         parser.getBuilder().getStringAttr(fieldName));
1325   }
1326   mlir::IntegerAttr constant;
1327   if (parser.parseComma() ||
1328       parser.parseAttribute(constant, fir::GlobalLenOp::intAttrName(),
1329                             result.attributes))
1330     return mlir::failure();
1331   return mlir::success();
1332 }
1333 
1334 static void print(mlir::OpAsmPrinter &p, fir::GlobalLenOp &op) {
1335   p << ' ' << op.getOperation()->getAttr(fir::GlobalLenOp::lenParamAttrName())
1336     << ", " << op.getOperation()->getAttr(fir::GlobalLenOp::intAttrName());
1337 }
1338 
1339 //===----------------------------------------------------------------------===//
1340 // ExtractValueOp
1341 //===----------------------------------------------------------------------===//
1342 
1343 void fir::ExtractValueOp::build(mlir::OpBuilder &builder,
1344                                 OperationState &result, mlir::Type resTy,
1345                                 mlir::Value aggVal,
1346                                 llvm::ArrayRef<mlir::Value> inds) {
1347   auto aa = collectAsAttributes<>(builder.getContext(), result, inds);
1348   build(builder, result, resTy, aggVal, aa);
1349 }
1350 
1351 //===----------------------------------------------------------------------===//
1352 // FieldIndexOp
1353 //===----------------------------------------------------------------------===//
1354 
1355 static mlir::ParseResult parseFieldIndexOp(mlir::OpAsmParser &parser,
1356                                            mlir::OperationState &result) {
1357   llvm::StringRef fieldName;
1358   auto &builder = parser.getBuilder();
1359   mlir::Type recty;
1360   if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() ||
1361       parser.parseType(recty))
1362     return mlir::failure();
1363   result.addAttribute(fir::FieldIndexOp::fieldAttrName(),
1364                       builder.getStringAttr(fieldName));
1365   if (!recty.dyn_cast<RecordType>())
1366     return mlir::failure();
1367   result.addAttribute(fir::FieldIndexOp::typeAttrName(),
1368                       mlir::TypeAttr::get(recty));
1369   if (!parser.parseOptionalLParen()) {
1370     llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
1371     llvm::SmallVector<mlir::Type> types;
1372     auto loc = parser.getNameLoc();
1373     if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) ||
1374         parser.parseColonTypeList(types) || parser.parseRParen() ||
1375         parser.resolveOperands(operands, types, loc, result.operands))
1376       return mlir::failure();
1377   }
1378   mlir::Type fieldType = fir::FieldType::get(builder.getContext());
1379   if (parser.addTypeToList(fieldType, result.types))
1380     return mlir::failure();
1381   return mlir::success();
1382 }
1383 
1384 static void print(mlir::OpAsmPrinter &p, fir::FieldIndexOp &op) {
1385   p << ' '
1386     << op.getOperation()
1387            ->getAttrOfType<mlir::StringAttr>(fir::FieldIndexOp::fieldAttrName())
1388            .getValue()
1389     << ", " << op.getOperation()->getAttr(fir::FieldIndexOp::typeAttrName());
1390   if (op.getNumOperands()) {
1391     p << '(';
1392     p.printOperands(op.typeparams());
1393     const auto *sep = ") : ";
1394     for (auto op : op.typeparams()) {
1395       p << sep;
1396       if (op)
1397         p.printType(op.getType());
1398       else
1399         p << "()";
1400       sep = ", ";
1401     }
1402   }
1403 }
1404 
1405 void fir::FieldIndexOp::build(mlir::OpBuilder &builder,
1406                               mlir::OperationState &result,
1407                               llvm::StringRef fieldName, mlir::Type recTy,
1408                               mlir::ValueRange operands) {
1409   result.addAttribute(fieldAttrName(), builder.getStringAttr(fieldName));
1410   result.addAttribute(typeAttrName(), TypeAttr::get(recTy));
1411   result.addOperands(operands);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 // InsertOnRangeOp
1416 //===----------------------------------------------------------------------===//
1417 
1418 void fir::InsertOnRangeOp::build(mlir::OpBuilder &builder,
1419                                  OperationState &result, mlir::Type resTy,
1420                                  mlir::Value aggVal, mlir::Value eleVal,
1421                                  llvm::ArrayRef<mlir::Value> inds) {
1422   auto aa = collectAsAttributes<false>(builder.getContext(), result, inds);
1423   build(builder, result, resTy, aggVal, eleVal, aa);
1424 }
1425 
1426 /// Range bounds must be nonnegative, and the range must not be empty.
1427 static mlir::LogicalResult verify(fir::InsertOnRangeOp op) {
1428   if (op.coor().size() < 2 || op.coor().size() % 2 != 0)
1429     return op.emitOpError("has uneven number of values in ranges");
1430   bool rangeIsKnownToBeNonempty = false;
1431   for (auto i = op.coor().end(), b = op.coor().begin(); i != b;) {
1432     int64_t ub = (*--i).cast<IntegerAttr>().getInt();
1433     int64_t lb = (*--i).cast<IntegerAttr>().getInt();
1434     if (lb < 0 || ub < 0)
1435       return op.emitOpError("negative range bound");
1436     if (rangeIsKnownToBeNonempty)
1437       continue;
1438     if (lb > ub)
1439       return op.emitOpError("empty range");
1440     rangeIsKnownToBeNonempty = lb < ub;
1441   }
1442   return mlir::success();
1443 }
1444 
1445 //===----------------------------------------------------------------------===//
1446 // InsertValueOp
1447 //===----------------------------------------------------------------------===//
1448 
1449 void fir::InsertValueOp::build(mlir::OpBuilder &builder, OperationState &result,
1450                                mlir::Type resTy, mlir::Value aggVal,
1451                                mlir::Value eleVal,
1452                                llvm::ArrayRef<mlir::Value> inds) {
1453   auto aa = collectAsAttributes<>(builder.getContext(), result, inds);
1454   build(builder, result, resTy, aggVal, eleVal, aa);
1455 }
1456 
1457 static bool checkIsIntegerConstant(mlir::Attribute attr, int64_t conVal) {
1458   if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>())
1459     return iattr.getInt() == conVal;
1460   return false;
1461 }
1462 static bool isZero(mlir::Attribute a) { return checkIsIntegerConstant(a, 0); }
1463 static bool isOne(mlir::Attribute a) { return checkIsIntegerConstant(a, 1); }
1464 
1465 // Undo some complex patterns created in the front-end and turn them back into
1466 // complex ops.
1467 template <typename FltOp, typename CpxOp>
1468 struct UndoComplexPattern : public mlir::RewritePattern {
1469   UndoComplexPattern(mlir::MLIRContext *ctx)
1470       : mlir::RewritePattern("fir.insert_value", 2, ctx) {}
1471 
1472   mlir::LogicalResult
1473   matchAndRewrite(mlir::Operation *op,
1474                   mlir::PatternRewriter &rewriter) const override {
1475     auto insval = dyn_cast_or_null<fir::InsertValueOp>(op);
1476     if (!insval || !insval.getType().isa<fir::ComplexType>())
1477       return mlir::failure();
1478     auto insval2 =
1479         dyn_cast_or_null<fir::InsertValueOp>(insval.adt().getDefiningOp());
1480     if (!insval2 || !isa<fir::UndefOp>(insval2.adt().getDefiningOp()))
1481       return mlir::failure();
1482     auto binf = dyn_cast_or_null<FltOp>(insval.val().getDefiningOp());
1483     auto binf2 = dyn_cast_or_null<FltOp>(insval2.val().getDefiningOp());
1484     if (!binf || !binf2 || insval.coor().size() != 1 ||
1485         !isOne(insval.coor()[0]) || insval2.coor().size() != 1 ||
1486         !isZero(insval2.coor()[0]))
1487       return mlir::failure();
1488     auto eai =
1489         dyn_cast_or_null<fir::ExtractValueOp>(binf.lhs().getDefiningOp());
1490     auto ebi =
1491         dyn_cast_or_null<fir::ExtractValueOp>(binf.rhs().getDefiningOp());
1492     auto ear =
1493         dyn_cast_or_null<fir::ExtractValueOp>(binf2.lhs().getDefiningOp());
1494     auto ebr =
1495         dyn_cast_or_null<fir::ExtractValueOp>(binf2.rhs().getDefiningOp());
1496     if (!eai || !ebi || !ear || !ebr || ear.adt() != eai.adt() ||
1497         ebr.adt() != ebi.adt() || eai.coor().size() != 1 ||
1498         !isOne(eai.coor()[0]) || ebi.coor().size() != 1 ||
1499         !isOne(ebi.coor()[0]) || ear.coor().size() != 1 ||
1500         !isZero(ear.coor()[0]) || ebr.coor().size() != 1 ||
1501         !isZero(ebr.coor()[0]))
1502       return mlir::failure();
1503     rewriter.replaceOpWithNewOp<CpxOp>(op, ear.adt(), ebr.adt());
1504     return mlir::success();
1505   }
1506 };
1507 
1508 void fir::InsertValueOp::getCanonicalizationPatterns(
1509     mlir::OwningRewritePatternList &results, mlir::MLIRContext *context) {
1510   results.insert<UndoComplexPattern<mlir::arith::AddFOp, fir::AddcOp>,
1511                  UndoComplexPattern<mlir::arith::SubFOp, fir::SubcOp>>(context);
1512 }
1513 
1514 //===----------------------------------------------------------------------===//
1515 // IterWhileOp
1516 //===----------------------------------------------------------------------===//
1517 
1518 void fir::IterWhileOp::build(mlir::OpBuilder &builder,
1519                              mlir::OperationState &result, mlir::Value lb,
1520                              mlir::Value ub, mlir::Value step,
1521                              mlir::Value iterate, bool finalCountValue,
1522                              mlir::ValueRange iterArgs,
1523                              llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1524   result.addOperands({lb, ub, step, iterate});
1525   if (finalCountValue) {
1526     result.addTypes(builder.getIndexType());
1527     result.addAttribute(getFinalValueAttrName(), builder.getUnitAttr());
1528   }
1529   result.addTypes(iterate.getType());
1530   result.addOperands(iterArgs);
1531   for (auto v : iterArgs)
1532     result.addTypes(v.getType());
1533   mlir::Region *bodyRegion = result.addRegion();
1534   bodyRegion->push_back(new Block{});
1535   bodyRegion->front().addArgument(builder.getIndexType());
1536   bodyRegion->front().addArgument(iterate.getType());
1537   bodyRegion->front().addArguments(iterArgs.getTypes());
1538   result.addAttributes(attributes);
1539 }
1540 
1541 static mlir::ParseResult parseIterWhileOp(mlir::OpAsmParser &parser,
1542                                           mlir::OperationState &result) {
1543   auto &builder = parser.getBuilder();
1544   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
1545   if (parser.parseLParen() || parser.parseRegionArgument(inductionVariable) ||
1546       parser.parseEqual())
1547     return mlir::failure();
1548 
1549   // Parse loop bounds.
1550   auto indexType = builder.getIndexType();
1551   auto i1Type = builder.getIntegerType(1);
1552   if (parser.parseOperand(lb) ||
1553       parser.resolveOperand(lb, indexType, result.operands) ||
1554       parser.parseKeyword("to") || parser.parseOperand(ub) ||
1555       parser.resolveOperand(ub, indexType, result.operands) ||
1556       parser.parseKeyword("step") || parser.parseOperand(step) ||
1557       parser.parseRParen() ||
1558       parser.resolveOperand(step, indexType, result.operands))
1559     return mlir::failure();
1560 
1561   mlir::OpAsmParser::OperandType iterateVar, iterateInput;
1562   if (parser.parseKeyword("and") || parser.parseLParen() ||
1563       parser.parseRegionArgument(iterateVar) || parser.parseEqual() ||
1564       parser.parseOperand(iterateInput) || parser.parseRParen() ||
1565       parser.resolveOperand(iterateInput, i1Type, result.operands))
1566     return mlir::failure();
1567 
1568   // Parse the initial iteration arguments.
1569   llvm::SmallVector<mlir::OpAsmParser::OperandType> regionArgs;
1570   auto prependCount = false;
1571 
1572   // Induction variable.
1573   regionArgs.push_back(inductionVariable);
1574   regionArgs.push_back(iterateVar);
1575 
1576   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1577     llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
1578     llvm::SmallVector<mlir::Type> regionTypes;
1579     // Parse assignment list and results type list.
1580     if (parser.parseAssignmentList(regionArgs, operands) ||
1581         parser.parseArrowTypeList(regionTypes))
1582       return failure();
1583     if (regionTypes.size() == operands.size() + 2)
1584       prependCount = true;
1585     llvm::ArrayRef<mlir::Type> resTypes = regionTypes;
1586     resTypes = prependCount ? resTypes.drop_front(2) : resTypes;
1587     // Resolve input operands.
1588     for (auto operandType : llvm::zip(operands, resTypes))
1589       if (parser.resolveOperand(std::get<0>(operandType),
1590                                 std::get<1>(operandType), result.operands))
1591         return failure();
1592     if (prependCount) {
1593       result.addTypes(regionTypes);
1594     } else {
1595       result.addTypes(i1Type);
1596       result.addTypes(resTypes);
1597     }
1598   } else if (succeeded(parser.parseOptionalArrow())) {
1599     llvm::SmallVector<mlir::Type> typeList;
1600     if (parser.parseLParen() || parser.parseTypeList(typeList) ||
1601         parser.parseRParen())
1602       return failure();
1603     // Type list must be "(index, i1)".
1604     if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() ||
1605         !typeList[1].isSignlessInteger(1))
1606       return failure();
1607     result.addTypes(typeList);
1608     prependCount = true;
1609   } else {
1610     result.addTypes(i1Type);
1611   }
1612 
1613   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1614     return mlir::failure();
1615 
1616   llvm::SmallVector<mlir::Type> argTypes;
1617   // Induction variable (hidden)
1618   if (prependCount)
1619     result.addAttribute(IterWhileOp::getFinalValueAttrName(),
1620                         builder.getUnitAttr());
1621   else
1622     argTypes.push_back(indexType);
1623   // Loop carried variables (including iterate)
1624   argTypes.append(result.types.begin(), result.types.end());
1625   // Parse the body region.
1626   auto *body = result.addRegion();
1627   if (regionArgs.size() != argTypes.size())
1628     return parser.emitError(
1629         parser.getNameLoc(),
1630         "mismatch in number of loop-carried values and defined values");
1631 
1632   if (parser.parseRegion(*body, regionArgs, argTypes))
1633     return failure();
1634 
1635   fir::IterWhileOp::ensureTerminator(*body, builder, result.location);
1636 
1637   return mlir::success();
1638 }
1639 
1640 static mlir::LogicalResult verify(fir::IterWhileOp op) {
1641   // Check that the body defines as single block argument for the induction
1642   // variable.
1643   auto *body = op.getBody();
1644   if (!body->getArgument(1).getType().isInteger(1))
1645     return op.emitOpError(
1646         "expected body second argument to be an index argument for "
1647         "the induction variable");
1648   if (!body->getArgument(0).getType().isIndex())
1649     return op.emitOpError(
1650         "expected body first argument to be an index argument for "
1651         "the induction variable");
1652 
1653   auto opNumResults = op.getNumResults();
1654   if (op.finalValue()) {
1655     // Result type must be "(index, i1, ...)".
1656     if (!op.getResult(0).getType().isa<mlir::IndexType>())
1657       return op.emitOpError("result #0 expected to be index");
1658     if (!op.getResult(1).getType().isSignlessInteger(1))
1659       return op.emitOpError("result #1 expected to be i1");
1660     opNumResults--;
1661   } else {
1662     // iterate_while always returns the early exit induction value.
1663     // Result type must be "(i1, ...)"
1664     if (!op.getResult(0).getType().isSignlessInteger(1))
1665       return op.emitOpError("result #0 expected to be i1");
1666   }
1667   if (opNumResults == 0)
1668     return mlir::failure();
1669   if (op.getNumIterOperands() != opNumResults)
1670     return op.emitOpError(
1671         "mismatch in number of loop-carried values and defined values");
1672   if (op.getNumRegionIterArgs() != opNumResults)
1673     return op.emitOpError(
1674         "mismatch in number of basic block args and defined values");
1675   auto iterOperands = op.getIterOperands();
1676   auto iterArgs = op.getRegionIterArgs();
1677   auto opResults =
1678       op.finalValue() ? op.getResults().drop_front() : op.getResults();
1679   unsigned i = 0;
1680   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
1681     if (std::get<0>(e).getType() != std::get<2>(e).getType())
1682       return op.emitOpError() << "types mismatch between " << i
1683                               << "th iter operand and defined value";
1684     if (std::get<1>(e).getType() != std::get<2>(e).getType())
1685       return op.emitOpError() << "types mismatch between " << i
1686                               << "th iter region arg and defined value";
1687 
1688     i++;
1689   }
1690   return mlir::success();
1691 }
1692 
1693 static void print(mlir::OpAsmPrinter &p, fir::IterWhileOp op) {
1694   p << " (" << op.getInductionVar() << " = " << op.lowerBound() << " to "
1695     << op.upperBound() << " step " << op.step() << ") and (";
1696   assert(op.hasIterOperands());
1697   auto regionArgs = op.getRegionIterArgs();
1698   auto operands = op.getIterOperands();
1699   p << regionArgs.front() << " = " << *operands.begin() << ")";
1700   if (regionArgs.size() > 1) {
1701     p << " iter_args(";
1702     llvm::interleaveComma(
1703         llvm::zip(regionArgs.drop_front(), operands.drop_front()), p,
1704         [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); });
1705     p << ") -> (";
1706     llvm::interleaveComma(
1707         llvm::drop_begin(op.getResultTypes(), op.finalValue() ? 0 : 1), p);
1708     p << ")";
1709   } else if (op.finalValue()) {
1710     p << " -> (" << op.getResultTypes() << ')';
1711   }
1712   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
1713                                      {IterWhileOp::getFinalValueAttrName()});
1714   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
1715                 /*printBlockTerminators=*/true);
1716 }
1717 
1718 mlir::Region &fir::IterWhileOp::getLoopBody() { return region(); }
1719 
1720 bool fir::IterWhileOp::isDefinedOutsideOfLoop(mlir::Value value) {
1721   return !region().isAncestor(value.getParentRegion());
1722 }
1723 
1724 mlir::LogicalResult
1725 fir::IterWhileOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
1726   for (auto *op : ops)
1727     op->moveBefore(*this);
1728   return success();
1729 }
1730 
1731 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) {
1732   for (auto i : llvm::enumerate(initArgs()))
1733     if (iterArg == i.value())
1734       return region().front().getArgument(i.index() + 1);
1735   return {};
1736 }
1737 
1738 void fir::IterWhileOp::resultToSourceOps(
1739     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
1740   auto oper = finalValue() ? resultNum + 1 : resultNum;
1741   auto *term = region().front().getTerminator();
1742   if (oper < term->getNumOperands())
1743     results.push_back(term->getOperand(oper));
1744 }
1745 
1746 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) {
1747   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
1748     return initArgs()[blockArgNum - 1];
1749   return {};
1750 }
1751 
1752 //===----------------------------------------------------------------------===//
1753 // LenParamIndexOp
1754 //===----------------------------------------------------------------------===//
1755 
1756 static mlir::ParseResult parseLenParamIndexOp(mlir::OpAsmParser &parser,
1757                                               mlir::OperationState &result) {
1758   llvm::StringRef fieldName;
1759   auto &builder = parser.getBuilder();
1760   mlir::Type recty;
1761   if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() ||
1762       parser.parseType(recty))
1763     return mlir::failure();
1764   result.addAttribute(fir::LenParamIndexOp::fieldAttrName(),
1765                       builder.getStringAttr(fieldName));
1766   if (!recty.dyn_cast<RecordType>())
1767     return mlir::failure();
1768   result.addAttribute(fir::LenParamIndexOp::typeAttrName(),
1769                       mlir::TypeAttr::get(recty));
1770   mlir::Type lenType = fir::LenType::get(builder.getContext());
1771   if (parser.addTypeToList(lenType, result.types))
1772     return mlir::failure();
1773   return mlir::success();
1774 }
1775 
1776 static void print(mlir::OpAsmPrinter &p, fir::LenParamIndexOp &op) {
1777   p << ' '
1778     << op.getOperation()
1779            ->getAttrOfType<mlir::StringAttr>(
1780                fir::LenParamIndexOp::fieldAttrName())
1781            .getValue()
1782     << ", " << op.getOperation()->getAttr(fir::LenParamIndexOp::typeAttrName());
1783 }
1784 
1785 //===----------------------------------------------------------------------===//
1786 // LoadOp
1787 //===----------------------------------------------------------------------===//
1788 
1789 void fir::LoadOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
1790                         mlir::Value refVal) {
1791   if (!refVal) {
1792     mlir::emitError(result.location, "LoadOp has null argument");
1793     return;
1794   }
1795   auto eleTy = fir::dyn_cast_ptrEleTy(refVal.getType());
1796   if (!eleTy) {
1797     mlir::emitError(result.location, "not a memory reference type");
1798     return;
1799   }
1800   result.addOperands(refVal);
1801   result.addTypes(eleTy);
1802 }
1803 
1804 /// Get the element type of a reference like type; otherwise null
1805 static mlir::Type elementTypeOf(mlir::Type ref) {
1806   return llvm::TypeSwitch<mlir::Type, mlir::Type>(ref)
1807       .Case<ReferenceType, PointerType, HeapType>(
1808           [](auto type) { return type.getEleTy(); })
1809       .Default([](mlir::Type) { return mlir::Type{}; });
1810 }
1811 
1812 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) {
1813   if ((ele = elementTypeOf(ref)))
1814     return mlir::success();
1815   return mlir::failure();
1816 }
1817 
1818 static mlir::ParseResult parseLoadOp(mlir::OpAsmParser &parser,
1819                                      mlir::OperationState &result) {
1820   mlir::Type type;
1821   mlir::OpAsmParser::OperandType oper;
1822   if (parser.parseOperand(oper) ||
1823       parser.parseOptionalAttrDict(result.attributes) ||
1824       parser.parseColonType(type) ||
1825       parser.resolveOperand(oper, type, result.operands))
1826     return mlir::failure();
1827   mlir::Type eleTy;
1828   if (fir::LoadOp::getElementOf(eleTy, type) ||
1829       parser.addTypeToList(eleTy, result.types))
1830     return mlir::failure();
1831   return mlir::success();
1832 }
1833 
1834 static void print(mlir::OpAsmPrinter &p, fir::LoadOp &op) {
1835   p << ' ';
1836   p.printOperand(op.memref());
1837   p.printOptionalAttrDict(op.getOperation()->getAttrs(), {});
1838   p << " : " << op.memref().getType();
1839 }
1840 
1841 //===----------------------------------------------------------------------===//
1842 // DoLoopOp
1843 //===----------------------------------------------------------------------===//
1844 
1845 void fir::DoLoopOp::build(mlir::OpBuilder &builder,
1846                           mlir::OperationState &result, mlir::Value lb,
1847                           mlir::Value ub, mlir::Value step, bool unordered,
1848                           bool finalCountValue, mlir::ValueRange iterArgs,
1849                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1850   result.addOperands({lb, ub, step});
1851   result.addOperands(iterArgs);
1852   if (finalCountValue) {
1853     result.addTypes(builder.getIndexType());
1854     result.addAttribute(finalValueAttrName(result.name), builder.getUnitAttr());
1855   }
1856   for (auto v : iterArgs)
1857     result.addTypes(v.getType());
1858   mlir::Region *bodyRegion = result.addRegion();
1859   bodyRegion->push_back(new Block{});
1860   if (iterArgs.empty() && !finalCountValue)
1861     DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
1862   bodyRegion->front().addArgument(builder.getIndexType());
1863   bodyRegion->front().addArguments(iterArgs.getTypes());
1864   if (unordered)
1865     result.addAttribute(unorderedAttrName(result.name), builder.getUnitAttr());
1866   result.addAttributes(attributes);
1867 }
1868 
1869 static mlir::ParseResult parseDoLoopOp(mlir::OpAsmParser &parser,
1870                                        mlir::OperationState &result) {
1871   auto &builder = parser.getBuilder();
1872   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
1873   // Parse the induction variable followed by '='.
1874   if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual())
1875     return mlir::failure();
1876 
1877   // Parse loop bounds.
1878   auto indexType = builder.getIndexType();
1879   if (parser.parseOperand(lb) ||
1880       parser.resolveOperand(lb, indexType, result.operands) ||
1881       parser.parseKeyword("to") || parser.parseOperand(ub) ||
1882       parser.resolveOperand(ub, indexType, result.operands) ||
1883       parser.parseKeyword("step") || parser.parseOperand(step) ||
1884       parser.resolveOperand(step, indexType, result.operands))
1885     return failure();
1886 
1887   if (mlir::succeeded(parser.parseOptionalKeyword("unordered")))
1888     result.addAttribute("unordered", builder.getUnitAttr());
1889 
1890   // Parse the optional initial iteration arguments.
1891   llvm::SmallVector<mlir::OpAsmParser::OperandType> regionArgs, operands;
1892   llvm::SmallVector<mlir::Type> argTypes;
1893   auto prependCount = false;
1894   regionArgs.push_back(inductionVariable);
1895 
1896   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1897     // Parse assignment list and results type list.
1898     if (parser.parseAssignmentList(regionArgs, operands) ||
1899         parser.parseArrowTypeList(result.types))
1900       return failure();
1901     if (result.types.size() == operands.size() + 1)
1902       prependCount = true;
1903     // Resolve input operands.
1904     llvm::ArrayRef<mlir::Type> resTypes = result.types;
1905     for (auto operand_type :
1906          llvm::zip(operands, prependCount ? resTypes.drop_front() : resTypes))
1907       if (parser.resolveOperand(std::get<0>(operand_type),
1908                                 std::get<1>(operand_type), result.operands))
1909         return failure();
1910   } else if (succeeded(parser.parseOptionalArrow())) {
1911     if (parser.parseKeyword("index"))
1912       return failure();
1913     result.types.push_back(indexType);
1914     prependCount = true;
1915   }
1916 
1917   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1918     return mlir::failure();
1919 
1920   // Induction variable.
1921   if (prependCount)
1922     result.addAttribute(DoLoopOp::finalValueAttrName(result.name),
1923                         builder.getUnitAttr());
1924   else
1925     argTypes.push_back(indexType);
1926   // Loop carried variables
1927   argTypes.append(result.types.begin(), result.types.end());
1928   // Parse the body region.
1929   auto *body = result.addRegion();
1930   if (regionArgs.size() != argTypes.size())
1931     return parser.emitError(
1932         parser.getNameLoc(),
1933         "mismatch in number of loop-carried values and defined values");
1934 
1935   if (parser.parseRegion(*body, regionArgs, argTypes))
1936     return failure();
1937 
1938   DoLoopOp::ensureTerminator(*body, builder, result.location);
1939 
1940   return mlir::success();
1941 }
1942 
1943 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) {
1944   auto ivArg = val.dyn_cast<mlir::BlockArgument>();
1945   if (!ivArg)
1946     return {};
1947   assert(ivArg.getOwner() && "unlinked block argument");
1948   auto *containingInst = ivArg.getOwner()->getParentOp();
1949   return dyn_cast_or_null<fir::DoLoopOp>(containingInst);
1950 }
1951 
1952 // Lifted from loop.loop
1953 static mlir::LogicalResult verify(fir::DoLoopOp op) {
1954   // Check that the body defines as single block argument for the induction
1955   // variable.
1956   auto *body = op.getBody();
1957   if (!body->getArgument(0).getType().isIndex())
1958     return op.emitOpError(
1959         "expected body first argument to be an index argument for "
1960         "the induction variable");
1961 
1962   auto opNumResults = op.getNumResults();
1963   if (opNumResults == 0)
1964     return success();
1965 
1966   if (op.finalValue()) {
1967     if (op.unordered())
1968       return op.emitOpError("unordered loop has no final value");
1969     opNumResults--;
1970   }
1971   if (op.getNumIterOperands() != opNumResults)
1972     return op.emitOpError(
1973         "mismatch in number of loop-carried values and defined values");
1974   if (op.getNumRegionIterArgs() != opNumResults)
1975     return op.emitOpError(
1976         "mismatch in number of basic block args and defined values");
1977   auto iterOperands = op.getIterOperands();
1978   auto iterArgs = op.getRegionIterArgs();
1979   auto opResults =
1980       op.finalValue() ? op.getResults().drop_front() : op.getResults();
1981   unsigned i = 0;
1982   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
1983     if (std::get<0>(e).getType() != std::get<2>(e).getType())
1984       return op.emitOpError() << "types mismatch between " << i
1985                               << "th iter operand and defined value";
1986     if (std::get<1>(e).getType() != std::get<2>(e).getType())
1987       return op.emitOpError() << "types mismatch between " << i
1988                               << "th iter region arg and defined value";
1989 
1990     i++;
1991   }
1992   return success();
1993 }
1994 
1995 static void print(mlir::OpAsmPrinter &p, fir::DoLoopOp op) {
1996   bool printBlockTerminators = false;
1997   p << ' ' << op.getInductionVar() << " = " << op.lowerBound() << " to "
1998     << op.upperBound() << " step " << op.step();
1999   if (op.unordered())
2000     p << " unordered";
2001   if (op.hasIterOperands()) {
2002     p << " iter_args(";
2003     auto regionArgs = op.getRegionIterArgs();
2004     auto operands = op.getIterOperands();
2005     llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
2006       p << std::get<0>(it) << " = " << std::get<1>(it);
2007     });
2008     p << ") -> (" << op.getResultTypes() << ')';
2009     printBlockTerminators = true;
2010   } else if (op.finalValue()) {
2011     p << " -> " << op.getResultTypes();
2012     printBlockTerminators = true;
2013   }
2014   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
2015                                      {"unordered", "finalValue"});
2016   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
2017                 printBlockTerminators);
2018 }
2019 
2020 mlir::Region &fir::DoLoopOp::getLoopBody() { return region(); }
2021 
2022 bool fir::DoLoopOp::isDefinedOutsideOfLoop(mlir::Value value) {
2023   return !region().isAncestor(value.getParentRegion());
2024 }
2025 
2026 mlir::LogicalResult
2027 fir::DoLoopOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
2028   for (auto op : ops)
2029     op->moveBefore(*this);
2030   return success();
2031 }
2032 
2033 /// Translate a value passed as an iter_arg to the corresponding block
2034 /// argument in the body of the loop.
2035 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) {
2036   for (auto i : llvm::enumerate(initArgs()))
2037     if (iterArg == i.value())
2038       return region().front().getArgument(i.index() + 1);
2039   return {};
2040 }
2041 
2042 /// Translate the result vector (by index number) to the corresponding value
2043 /// to the `fir.result` Op.
2044 void fir::DoLoopOp::resultToSourceOps(
2045     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
2046   auto oper = finalValue() ? resultNum + 1 : resultNum;
2047   auto *term = region().front().getTerminator();
2048   if (oper < term->getNumOperands())
2049     results.push_back(term->getOperand(oper));
2050 }
2051 
2052 /// Translate the block argument (by index number) to the corresponding value
2053 /// passed as an iter_arg to the parent DoLoopOp.
2054 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) {
2055   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
2056     return initArgs()[blockArgNum - 1];
2057   return {};
2058 }
2059 
2060 //===----------------------------------------------------------------------===//
2061 // DTEntryOp
2062 //===----------------------------------------------------------------------===//
2063 
2064 static mlir::ParseResult parseDTEntryOp(mlir::OpAsmParser &parser,
2065                                         mlir::OperationState &result) {
2066   llvm::StringRef methodName;
2067   // allow `methodName` or `"methodName"`
2068   if (failed(parser.parseOptionalKeyword(&methodName))) {
2069     mlir::StringAttr methodAttr;
2070     if (parser.parseAttribute(methodAttr, fir::DTEntryOp::getMethodAttrName(),
2071                               result.attributes))
2072       return mlir::failure();
2073   } else {
2074     result.addAttribute(fir::DTEntryOp::getMethodAttrName(),
2075                         parser.getBuilder().getStringAttr(methodName));
2076   }
2077   mlir::SymbolRefAttr calleeAttr;
2078   if (parser.parseComma() ||
2079       parser.parseAttribute(calleeAttr, fir::DTEntryOp::getProcAttrName(),
2080                             result.attributes))
2081     return mlir::failure();
2082   return mlir::success();
2083 }
2084 
2085 static void print(mlir::OpAsmPrinter &p, fir::DTEntryOp &op) {
2086   p << ' ' << op.getOperation()->getAttr(fir::DTEntryOp::getMethodAttrName())
2087     << ", " << op.getOperation()->getAttr(fir::DTEntryOp::getProcAttrName());
2088 }
2089 
2090 //===----------------------------------------------------------------------===//
2091 // ReboxOp
2092 //===----------------------------------------------------------------------===//
2093 
2094 /// Get the scalar type related to a fir.box type.
2095 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>.
2096 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
2097   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
2098   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
2099     return seqTy.getEleTy();
2100   return eleTy;
2101 }
2102 
2103 /// Get the rank from a !fir.box type
2104 static unsigned getBoxRank(mlir::Type boxTy) {
2105   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
2106   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
2107     return seqTy.getDimension();
2108   return 0;
2109 }
2110 
2111 static mlir::LogicalResult verify(fir::ReboxOp op) {
2112   auto inputBoxTy = op.box().getType();
2113   if (fir::isa_unknown_size_box(inputBoxTy))
2114     return op.emitOpError("box operand must not have unknown rank or type");
2115   auto outBoxTy = op.getType();
2116   if (fir::isa_unknown_size_box(outBoxTy))
2117     return op.emitOpError("result type must not have unknown rank or type");
2118   auto inputRank = getBoxRank(inputBoxTy);
2119   auto inputEleTy = getBoxScalarEleTy(inputBoxTy);
2120   auto outRank = getBoxRank(outBoxTy);
2121   auto outEleTy = getBoxScalarEleTy(outBoxTy);
2122 
2123   if (auto slice = op.slice()) {
2124     // Slicing case
2125     if (slice.getType().cast<fir::SliceType>().getRank() != inputRank)
2126       return op.emitOpError("slice operand rank must match box operand rank");
2127     if (auto shape = op.shape()) {
2128       if (auto shiftTy = shape.getType().dyn_cast<fir::ShiftType>()) {
2129         if (shiftTy.getRank() != inputRank)
2130           return op.emitOpError("shape operand and input box ranks must match "
2131                                 "when there is a slice");
2132       } else {
2133         return op.emitOpError("shape operand must absent or be a fir.shift "
2134                               "when there is a slice");
2135       }
2136     }
2137     if (auto sliceOp = slice.getDefiningOp()) {
2138       auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank();
2139       if (slicedRank != outRank)
2140         return op.emitOpError("result type rank and rank after applying slice "
2141                               "operand must match");
2142     }
2143   } else {
2144     // Reshaping case
2145     unsigned shapeRank = inputRank;
2146     if (auto shape = op.shape()) {
2147       auto ty = shape.getType();
2148       if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) {
2149         shapeRank = shapeTy.getRank();
2150       } else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) {
2151         shapeRank = shapeShiftTy.getRank();
2152       } else {
2153         auto shiftTy = ty.cast<fir::ShiftType>();
2154         shapeRank = shiftTy.getRank();
2155         if (shapeRank != inputRank)
2156           return op.emitOpError("shape operand and input box ranks must match "
2157                                 "when the shape is a fir.shift");
2158       }
2159     }
2160     if (shapeRank != outRank)
2161       return op.emitOpError("result type and shape operand ranks must match");
2162   }
2163 
2164   if (inputEleTy != outEleTy)
2165     // TODO: check that outBoxTy is a parent type of inputBoxTy for derived
2166     // types.
2167     if (!inputEleTy.isa<fir::RecordType>())
2168       return op.emitOpError(
2169           "op input and output element types must match for intrinsic types");
2170   return mlir::success();
2171 }
2172 
2173 //===----------------------------------------------------------------------===//
2174 // ResultOp
2175 //===----------------------------------------------------------------------===//
2176 
2177 static mlir::LogicalResult verify(fir::ResultOp op) {
2178   auto *parentOp = op->getParentOp();
2179   auto results = parentOp->getResults();
2180   auto operands = op->getOperands();
2181 
2182   if (parentOp->getNumResults() != op.getNumOperands())
2183     return op.emitOpError() << "parent of result must have same arity";
2184   for (auto e : llvm::zip(results, operands))
2185     if (std::get<0>(e).getType() != std::get<1>(e).getType())
2186       return op.emitOpError()
2187              << "types mismatch between result op and its parent";
2188   return success();
2189 }
2190 
2191 //===----------------------------------------------------------------------===//
2192 // SaveResultOp
2193 //===----------------------------------------------------------------------===//
2194 
2195 static mlir::LogicalResult verify(fir::SaveResultOp op) {
2196   auto resultType = op.value().getType();
2197   if (resultType != fir::dyn_cast_ptrEleTy(op.memref().getType()))
2198     return op.emitOpError("value type must match memory reference type");
2199   if (fir::isa_unknown_size_box(resultType))
2200     return op.emitOpError("cannot save !fir.box of unknown rank or type");
2201 
2202   if (resultType.isa<fir::BoxType>()) {
2203     if (op.shape() || !op.typeparams().empty())
2204       return op.emitOpError(
2205           "must not have shape or length operands if the value is a fir.box");
2206     return mlir::success();
2207   }
2208 
2209   // fir.record or fir.array case.
2210   unsigned shapeTyRank = 0;
2211   if (auto shapeOp = op.shape()) {
2212     auto shapeTy = shapeOp.getType();
2213     if (auto s = shapeTy.dyn_cast<fir::ShapeType>())
2214       shapeTyRank = s.getRank();
2215     else
2216       shapeTyRank = shapeTy.cast<fir::ShapeShiftType>().getRank();
2217   }
2218 
2219   auto eleTy = resultType;
2220   if (auto seqTy = resultType.dyn_cast<fir::SequenceType>()) {
2221     if (seqTy.getDimension() != shapeTyRank)
2222       op.emitOpError("shape operand must be provided and have the value rank "
2223                      "when the value is a fir.array");
2224     eleTy = seqTy.getEleTy();
2225   } else {
2226     if (shapeTyRank != 0)
2227       op.emitOpError(
2228           "shape operand should only be provided if the value is a fir.array");
2229   }
2230 
2231   if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) {
2232     if (recTy.getNumLenParams() != op.typeparams().size())
2233       op.emitOpError("length parameters number must match with the value type "
2234                      "length parameters");
2235   } else if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
2236     if (op.typeparams().size() > 1)
2237       op.emitOpError("no more than one length parameter must be provided for "
2238                      "character value");
2239   } else {
2240     if (!op.typeparams().empty())
2241       op.emitOpError(
2242           "length parameters must not be provided for this value type");
2243   }
2244 
2245   return mlir::success();
2246 }
2247 
2248 //===----------------------------------------------------------------------===//
2249 // SelectOp
2250 //===----------------------------------------------------------------------===//
2251 
2252 static constexpr llvm::StringRef getCompareOffsetAttr() {
2253   return "compare_operand_offsets";
2254 }
2255 
2256 static constexpr llvm::StringRef getTargetOffsetAttr() {
2257   return "target_operand_offsets";
2258 }
2259 
2260 template <typename A, typename... AdditionalArgs>
2261 static A getSubOperands(unsigned pos, A allArgs,
2262                         mlir::DenseIntElementsAttr ranges,
2263                         AdditionalArgs &&...additionalArgs) {
2264   unsigned start = 0;
2265   for (unsigned i = 0; i < pos; ++i)
2266     start += (*(ranges.begin() + i)).getZExtValue();
2267   return allArgs.slice(start, (*(ranges.begin() + pos)).getZExtValue(),
2268                        std::forward<AdditionalArgs>(additionalArgs)...);
2269 }
2270 
2271 static mlir::MutableOperandRange
2272 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands,
2273                             StringRef offsetAttr) {
2274   Operation *owner = operands.getOwner();
2275   NamedAttribute targetOffsetAttr =
2276       *owner->getAttrDictionary().getNamed(offsetAttr);
2277   return getSubOperands(
2278       pos, operands, targetOffsetAttr.second.cast<DenseIntElementsAttr>(),
2279       mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr));
2280 }
2281 
2282 static unsigned denseElementsSize(mlir::DenseIntElementsAttr attr) {
2283   return attr.getNumElements();
2284 }
2285 
2286 llvm::Optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) {
2287   return {};
2288 }
2289 
2290 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2291 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
2292   return {};
2293 }
2294 
2295 llvm::Optional<mlir::MutableOperandRange>
2296 fir::SelectOp::getMutableSuccessorOperands(unsigned oper) {
2297   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2298                                        getTargetOffsetAttr());
2299 }
2300 
2301 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2302 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2303                                     unsigned oper) {
2304   auto a =
2305       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2306   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2307       getOperandSegmentSizeAttr());
2308   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2309 }
2310 
2311 unsigned fir::SelectOp::targetOffsetSize() {
2312   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2313       getTargetOffsetAttr()));
2314 }
2315 
2316 //===----------------------------------------------------------------------===//
2317 // SelectCaseOp
2318 //===----------------------------------------------------------------------===//
2319 
2320 llvm::Optional<mlir::OperandRange>
2321 fir::SelectCaseOp::getCompareOperands(unsigned cond) {
2322   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2323       getCompareOffsetAttr());
2324   return {getSubOperands(cond, compareArgs(), a)};
2325 }
2326 
2327 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2328 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands,
2329                                       unsigned cond) {
2330   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2331       getCompareOffsetAttr());
2332   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2333       getOperandSegmentSizeAttr());
2334   return {getSubOperands(cond, getSubOperands(1, operands, segments), a)};
2335 }
2336 
2337 llvm::Optional<mlir::MutableOperandRange>
2338 fir::SelectCaseOp::getMutableSuccessorOperands(unsigned oper) {
2339   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2340                                        getTargetOffsetAttr());
2341 }
2342 
2343 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2344 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2345                                         unsigned oper) {
2346   auto a =
2347       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2348   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2349       getOperandSegmentSizeAttr());
2350   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2351 }
2352 
2353 // parser for fir.select_case Op
2354 static mlir::ParseResult parseSelectCase(mlir::OpAsmParser &parser,
2355                                          mlir::OperationState &result) {
2356   mlir::OpAsmParser::OperandType selector;
2357   mlir::Type type;
2358   if (parseSelector(parser, result, selector, type))
2359     return mlir::failure();
2360 
2361   llvm::SmallVector<mlir::Attribute> attrs;
2362   llvm::SmallVector<mlir::OpAsmParser::OperandType> opers;
2363   llvm::SmallVector<mlir::Block *> dests;
2364   llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
2365   llvm::SmallVector<int32_t> argOffs;
2366   int32_t offSize = 0;
2367   while (true) {
2368     mlir::Attribute attr;
2369     mlir::Block *dest;
2370     llvm::SmallVector<mlir::Value> destArg;
2371     mlir::NamedAttrList temp;
2372     if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) ||
2373         parser.parseComma())
2374       return mlir::failure();
2375     attrs.push_back(attr);
2376     if (attr.dyn_cast_or_null<mlir::UnitAttr>()) {
2377       argOffs.push_back(0);
2378     } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) {
2379       mlir::OpAsmParser::OperandType oper1;
2380       mlir::OpAsmParser::OperandType oper2;
2381       if (parser.parseOperand(oper1) || parser.parseComma() ||
2382           parser.parseOperand(oper2) || parser.parseComma())
2383         return mlir::failure();
2384       opers.push_back(oper1);
2385       opers.push_back(oper2);
2386       argOffs.push_back(2);
2387       offSize += 2;
2388     } else {
2389       mlir::OpAsmParser::OperandType oper;
2390       if (parser.parseOperand(oper) || parser.parseComma())
2391         return mlir::failure();
2392       opers.push_back(oper);
2393       argOffs.push_back(1);
2394       ++offSize;
2395     }
2396     if (parser.parseSuccessorAndUseList(dest, destArg))
2397       return mlir::failure();
2398     dests.push_back(dest);
2399     destArgs.push_back(destArg);
2400     if (mlir::succeeded(parser.parseOptionalRSquare()))
2401       break;
2402     if (parser.parseComma())
2403       return mlir::failure();
2404   }
2405   result.addAttribute(fir::SelectCaseOp::getCasesAttr(),
2406                       parser.getBuilder().getArrayAttr(attrs));
2407   if (parser.resolveOperands(opers, type, result.operands))
2408     return mlir::failure();
2409   llvm::SmallVector<int32_t> targOffs;
2410   int32_t toffSize = 0;
2411   const auto count = dests.size();
2412   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2413     result.addSuccessors(dests[i]);
2414     result.addOperands(destArgs[i]);
2415     auto argSize = destArgs[i].size();
2416     targOffs.push_back(argSize);
2417     toffSize += argSize;
2418   }
2419   auto &bld = parser.getBuilder();
2420   result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(),
2421                       bld.getI32VectorAttr({1, offSize, toffSize}));
2422   result.addAttribute(getCompareOffsetAttr(), bld.getI32VectorAttr(argOffs));
2423   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(targOffs));
2424   return mlir::success();
2425 }
2426 
2427 static void print(mlir::OpAsmPrinter &p, fir::SelectCaseOp &op) {
2428   p << ' ';
2429   p.printOperand(op.getSelector());
2430   p << " : " << op.getSelector().getType() << " [";
2431   auto cases = op.getOperation()
2432                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2433                    .getValue();
2434   auto count = op.getNumConditions();
2435   for (decltype(count) i = 0; i != count; ++i) {
2436     if (i)
2437       p << ", ";
2438     p << cases[i] << ", ";
2439     if (!cases[i].isa<mlir::UnitAttr>()) {
2440       auto caseArgs = *op.getCompareOperands(i);
2441       p.printOperand(*caseArgs.begin());
2442       p << ", ";
2443       if (cases[i].isa<fir::ClosedIntervalAttr>()) {
2444         p.printOperand(*(++caseArgs.begin()));
2445         p << ", ";
2446       }
2447     }
2448     op.printSuccessorAtIndex(p, i);
2449   }
2450   p << ']';
2451   p.printOptionalAttrDict(op.getOperation()->getAttrs(),
2452                           {op.getCasesAttr(), getCompareOffsetAttr(),
2453                            getTargetOffsetAttr(),
2454                            op.getOperandSegmentSizeAttr()});
2455 }
2456 
2457 unsigned fir::SelectCaseOp::compareOffsetSize() {
2458   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2459       getCompareOffsetAttr()));
2460 }
2461 
2462 unsigned fir::SelectCaseOp::targetOffsetSize() {
2463   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2464       getTargetOffsetAttr()));
2465 }
2466 
2467 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
2468                               mlir::OperationState &result,
2469                               mlir::Value selector,
2470                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
2471                               llvm::ArrayRef<mlir::ValueRange> cmpOperands,
2472                               llvm::ArrayRef<mlir::Block *> destinations,
2473                               llvm::ArrayRef<mlir::ValueRange> destOperands,
2474                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2475   result.addOperands(selector);
2476   result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs));
2477   llvm::SmallVector<int32_t> operOffs;
2478   int32_t operSize = 0;
2479   for (auto attr : compareAttrs) {
2480     if (attr.isa<fir::ClosedIntervalAttr>()) {
2481       operOffs.push_back(2);
2482       operSize += 2;
2483     } else if (attr.isa<mlir::UnitAttr>()) {
2484       operOffs.push_back(0);
2485     } else {
2486       operOffs.push_back(1);
2487       ++operSize;
2488     }
2489   }
2490   for (auto ops : cmpOperands)
2491     result.addOperands(ops);
2492   result.addAttribute(getCompareOffsetAttr(),
2493                       builder.getI32VectorAttr(operOffs));
2494   const auto count = destinations.size();
2495   for (auto d : destinations)
2496     result.addSuccessors(d);
2497   const auto opCount = destOperands.size();
2498   llvm::SmallVector<int32_t> argOffs;
2499   int32_t sumArgs = 0;
2500   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2501     if (i < opCount) {
2502       result.addOperands(destOperands[i]);
2503       const auto argSz = destOperands[i].size();
2504       argOffs.push_back(argSz);
2505       sumArgs += argSz;
2506     } else {
2507       argOffs.push_back(0);
2508     }
2509   }
2510   result.addAttribute(getOperandSegmentSizeAttr(),
2511                       builder.getI32VectorAttr({1, operSize, sumArgs}));
2512   result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
2513   result.addAttributes(attributes);
2514 }
2515 
2516 /// This builder has a slightly simplified interface in that the list of
2517 /// operands need not be partitioned by the builder. Instead the operands are
2518 /// partitioned here, before being passed to the default builder. This
2519 /// partitioning is unchecked, so can go awry on bad input.
2520 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
2521                               mlir::OperationState &result,
2522                               mlir::Value selector,
2523                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
2524                               llvm::ArrayRef<mlir::Value> cmpOpList,
2525                               llvm::ArrayRef<mlir::Block *> destinations,
2526                               llvm::ArrayRef<mlir::ValueRange> destOperands,
2527                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2528   llvm::SmallVector<mlir::ValueRange> cmpOpers;
2529   auto iter = cmpOpList.begin();
2530   for (auto &attr : compareAttrs) {
2531     if (attr.isa<fir::ClosedIntervalAttr>()) {
2532       cmpOpers.push_back(mlir::ValueRange({iter, iter + 2}));
2533       iter += 2;
2534     } else if (attr.isa<UnitAttr>()) {
2535       cmpOpers.push_back(mlir::ValueRange{});
2536     } else {
2537       cmpOpers.push_back(mlir::ValueRange({iter, iter + 1}));
2538       ++iter;
2539     }
2540   }
2541   build(builder, result, selector, compareAttrs, cmpOpers, destinations,
2542         destOperands, attributes);
2543 }
2544 
2545 static mlir::LogicalResult verify(fir::SelectCaseOp &op) {
2546   if (!(op.getSelector().getType().isa<mlir::IntegerType>() ||
2547         op.getSelector().getType().isa<mlir::IndexType>() ||
2548         op.getSelector().getType().isa<fir::IntegerType>() ||
2549         op.getSelector().getType().isa<fir::LogicalType>() ||
2550         op.getSelector().getType().isa<fir::CharacterType>()))
2551     return op.emitOpError("must be an integer, character, or logical");
2552   auto cases = op.getOperation()
2553                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2554                    .getValue();
2555   auto count = op.getNumDest();
2556   if (count == 0)
2557     return op.emitOpError("must have at least one successor");
2558   if (op.getNumConditions() != count)
2559     return op.emitOpError("number of conditions and successors don't match");
2560   if (op.compareOffsetSize() != count)
2561     return op.emitOpError("incorrect number of compare operand groups");
2562   if (op.targetOffsetSize() != count)
2563     return op.emitOpError("incorrect number of successor operand groups");
2564   for (decltype(count) i = 0; i != count; ++i) {
2565     auto &attr = cases[i];
2566     if (!(attr.isa<fir::PointIntervalAttr>() ||
2567           attr.isa<fir::LowerBoundAttr>() || attr.isa<fir::UpperBoundAttr>() ||
2568           attr.isa<fir::ClosedIntervalAttr>() || attr.isa<mlir::UnitAttr>()))
2569       return op.emitOpError("incorrect select case attribute type");
2570   }
2571   return mlir::success();
2572 }
2573 
2574 //===----------------------------------------------------------------------===//
2575 // SelectRankOp
2576 //===----------------------------------------------------------------------===//
2577 
2578 llvm::Optional<mlir::OperandRange>
2579 fir::SelectRankOp::getCompareOperands(unsigned) {
2580   return {};
2581 }
2582 
2583 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2584 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
2585   return {};
2586 }
2587 
2588 llvm::Optional<mlir::MutableOperandRange>
2589 fir::SelectRankOp::getMutableSuccessorOperands(unsigned oper) {
2590   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2591                                        getTargetOffsetAttr());
2592 }
2593 
2594 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2595 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2596                                         unsigned oper) {
2597   auto a =
2598       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2599   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2600       getOperandSegmentSizeAttr());
2601   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2602 }
2603 
2604 unsigned fir::SelectRankOp::targetOffsetSize() {
2605   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2606       getTargetOffsetAttr()));
2607 }
2608 
2609 //===----------------------------------------------------------------------===//
2610 // SelectTypeOp
2611 //===----------------------------------------------------------------------===//
2612 
2613 llvm::Optional<mlir::OperandRange>
2614 fir::SelectTypeOp::getCompareOperands(unsigned) {
2615   return {};
2616 }
2617 
2618 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2619 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
2620   return {};
2621 }
2622 
2623 llvm::Optional<mlir::MutableOperandRange>
2624 fir::SelectTypeOp::getMutableSuccessorOperands(unsigned oper) {
2625   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2626                                        getTargetOffsetAttr());
2627 }
2628 
2629 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2630 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2631                                         unsigned oper) {
2632   auto a =
2633       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2634   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2635       getOperandSegmentSizeAttr());
2636   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2637 }
2638 
2639 static ParseResult parseSelectType(OpAsmParser &parser,
2640                                    OperationState &result) {
2641   mlir::OpAsmParser::OperandType selector;
2642   mlir::Type type;
2643   if (parseSelector(parser, result, selector, type))
2644     return mlir::failure();
2645 
2646   llvm::SmallVector<mlir::Attribute> attrs;
2647   llvm::SmallVector<mlir::Block *> dests;
2648   llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
2649   while (true) {
2650     mlir::Attribute attr;
2651     mlir::Block *dest;
2652     llvm::SmallVector<mlir::Value> destArg;
2653     mlir::NamedAttrList temp;
2654     if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() ||
2655         parser.parseSuccessorAndUseList(dest, destArg))
2656       return mlir::failure();
2657     attrs.push_back(attr);
2658     dests.push_back(dest);
2659     destArgs.push_back(destArg);
2660     if (mlir::succeeded(parser.parseOptionalRSquare()))
2661       break;
2662     if (parser.parseComma())
2663       return mlir::failure();
2664   }
2665   auto &bld = parser.getBuilder();
2666   result.addAttribute(fir::SelectTypeOp::getCasesAttr(),
2667                       bld.getArrayAttr(attrs));
2668   llvm::SmallVector<int32_t> argOffs;
2669   int32_t offSize = 0;
2670   const auto count = dests.size();
2671   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2672     result.addSuccessors(dests[i]);
2673     result.addOperands(destArgs[i]);
2674     auto argSize = destArgs[i].size();
2675     argOffs.push_back(argSize);
2676     offSize += argSize;
2677   }
2678   result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(),
2679                       bld.getI32VectorAttr({1, 0, offSize}));
2680   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs));
2681   return mlir::success();
2682 }
2683 
2684 unsigned fir::SelectTypeOp::targetOffsetSize() {
2685   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2686       getTargetOffsetAttr()));
2687 }
2688 
2689 static void print(mlir::OpAsmPrinter &p, fir::SelectTypeOp &op) {
2690   p << ' ';
2691   p.printOperand(op.getSelector());
2692   p << " : " << op.getSelector().getType() << " [";
2693   auto cases = op.getOperation()
2694                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2695                    .getValue();
2696   auto count = op.getNumConditions();
2697   for (decltype(count) i = 0; i != count; ++i) {
2698     if (i)
2699       p << ", ";
2700     p << cases[i] << ", ";
2701     op.printSuccessorAtIndex(p, i);
2702   }
2703   p << ']';
2704   p.printOptionalAttrDict(op.getOperation()->getAttrs(),
2705                           {op.getCasesAttr(), getCompareOffsetAttr(),
2706                            getTargetOffsetAttr(),
2707                            fir::SelectTypeOp::getOperandSegmentSizeAttr()});
2708 }
2709 
2710 static mlir::LogicalResult verify(fir::SelectTypeOp &op) {
2711   if (!(op.getSelector().getType().isa<fir::BoxType>()))
2712     return op.emitOpError("must be a boxed type");
2713   auto cases = op.getOperation()
2714                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2715                    .getValue();
2716   auto count = op.getNumDest();
2717   if (count == 0)
2718     return op.emitOpError("must have at least one successor");
2719   if (op.getNumConditions() != count)
2720     return op.emitOpError("number of conditions and successors don't match");
2721   if (op.targetOffsetSize() != count)
2722     return op.emitOpError("incorrect number of successor operand groups");
2723   for (decltype(count) i = 0; i != count; ++i) {
2724     auto &attr = cases[i];
2725     if (!(attr.isa<fir::ExactTypeAttr>() || attr.isa<fir::SubclassAttr>() ||
2726           attr.isa<mlir::UnitAttr>()))
2727       return op.emitOpError("invalid type-case alternative");
2728   }
2729   return mlir::success();
2730 }
2731 
2732 void fir::SelectTypeOp::build(mlir::OpBuilder &builder,
2733                               mlir::OperationState &result,
2734                               mlir::Value selector,
2735                               llvm::ArrayRef<mlir::Attribute> typeOperands,
2736                               llvm::ArrayRef<mlir::Block *> destinations,
2737                               llvm::ArrayRef<mlir::ValueRange> destOperands,
2738                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2739   result.addOperands(selector);
2740   result.addAttribute(getCasesAttr(), builder.getArrayAttr(typeOperands));
2741   const auto count = destinations.size();
2742   for (mlir::Block *dest : destinations)
2743     result.addSuccessors(dest);
2744   const auto opCount = destOperands.size();
2745   llvm::SmallVector<int32_t> argOffs;
2746   int32_t sumArgs = 0;
2747   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2748     if (i < opCount) {
2749       result.addOperands(destOperands[i]);
2750       const auto argSz = destOperands[i].size();
2751       argOffs.push_back(argSz);
2752       sumArgs += argSz;
2753     } else {
2754       argOffs.push_back(0);
2755     }
2756   }
2757   result.addAttribute(getOperandSegmentSizeAttr(),
2758                       builder.getI32VectorAttr({1, 0, sumArgs}));
2759   result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
2760   result.addAttributes(attributes);
2761 }
2762 
2763 //===----------------------------------------------------------------------===//
2764 // ShapeOp
2765 //===----------------------------------------------------------------------===//
2766 
2767 static mlir::LogicalResult verify(fir::ShapeOp &op) {
2768   auto size = op.extents().size();
2769   auto shapeTy = op.getType().dyn_cast<fir::ShapeType>();
2770   assert(shapeTy && "must be a shape type");
2771   if (shapeTy.getRank() != size)
2772     return op.emitOpError("shape type rank mismatch");
2773   return mlir::success();
2774 }
2775 
2776 //===----------------------------------------------------------------------===//
2777 // ShapeShiftOp
2778 //===----------------------------------------------------------------------===//
2779 
2780 static mlir::LogicalResult verify(fir::ShapeShiftOp &op) {
2781   auto size = op.pairs().size();
2782   if (size < 2 || size > 16 * 2)
2783     return op.emitOpError("incorrect number of args");
2784   if (size % 2 != 0)
2785     return op.emitOpError("requires a multiple of 2 args");
2786   auto shapeTy = op.getType().dyn_cast<fir::ShapeShiftType>();
2787   assert(shapeTy && "must be a shape shift type");
2788   if (shapeTy.getRank() * 2 != size)
2789     return op.emitOpError("shape type rank mismatch");
2790   return mlir::success();
2791 }
2792 
2793 //===----------------------------------------------------------------------===//
2794 // ShiftOp
2795 //===----------------------------------------------------------------------===//
2796 
2797 static mlir::LogicalResult verify(fir::ShiftOp &op) {
2798   auto size = op.origins().size();
2799   auto shiftTy = op.getType().dyn_cast<fir::ShiftType>();
2800   assert(shiftTy && "must be a shift type");
2801   if (shiftTy.getRank() != size)
2802     return op.emitOpError("shift type rank mismatch");
2803   return mlir::success();
2804 }
2805 
2806 //===----------------------------------------------------------------------===//
2807 // SliceOp
2808 //===----------------------------------------------------------------------===//
2809 
2810 /// Return the output rank of a slice op. The output rank must be between 1 and
2811 /// the rank of the array being sliced (inclusive).
2812 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) {
2813   unsigned rank = 0;
2814   if (!triples.empty()) {
2815     for (unsigned i = 1, end = triples.size(); i < end; i += 3) {
2816       auto op = triples[i].getDefiningOp();
2817       if (!mlir::isa_and_nonnull<fir::UndefOp>(op))
2818         ++rank;
2819     }
2820     assert(rank > 0);
2821   }
2822   return rank;
2823 }
2824 
2825 static mlir::LogicalResult verify(fir::SliceOp &op) {
2826   auto size = op.triples().size();
2827   if (size < 3 || size > 16 * 3)
2828     return op.emitOpError("incorrect number of args for triple");
2829   if (size % 3 != 0)
2830     return op.emitOpError("requires a multiple of 3 args");
2831   auto sliceTy = op.getType().dyn_cast<fir::SliceType>();
2832   assert(sliceTy && "must be a slice type");
2833   if (sliceTy.getRank() * 3 != size)
2834     return op.emitOpError("slice type rank mismatch");
2835   return mlir::success();
2836 }
2837 
2838 //===----------------------------------------------------------------------===//
2839 // StoreOp
2840 //===----------------------------------------------------------------------===//
2841 
2842 mlir::Type fir::StoreOp::elementType(mlir::Type refType) {
2843   return fir::dyn_cast_ptrEleTy(refType);
2844 }
2845 
2846 static mlir::ParseResult parseStoreOp(mlir::OpAsmParser &parser,
2847                                       mlir::OperationState &result) {
2848   mlir::Type type;
2849   mlir::OpAsmParser::OperandType oper;
2850   mlir::OpAsmParser::OperandType store;
2851   if (parser.parseOperand(oper) || parser.parseKeyword("to") ||
2852       parser.parseOperand(store) ||
2853       parser.parseOptionalAttrDict(result.attributes) ||
2854       parser.parseColonType(type) ||
2855       parser.resolveOperand(oper, fir::StoreOp::elementType(type),
2856                             result.operands) ||
2857       parser.resolveOperand(store, type, result.operands))
2858     return mlir::failure();
2859   return mlir::success();
2860 }
2861 
2862 static void print(mlir::OpAsmPrinter &p, fir::StoreOp &op) {
2863   p << ' ';
2864   p.printOperand(op.value());
2865   p << " to ";
2866   p.printOperand(op.memref());
2867   p.printOptionalAttrDict(op.getOperation()->getAttrs(), {});
2868   p << " : " << op.memref().getType();
2869 }
2870 
2871 static mlir::LogicalResult verify(fir::StoreOp &op) {
2872   if (op.value().getType() != fir::dyn_cast_ptrEleTy(op.memref().getType()))
2873     return op.emitOpError("store value type must match memory reference type");
2874   if (fir::isa_unknown_size_box(op.value().getType()))
2875     return op.emitOpError("cannot store !fir.box of unknown rank or type");
2876   return mlir::success();
2877 }
2878 
2879 //===----------------------------------------------------------------------===//
2880 // StringLitOp
2881 //===----------------------------------------------------------------------===//
2882 
2883 bool fir::StringLitOp::isWideValue() {
2884   auto eleTy = getType().cast<fir::SequenceType>().getEleTy();
2885   return eleTy.cast<fir::CharacterType>().getFKind() != 1;
2886 }
2887 
2888 static mlir::NamedAttribute
2889 mkNamedIntegerAttr(mlir::OpBuilder &builder, llvm::StringRef name, int64_t v) {
2890   assert(v > 0);
2891   return builder.getNamedAttr(
2892       name, builder.getIntegerAttr(builder.getIntegerType(64), v));
2893 }
2894 
2895 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2896                              fir::CharacterType inType, llvm::StringRef val,
2897                              llvm::Optional<int64_t> len) {
2898   auto valAttr = builder.getNamedAttr(value(), builder.getStringAttr(val));
2899   int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2900   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2901   result.addAttributes({valAttr, lenAttr});
2902   result.addTypes(inType);
2903 }
2904 
2905 template <typename C>
2906 static mlir::ArrayAttr convertToArrayAttr(mlir::OpBuilder &builder,
2907                                           llvm::ArrayRef<C> xlist) {
2908   llvm::SmallVector<mlir::Attribute> attrs;
2909   auto ty = builder.getIntegerType(8 * sizeof(C));
2910   for (auto ch : xlist)
2911     attrs.push_back(builder.getIntegerAttr(ty, ch));
2912   return builder.getArrayAttr(attrs);
2913 }
2914 
2915 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2916                              fir::CharacterType inType,
2917                              llvm::ArrayRef<char> vlist,
2918                              llvm::Optional<int64_t> len) {
2919   auto valAttr =
2920       builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
2921   std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2922   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2923   result.addAttributes({valAttr, lenAttr});
2924   result.addTypes(inType);
2925 }
2926 
2927 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2928                              fir::CharacterType inType,
2929                              llvm::ArrayRef<char16_t> vlist,
2930                              llvm::Optional<int64_t> len) {
2931   auto valAttr =
2932       builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
2933   std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2934   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2935   result.addAttributes({valAttr, lenAttr});
2936   result.addTypes(inType);
2937 }
2938 
2939 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2940                              fir::CharacterType inType,
2941                              llvm::ArrayRef<char32_t> vlist,
2942                              llvm::Optional<int64_t> len) {
2943   auto valAttr =
2944       builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
2945   std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2946   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2947   result.addAttributes({valAttr, lenAttr});
2948   result.addTypes(inType);
2949 }
2950 
2951 static mlir::ParseResult parseStringLitOp(mlir::OpAsmParser &parser,
2952                                           mlir::OperationState &result) {
2953   auto &builder = parser.getBuilder();
2954   mlir::Attribute val;
2955   mlir::NamedAttrList attrs;
2956   llvm::SMLoc trailingTypeLoc;
2957   if (parser.parseAttribute(val, "fake", attrs))
2958     return mlir::failure();
2959   if (auto v = val.dyn_cast<mlir::StringAttr>())
2960     result.attributes.push_back(
2961         builder.getNamedAttr(fir::StringLitOp::value(), v));
2962   else if (auto v = val.dyn_cast<mlir::ArrayAttr>())
2963     result.attributes.push_back(
2964         builder.getNamedAttr(fir::StringLitOp::xlist(), v));
2965   else
2966     return parser.emitError(parser.getCurrentLocation(),
2967                             "found an invalid constant");
2968   mlir::IntegerAttr sz;
2969   mlir::Type type;
2970   if (parser.parseLParen() ||
2971       parser.parseAttribute(sz, fir::StringLitOp::size(), result.attributes) ||
2972       parser.parseRParen() || parser.getCurrentLocation(&trailingTypeLoc) ||
2973       parser.parseColonType(type))
2974     return mlir::failure();
2975   auto charTy = type.dyn_cast<fir::CharacterType>();
2976   if (!charTy)
2977     return parser.emitError(trailingTypeLoc, "must have character type");
2978   type = fir::CharacterType::get(builder.getContext(), charTy.getFKind(),
2979                                  sz.getInt());
2980   if (!type || parser.addTypesToList(type, result.types))
2981     return mlir::failure();
2982   return mlir::success();
2983 }
2984 
2985 static void print(mlir::OpAsmPrinter &p, fir::StringLitOp &op) {
2986   p << ' ' << op.getValue() << '(';
2987   p << op.getSize().cast<mlir::IntegerAttr>().getValue() << ") : ";
2988   p.printType(op.getType());
2989 }
2990 
2991 static mlir::LogicalResult verify(fir::StringLitOp &op) {
2992   if (op.getSize().cast<mlir::IntegerAttr>().getValue().isNegative())
2993     return op.emitOpError("size must be non-negative");
2994   if (auto xl = op.getOperation()->getAttr(fir::StringLitOp::xlist())) {
2995     auto xList = xl.cast<mlir::ArrayAttr>();
2996     for (auto a : xList)
2997       if (!a.isa<mlir::IntegerAttr>())
2998         return op.emitOpError("values in list must be integers");
2999   }
3000   return mlir::success();
3001 }
3002 
3003 //===----------------------------------------------------------------------===//
3004 // UnboxProcOp
3005 //===----------------------------------------------------------------------===//
3006 
3007 static mlir::LogicalResult verify(fir::UnboxProcOp &op) {
3008   if (auto eleTy = fir::dyn_cast_ptrEleTy(op.refTuple().getType()))
3009     if (eleTy.isa<mlir::TupleType>())
3010       return mlir::success();
3011   return op.emitOpError("second output argument has bad type");
3012 }
3013 
3014 //===----------------------------------------------------------------------===//
3015 // IfOp
3016 //===----------------------------------------------------------------------===//
3017 
3018 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
3019                       mlir::Value cond, bool withElseRegion) {
3020   build(builder, result, llvm::None, cond, withElseRegion);
3021 }
3022 
3023 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
3024                       mlir::TypeRange resultTypes, mlir::Value cond,
3025                       bool withElseRegion) {
3026   result.addOperands(cond);
3027   result.addTypes(resultTypes);
3028 
3029   mlir::Region *thenRegion = result.addRegion();
3030   thenRegion->push_back(new mlir::Block());
3031   if (resultTypes.empty())
3032     IfOp::ensureTerminator(*thenRegion, builder, result.location);
3033 
3034   mlir::Region *elseRegion = result.addRegion();
3035   if (withElseRegion) {
3036     elseRegion->push_back(new mlir::Block());
3037     if (resultTypes.empty())
3038       IfOp::ensureTerminator(*elseRegion, builder, result.location);
3039   }
3040 }
3041 
3042 static mlir::ParseResult parseIfOp(OpAsmParser &parser,
3043                                    OperationState &result) {
3044   result.regions.reserve(2);
3045   mlir::Region *thenRegion = result.addRegion();
3046   mlir::Region *elseRegion = result.addRegion();
3047 
3048   auto &builder = parser.getBuilder();
3049   OpAsmParser::OperandType cond;
3050   mlir::Type i1Type = builder.getIntegerType(1);
3051   if (parser.parseOperand(cond) ||
3052       parser.resolveOperand(cond, i1Type, result.operands))
3053     return mlir::failure();
3054 
3055   if (parser.parseOptionalArrowTypeList(result.types))
3056     return mlir::failure();
3057 
3058   if (parser.parseRegion(*thenRegion, {}, {}))
3059     return mlir::failure();
3060   IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
3061 
3062   if (mlir::succeeded(parser.parseOptionalKeyword("else"))) {
3063     if (parser.parseRegion(*elseRegion, {}, {}))
3064       return mlir::failure();
3065     IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
3066   }
3067 
3068   // Parse the optional attribute list.
3069   if (parser.parseOptionalAttrDict(result.attributes))
3070     return mlir::failure();
3071   return mlir::success();
3072 }
3073 
3074 static LogicalResult verify(fir::IfOp op) {
3075   if (op.getNumResults() != 0 && op.elseRegion().empty())
3076     return op.emitOpError("must have an else block if defining values");
3077 
3078   return mlir::success();
3079 }
3080 
3081 static void print(mlir::OpAsmPrinter &p, fir::IfOp op) {
3082   bool printBlockTerminators = false;
3083   p << ' ' << op.condition();
3084   if (!op.results().empty()) {
3085     p << " -> (" << op.getResultTypes() << ')';
3086     printBlockTerminators = true;
3087   }
3088   p.printRegion(op.thenRegion(), /*printEntryBlockArgs=*/false,
3089                 printBlockTerminators);
3090 
3091   // Print the 'else' regions if it exists and has a block.
3092   auto &otherReg = op.elseRegion();
3093   if (!otherReg.empty()) {
3094     p << " else";
3095     p.printRegion(otherReg, /*printEntryBlockArgs=*/false,
3096                   printBlockTerminators);
3097   }
3098   p.printOptionalAttrDict(op->getAttrs());
3099 }
3100 
3101 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results,
3102                                   unsigned resultNum) {
3103   auto *term = thenRegion().front().getTerminator();
3104   if (resultNum < term->getNumOperands())
3105     results.push_back(term->getOperand(resultNum));
3106   term = elseRegion().front().getTerminator();
3107   if (resultNum < term->getNumOperands())
3108     results.push_back(term->getOperand(resultNum));
3109 }
3110 
3111 //===----------------------------------------------------------------------===//
3112 
3113 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) {
3114   if (attr.dyn_cast_or_null<mlir::UnitAttr>() ||
3115       attr.dyn_cast_or_null<ClosedIntervalAttr>() ||
3116       attr.dyn_cast_or_null<PointIntervalAttr>() ||
3117       attr.dyn_cast_or_null<LowerBoundAttr>() ||
3118       attr.dyn_cast_or_null<UpperBoundAttr>())
3119     return mlir::success();
3120   return mlir::failure();
3121 }
3122 
3123 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,
3124                                     unsigned dest) {
3125   unsigned o = 0;
3126   for (unsigned i = 0; i < dest; ++i) {
3127     auto &attr = cases[i];
3128     if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) {
3129       ++o;
3130       if (attr.dyn_cast_or_null<ClosedIntervalAttr>())
3131         ++o;
3132     }
3133   }
3134   return o;
3135 }
3136 
3137 mlir::ParseResult fir::parseSelector(mlir::OpAsmParser &parser,
3138                                      mlir::OperationState &result,
3139                                      mlir::OpAsmParser::OperandType &selector,
3140                                      mlir::Type &type) {
3141   if (parser.parseOperand(selector) || parser.parseColonType(type) ||
3142       parser.resolveOperand(selector, type, result.operands) ||
3143       parser.parseLSquare())
3144     return mlir::failure();
3145   return mlir::success();
3146 }
3147 
3148 /// Generic pretty-printer of a binary operation
3149 static void printBinaryOp(Operation *op, OpAsmPrinter &p) {
3150   assert(op->getNumOperands() == 2 && "binary op must have two operands");
3151   assert(op->getNumResults() == 1 && "binary op must have one result");
3152 
3153   p << ' ' << op->getOperand(0) << ", " << op->getOperand(1);
3154   p.printOptionalAttrDict(op->getAttrs());
3155   p << " : " << op->getResult(0).getType();
3156 }
3157 
3158 /// Generic pretty-printer of an unary operation
3159 static void printUnaryOp(Operation *op, OpAsmPrinter &p) {
3160   assert(op->getNumOperands() == 1 && "unary op must have one operand");
3161   assert(op->getNumResults() == 1 && "unary op must have one result");
3162 
3163   p << ' ' << op->getOperand(0);
3164   p.printOptionalAttrDict(op->getAttrs());
3165   p << " : " << op->getResult(0).getType();
3166 }
3167 
3168 bool fir::isReferenceLike(mlir::Type type) {
3169   return type.isa<fir::ReferenceType>() || type.isa<fir::HeapType>() ||
3170          type.isa<fir::PointerType>();
3171 }
3172 
3173 mlir::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module,
3174                                StringRef name, mlir::FunctionType type,
3175                                llvm::ArrayRef<mlir::NamedAttribute> attrs) {
3176   if (auto f = module.lookupSymbol<mlir::FuncOp>(name))
3177     return f;
3178   mlir::OpBuilder modBuilder(module.getBodyRegion());
3179   modBuilder.setInsertionPoint(module.getBody()->getTerminator());
3180   auto result = modBuilder.create<mlir::FuncOp>(loc, name, type, attrs);
3181   result.setVisibility(mlir::SymbolTable::Visibility::Private);
3182   return result;
3183 }
3184 
3185 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module,
3186                                   StringRef name, mlir::Type type,
3187                                   llvm::ArrayRef<mlir::NamedAttribute> attrs) {
3188   if (auto g = module.lookupSymbol<fir::GlobalOp>(name))
3189     return g;
3190   mlir::OpBuilder modBuilder(module.getBodyRegion());
3191   auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs);
3192   result.setVisibility(mlir::SymbolTable::Visibility::Private);
3193   return result;
3194 }
3195 
3196 bool fir::valueHasFirAttribute(mlir::Value value,
3197                                llvm::StringRef attributeName) {
3198   // If this is a fir.box that was loaded, the fir attributes will be on the
3199   // related fir.ref<fir.box> creation.
3200   if (value.getType().isa<fir::BoxType>())
3201     if (auto definingOp = value.getDefiningOp())
3202       if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp))
3203         value = loadOp.memref();
3204   // If this is a function argument, look in the argument attributes.
3205   if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) {
3206     if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock())
3207       if (auto funcOp =
3208               mlir::dyn_cast<mlir::FuncOp>(blockArg.getOwner()->getParentOp()))
3209         if (funcOp.getArgAttr(blockArg.getArgNumber(), attributeName))
3210           return true;
3211     return false;
3212   }
3213 
3214   if (auto definingOp = value.getDefiningOp()) {
3215     // If this is an allocated value, look at the allocation attributes.
3216     if (mlir::isa<fir::AllocMemOp>(definingOp) ||
3217         mlir::isa<AllocaOp>(definingOp))
3218       return definingOp->hasAttr(attributeName);
3219     // If this is an imported global, look at AddrOfOp and GlobalOp attributes.
3220     // Both operations are looked at because use/host associated variable (the
3221     // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate
3222     // entity (the globalOp) does not have them.
3223     if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) {
3224       if (addressOfOp->hasAttr(attributeName))
3225         return true;
3226       if (auto module = definingOp->getParentOfType<mlir::ModuleOp>())
3227         if (auto globalOp =
3228                 module.lookupSymbol<fir::GlobalOp>(addressOfOp.symbol()))
3229           return globalOp->hasAttr(attributeName);
3230     }
3231   }
3232   // TODO: Construct associated entities attributes. Decide where the fir
3233   // attributes must be placed/looked for in this case.
3234   return false;
3235 }
3236 
3237 mlir::Type fir::applyPathToType(mlir::Type eleTy, mlir::ValueRange path) {
3238   for (auto i = path.begin(), end = path.end(); eleTy && i < end;) {
3239     eleTy = llvm::TypeSwitch<mlir::Type, mlir::Type>(eleTy)
3240                 .Case<fir::RecordType>([&](fir::RecordType ty) {
3241                   if (auto *op = (*i++).getDefiningOp()) {
3242                     if (auto off = mlir::dyn_cast<fir::FieldIndexOp>(op))
3243                       return ty.getType(off.getFieldName());
3244                     if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op))
3245                       return ty.getType(fir::toInt(off));
3246                   }
3247                   return mlir::Type{};
3248                 })
3249                 .Case<fir::SequenceType>([&](fir::SequenceType ty) {
3250                   bool valid = true;
3251                   const auto rank = ty.getDimension();
3252                   for (std::remove_const_t<decltype(rank)> ii = 0;
3253                        valid && ii < rank; ++ii)
3254                     valid = i < end && fir::isa_integer((*i++).getType());
3255                   return valid ? ty.getEleTy() : mlir::Type{};
3256                 })
3257                 .Case<mlir::TupleType>([&](mlir::TupleType ty) {
3258                   if (auto *op = (*i++).getDefiningOp())
3259                     if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op))
3260                       return ty.getType(fir::toInt(off));
3261                   return mlir::Type{};
3262                 })
3263                 .Case<fir::ComplexType>([&](fir::ComplexType ty) {
3264                   if (fir::isa_integer((*i++).getType()))
3265                     return ty.getElementType();
3266                   return mlir::Type{};
3267                 })
3268                 .Case<mlir::ComplexType>([&](mlir::ComplexType ty) {
3269                   if (fir::isa_integer((*i++).getType()))
3270                     return ty.getElementType();
3271                   return mlir::Type{};
3272                 })
3273                 .Default([&](const auto &) { return mlir::Type{}; });
3274   }
3275   return eleTy;
3276 }
3277 
3278 // Tablegen operators
3279 
3280 #define GET_OP_CLASSES
3281 #include "flang/Optimizer/Dialect/FIROps.cpp.inc"
3282