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 mlir::Type fir::GlobalOp::resultType() {
1315   return wrapAllocaResultType(getType());
1316 }
1317 
1318 static mlir::ParseResult parseGlobalLenOp(mlir::OpAsmParser &parser,
1319                                           mlir::OperationState &result) {
1320   llvm::StringRef fieldName;
1321   if (failed(parser.parseOptionalKeyword(&fieldName))) {
1322     mlir::StringAttr fieldAttr;
1323     if (parser.parseAttribute(fieldAttr, fir::GlobalLenOp::lenParamAttrName(),
1324                               result.attributes))
1325       return mlir::failure();
1326   } else {
1327     result.addAttribute(fir::GlobalLenOp::lenParamAttrName(),
1328                         parser.getBuilder().getStringAttr(fieldName));
1329   }
1330   mlir::IntegerAttr constant;
1331   if (parser.parseComma() ||
1332       parser.parseAttribute(constant, fir::GlobalLenOp::intAttrName(),
1333                             result.attributes))
1334     return mlir::failure();
1335   return mlir::success();
1336 }
1337 
1338 static void print(mlir::OpAsmPrinter &p, fir::GlobalLenOp &op) {
1339   p << ' ' << op.getOperation()->getAttr(fir::GlobalLenOp::lenParamAttrName())
1340     << ", " << op.getOperation()->getAttr(fir::GlobalLenOp::intAttrName());
1341 }
1342 
1343 //===----------------------------------------------------------------------===//
1344 // ExtractValueOp
1345 //===----------------------------------------------------------------------===//
1346 
1347 void fir::ExtractValueOp::build(mlir::OpBuilder &builder,
1348                                 OperationState &result, mlir::Type resTy,
1349                                 mlir::Value aggVal,
1350                                 llvm::ArrayRef<mlir::Value> inds) {
1351   auto aa = collectAsAttributes<>(builder.getContext(), result, inds);
1352   build(builder, result, resTy, aggVal, aa);
1353 }
1354 
1355 //===----------------------------------------------------------------------===//
1356 // FieldIndexOp
1357 //===----------------------------------------------------------------------===//
1358 
1359 static mlir::ParseResult parseFieldIndexOp(mlir::OpAsmParser &parser,
1360                                            mlir::OperationState &result) {
1361   llvm::StringRef fieldName;
1362   auto &builder = parser.getBuilder();
1363   mlir::Type recty;
1364   if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() ||
1365       parser.parseType(recty))
1366     return mlir::failure();
1367   result.addAttribute(fir::FieldIndexOp::fieldAttrName(),
1368                       builder.getStringAttr(fieldName));
1369   if (!recty.dyn_cast<RecordType>())
1370     return mlir::failure();
1371   result.addAttribute(fir::FieldIndexOp::typeAttrName(),
1372                       mlir::TypeAttr::get(recty));
1373   if (!parser.parseOptionalLParen()) {
1374     llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
1375     llvm::SmallVector<mlir::Type> types;
1376     auto loc = parser.getNameLoc();
1377     if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) ||
1378         parser.parseColonTypeList(types) || parser.parseRParen() ||
1379         parser.resolveOperands(operands, types, loc, result.operands))
1380       return mlir::failure();
1381   }
1382   mlir::Type fieldType = fir::FieldType::get(builder.getContext());
1383   if (parser.addTypeToList(fieldType, result.types))
1384     return mlir::failure();
1385   return mlir::success();
1386 }
1387 
1388 static void print(mlir::OpAsmPrinter &p, fir::FieldIndexOp &op) {
1389   p << ' '
1390     << op.getOperation()
1391            ->getAttrOfType<mlir::StringAttr>(fir::FieldIndexOp::fieldAttrName())
1392            .getValue()
1393     << ", " << op.getOperation()->getAttr(fir::FieldIndexOp::typeAttrName());
1394   if (op.getNumOperands()) {
1395     p << '(';
1396     p.printOperands(op.typeparams());
1397     const auto *sep = ") : ";
1398     for (auto op : op.typeparams()) {
1399       p << sep;
1400       if (op)
1401         p.printType(op.getType());
1402       else
1403         p << "()";
1404       sep = ", ";
1405     }
1406   }
1407 }
1408 
1409 void fir::FieldIndexOp::build(mlir::OpBuilder &builder,
1410                               mlir::OperationState &result,
1411                               llvm::StringRef fieldName, mlir::Type recTy,
1412                               mlir::ValueRange operands) {
1413   result.addAttribute(fieldAttrName(), builder.getStringAttr(fieldName));
1414   result.addAttribute(typeAttrName(), TypeAttr::get(recTy));
1415   result.addOperands(operands);
1416 }
1417 
1418 //===----------------------------------------------------------------------===//
1419 // InsertOnRangeOp
1420 //===----------------------------------------------------------------------===//
1421 
1422 void fir::InsertOnRangeOp::build(mlir::OpBuilder &builder,
1423                                  OperationState &result, mlir::Type resTy,
1424                                  mlir::Value aggVal, mlir::Value eleVal,
1425                                  llvm::ArrayRef<mlir::Value> inds) {
1426   auto aa = collectAsAttributes<false>(builder.getContext(), result, inds);
1427   build(builder, result, resTy, aggVal, eleVal, aa);
1428 }
1429 
1430 /// Range bounds must be nonnegative, and the range must not be empty.
1431 static mlir::LogicalResult verify(fir::InsertOnRangeOp op) {
1432   if (op.coor().size() < 2 || op.coor().size() % 2 != 0)
1433     return op.emitOpError("has uneven number of values in ranges");
1434   bool rangeIsKnownToBeNonempty = false;
1435   for (auto i = op.coor().end(), b = op.coor().begin(); i != b;) {
1436     int64_t ub = (*--i).cast<IntegerAttr>().getInt();
1437     int64_t lb = (*--i).cast<IntegerAttr>().getInt();
1438     if (lb < 0 || ub < 0)
1439       return op.emitOpError("negative range bound");
1440     if (rangeIsKnownToBeNonempty)
1441       continue;
1442     if (lb > ub)
1443       return op.emitOpError("empty range");
1444     rangeIsKnownToBeNonempty = lb < ub;
1445   }
1446   return mlir::success();
1447 }
1448 
1449 //===----------------------------------------------------------------------===//
1450 // InsertValueOp
1451 //===----------------------------------------------------------------------===//
1452 
1453 void fir::InsertValueOp::build(mlir::OpBuilder &builder, OperationState &result,
1454                                mlir::Type resTy, mlir::Value aggVal,
1455                                mlir::Value eleVal,
1456                                llvm::ArrayRef<mlir::Value> inds) {
1457   auto aa = collectAsAttributes<>(builder.getContext(), result, inds);
1458   build(builder, result, resTy, aggVal, eleVal, aa);
1459 }
1460 
1461 static bool checkIsIntegerConstant(mlir::Attribute attr, int64_t conVal) {
1462   if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>())
1463     return iattr.getInt() == conVal;
1464   return false;
1465 }
1466 static bool isZero(mlir::Attribute a) { return checkIsIntegerConstant(a, 0); }
1467 static bool isOne(mlir::Attribute a) { return checkIsIntegerConstant(a, 1); }
1468 
1469 // Undo some complex patterns created in the front-end and turn them back into
1470 // complex ops.
1471 template <typename FltOp, typename CpxOp>
1472 struct UndoComplexPattern : public mlir::RewritePattern {
1473   UndoComplexPattern(mlir::MLIRContext *ctx)
1474       : mlir::RewritePattern("fir.insert_value", 2, ctx) {}
1475 
1476   mlir::LogicalResult
1477   matchAndRewrite(mlir::Operation *op,
1478                   mlir::PatternRewriter &rewriter) const override {
1479     auto insval = dyn_cast_or_null<fir::InsertValueOp>(op);
1480     if (!insval || !insval.getType().isa<fir::ComplexType>())
1481       return mlir::failure();
1482     auto insval2 =
1483         dyn_cast_or_null<fir::InsertValueOp>(insval.adt().getDefiningOp());
1484     if (!insval2 || !isa<fir::UndefOp>(insval2.adt().getDefiningOp()))
1485       return mlir::failure();
1486     auto binf = dyn_cast_or_null<FltOp>(insval.val().getDefiningOp());
1487     auto binf2 = dyn_cast_or_null<FltOp>(insval2.val().getDefiningOp());
1488     if (!binf || !binf2 || insval.coor().size() != 1 ||
1489         !isOne(insval.coor()[0]) || insval2.coor().size() != 1 ||
1490         !isZero(insval2.coor()[0]))
1491       return mlir::failure();
1492     auto eai =
1493         dyn_cast_or_null<fir::ExtractValueOp>(binf.lhs().getDefiningOp());
1494     auto ebi =
1495         dyn_cast_or_null<fir::ExtractValueOp>(binf.rhs().getDefiningOp());
1496     auto ear =
1497         dyn_cast_or_null<fir::ExtractValueOp>(binf2.lhs().getDefiningOp());
1498     auto ebr =
1499         dyn_cast_or_null<fir::ExtractValueOp>(binf2.rhs().getDefiningOp());
1500     if (!eai || !ebi || !ear || !ebr || ear.adt() != eai.adt() ||
1501         ebr.adt() != ebi.adt() || eai.coor().size() != 1 ||
1502         !isOne(eai.coor()[0]) || ebi.coor().size() != 1 ||
1503         !isOne(ebi.coor()[0]) || ear.coor().size() != 1 ||
1504         !isZero(ear.coor()[0]) || ebr.coor().size() != 1 ||
1505         !isZero(ebr.coor()[0]))
1506       return mlir::failure();
1507     rewriter.replaceOpWithNewOp<CpxOp>(op, ear.adt(), ebr.adt());
1508     return mlir::success();
1509   }
1510 };
1511 
1512 void fir::InsertValueOp::getCanonicalizationPatterns(
1513     mlir::OwningRewritePatternList &results, mlir::MLIRContext *context) {
1514   results.insert<UndoComplexPattern<mlir::arith::AddFOp, fir::AddcOp>,
1515                  UndoComplexPattern<mlir::arith::SubFOp, fir::SubcOp>>(context);
1516 }
1517 
1518 //===----------------------------------------------------------------------===//
1519 // IterWhileOp
1520 //===----------------------------------------------------------------------===//
1521 
1522 void fir::IterWhileOp::build(mlir::OpBuilder &builder,
1523                              mlir::OperationState &result, mlir::Value lb,
1524                              mlir::Value ub, mlir::Value step,
1525                              mlir::Value iterate, bool finalCountValue,
1526                              mlir::ValueRange iterArgs,
1527                              llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1528   result.addOperands({lb, ub, step, iterate});
1529   if (finalCountValue) {
1530     result.addTypes(builder.getIndexType());
1531     result.addAttribute(getFinalValueAttrName(), builder.getUnitAttr());
1532   }
1533   result.addTypes(iterate.getType());
1534   result.addOperands(iterArgs);
1535   for (auto v : iterArgs)
1536     result.addTypes(v.getType());
1537   mlir::Region *bodyRegion = result.addRegion();
1538   bodyRegion->push_back(new Block{});
1539   bodyRegion->front().addArgument(builder.getIndexType());
1540   bodyRegion->front().addArgument(iterate.getType());
1541   bodyRegion->front().addArguments(iterArgs.getTypes());
1542   result.addAttributes(attributes);
1543 }
1544 
1545 static mlir::ParseResult parseIterWhileOp(mlir::OpAsmParser &parser,
1546                                           mlir::OperationState &result) {
1547   auto &builder = parser.getBuilder();
1548   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
1549   if (parser.parseLParen() || parser.parseRegionArgument(inductionVariable) ||
1550       parser.parseEqual())
1551     return mlir::failure();
1552 
1553   // Parse loop bounds.
1554   auto indexType = builder.getIndexType();
1555   auto i1Type = builder.getIntegerType(1);
1556   if (parser.parseOperand(lb) ||
1557       parser.resolveOperand(lb, indexType, result.operands) ||
1558       parser.parseKeyword("to") || parser.parseOperand(ub) ||
1559       parser.resolveOperand(ub, indexType, result.operands) ||
1560       parser.parseKeyword("step") || parser.parseOperand(step) ||
1561       parser.parseRParen() ||
1562       parser.resolveOperand(step, indexType, result.operands))
1563     return mlir::failure();
1564 
1565   mlir::OpAsmParser::OperandType iterateVar, iterateInput;
1566   if (parser.parseKeyword("and") || parser.parseLParen() ||
1567       parser.parseRegionArgument(iterateVar) || parser.parseEqual() ||
1568       parser.parseOperand(iterateInput) || parser.parseRParen() ||
1569       parser.resolveOperand(iterateInput, i1Type, result.operands))
1570     return mlir::failure();
1571 
1572   // Parse the initial iteration arguments.
1573   llvm::SmallVector<mlir::OpAsmParser::OperandType> regionArgs;
1574   auto prependCount = false;
1575 
1576   // Induction variable.
1577   regionArgs.push_back(inductionVariable);
1578   regionArgs.push_back(iterateVar);
1579 
1580   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1581     llvm::SmallVector<mlir::OpAsmParser::OperandType> operands;
1582     llvm::SmallVector<mlir::Type> regionTypes;
1583     // Parse assignment list and results type list.
1584     if (parser.parseAssignmentList(regionArgs, operands) ||
1585         parser.parseArrowTypeList(regionTypes))
1586       return failure();
1587     if (regionTypes.size() == operands.size() + 2)
1588       prependCount = true;
1589     llvm::ArrayRef<mlir::Type> resTypes = regionTypes;
1590     resTypes = prependCount ? resTypes.drop_front(2) : resTypes;
1591     // Resolve input operands.
1592     for (auto operandType : llvm::zip(operands, resTypes))
1593       if (parser.resolveOperand(std::get<0>(operandType),
1594                                 std::get<1>(operandType), result.operands))
1595         return failure();
1596     if (prependCount) {
1597       result.addTypes(regionTypes);
1598     } else {
1599       result.addTypes(i1Type);
1600       result.addTypes(resTypes);
1601     }
1602   } else if (succeeded(parser.parseOptionalArrow())) {
1603     llvm::SmallVector<mlir::Type> typeList;
1604     if (parser.parseLParen() || parser.parseTypeList(typeList) ||
1605         parser.parseRParen())
1606       return failure();
1607     // Type list must be "(index, i1)".
1608     if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() ||
1609         !typeList[1].isSignlessInteger(1))
1610       return failure();
1611     result.addTypes(typeList);
1612     prependCount = true;
1613   } else {
1614     result.addTypes(i1Type);
1615   }
1616 
1617   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1618     return mlir::failure();
1619 
1620   llvm::SmallVector<mlir::Type> argTypes;
1621   // Induction variable (hidden)
1622   if (prependCount)
1623     result.addAttribute(IterWhileOp::getFinalValueAttrName(),
1624                         builder.getUnitAttr());
1625   else
1626     argTypes.push_back(indexType);
1627   // Loop carried variables (including iterate)
1628   argTypes.append(result.types.begin(), result.types.end());
1629   // Parse the body region.
1630   auto *body = result.addRegion();
1631   if (regionArgs.size() != argTypes.size())
1632     return parser.emitError(
1633         parser.getNameLoc(),
1634         "mismatch in number of loop-carried values and defined values");
1635 
1636   if (parser.parseRegion(*body, regionArgs, argTypes))
1637     return failure();
1638 
1639   fir::IterWhileOp::ensureTerminator(*body, builder, result.location);
1640 
1641   return mlir::success();
1642 }
1643 
1644 static mlir::LogicalResult verify(fir::IterWhileOp op) {
1645   // Check that the body defines as single block argument for the induction
1646   // variable.
1647   auto *body = op.getBody();
1648   if (!body->getArgument(1).getType().isInteger(1))
1649     return op.emitOpError(
1650         "expected body second argument to be an index argument for "
1651         "the induction variable");
1652   if (!body->getArgument(0).getType().isIndex())
1653     return op.emitOpError(
1654         "expected body first argument to be an index argument for "
1655         "the induction variable");
1656 
1657   auto opNumResults = op.getNumResults();
1658   if (op.finalValue()) {
1659     // Result type must be "(index, i1, ...)".
1660     if (!op.getResult(0).getType().isa<mlir::IndexType>())
1661       return op.emitOpError("result #0 expected to be index");
1662     if (!op.getResult(1).getType().isSignlessInteger(1))
1663       return op.emitOpError("result #1 expected to be i1");
1664     opNumResults--;
1665   } else {
1666     // iterate_while always returns the early exit induction value.
1667     // Result type must be "(i1, ...)"
1668     if (!op.getResult(0).getType().isSignlessInteger(1))
1669       return op.emitOpError("result #0 expected to be i1");
1670   }
1671   if (opNumResults == 0)
1672     return mlir::failure();
1673   if (op.getNumIterOperands() != opNumResults)
1674     return op.emitOpError(
1675         "mismatch in number of loop-carried values and defined values");
1676   if (op.getNumRegionIterArgs() != opNumResults)
1677     return op.emitOpError(
1678         "mismatch in number of basic block args and defined values");
1679   auto iterOperands = op.getIterOperands();
1680   auto iterArgs = op.getRegionIterArgs();
1681   auto opResults =
1682       op.finalValue() ? op.getResults().drop_front() : op.getResults();
1683   unsigned i = 0;
1684   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
1685     if (std::get<0>(e).getType() != std::get<2>(e).getType())
1686       return op.emitOpError() << "types mismatch between " << i
1687                               << "th iter operand and defined value";
1688     if (std::get<1>(e).getType() != std::get<2>(e).getType())
1689       return op.emitOpError() << "types mismatch between " << i
1690                               << "th iter region arg and defined value";
1691 
1692     i++;
1693   }
1694   return mlir::success();
1695 }
1696 
1697 static void print(mlir::OpAsmPrinter &p, fir::IterWhileOp op) {
1698   p << " (" << op.getInductionVar() << " = " << op.lowerBound() << " to "
1699     << op.upperBound() << " step " << op.step() << ") and (";
1700   assert(op.hasIterOperands());
1701   auto regionArgs = op.getRegionIterArgs();
1702   auto operands = op.getIterOperands();
1703   p << regionArgs.front() << " = " << *operands.begin() << ")";
1704   if (regionArgs.size() > 1) {
1705     p << " iter_args(";
1706     llvm::interleaveComma(
1707         llvm::zip(regionArgs.drop_front(), operands.drop_front()), p,
1708         [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); });
1709     p << ") -> (";
1710     llvm::interleaveComma(
1711         llvm::drop_begin(op.getResultTypes(), op.finalValue() ? 0 : 1), p);
1712     p << ")";
1713   } else if (op.finalValue()) {
1714     p << " -> (" << op.getResultTypes() << ')';
1715   }
1716   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
1717                                      {IterWhileOp::getFinalValueAttrName()});
1718   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
1719                 /*printBlockTerminators=*/true);
1720 }
1721 
1722 mlir::Region &fir::IterWhileOp::getLoopBody() { return region(); }
1723 
1724 bool fir::IterWhileOp::isDefinedOutsideOfLoop(mlir::Value value) {
1725   return !region().isAncestor(value.getParentRegion());
1726 }
1727 
1728 mlir::LogicalResult
1729 fir::IterWhileOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
1730   for (auto *op : ops)
1731     op->moveBefore(*this);
1732   return success();
1733 }
1734 
1735 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) {
1736   for (auto i : llvm::enumerate(initArgs()))
1737     if (iterArg == i.value())
1738       return region().front().getArgument(i.index() + 1);
1739   return {};
1740 }
1741 
1742 void fir::IterWhileOp::resultToSourceOps(
1743     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
1744   auto oper = finalValue() ? resultNum + 1 : resultNum;
1745   auto *term = region().front().getTerminator();
1746   if (oper < term->getNumOperands())
1747     results.push_back(term->getOperand(oper));
1748 }
1749 
1750 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) {
1751   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
1752     return initArgs()[blockArgNum - 1];
1753   return {};
1754 }
1755 
1756 //===----------------------------------------------------------------------===//
1757 // LenParamIndexOp
1758 //===----------------------------------------------------------------------===//
1759 
1760 static mlir::ParseResult parseLenParamIndexOp(mlir::OpAsmParser &parser,
1761                                               mlir::OperationState &result) {
1762   llvm::StringRef fieldName;
1763   auto &builder = parser.getBuilder();
1764   mlir::Type recty;
1765   if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() ||
1766       parser.parseType(recty))
1767     return mlir::failure();
1768   result.addAttribute(fir::LenParamIndexOp::fieldAttrName(),
1769                       builder.getStringAttr(fieldName));
1770   if (!recty.dyn_cast<RecordType>())
1771     return mlir::failure();
1772   result.addAttribute(fir::LenParamIndexOp::typeAttrName(),
1773                       mlir::TypeAttr::get(recty));
1774   mlir::Type lenType = fir::LenType::get(builder.getContext());
1775   if (parser.addTypeToList(lenType, result.types))
1776     return mlir::failure();
1777   return mlir::success();
1778 }
1779 
1780 static void print(mlir::OpAsmPrinter &p, fir::LenParamIndexOp &op) {
1781   p << ' '
1782     << op.getOperation()
1783            ->getAttrOfType<mlir::StringAttr>(
1784                fir::LenParamIndexOp::fieldAttrName())
1785            .getValue()
1786     << ", " << op.getOperation()->getAttr(fir::LenParamIndexOp::typeAttrName());
1787 }
1788 
1789 //===----------------------------------------------------------------------===//
1790 // LoadOp
1791 //===----------------------------------------------------------------------===//
1792 
1793 void fir::LoadOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
1794                         mlir::Value refVal) {
1795   if (!refVal) {
1796     mlir::emitError(result.location, "LoadOp has null argument");
1797     return;
1798   }
1799   auto eleTy = fir::dyn_cast_ptrEleTy(refVal.getType());
1800   if (!eleTy) {
1801     mlir::emitError(result.location, "not a memory reference type");
1802     return;
1803   }
1804   result.addOperands(refVal);
1805   result.addTypes(eleTy);
1806 }
1807 
1808 /// Get the element type of a reference like type; otherwise null
1809 static mlir::Type elementTypeOf(mlir::Type ref) {
1810   return llvm::TypeSwitch<mlir::Type, mlir::Type>(ref)
1811       .Case<ReferenceType, PointerType, HeapType>(
1812           [](auto type) { return type.getEleTy(); })
1813       .Default([](mlir::Type) { return mlir::Type{}; });
1814 }
1815 
1816 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) {
1817   if ((ele = elementTypeOf(ref)))
1818     return mlir::success();
1819   return mlir::failure();
1820 }
1821 
1822 static mlir::ParseResult parseLoadOp(mlir::OpAsmParser &parser,
1823                                      mlir::OperationState &result) {
1824   mlir::Type type;
1825   mlir::OpAsmParser::OperandType oper;
1826   if (parser.parseOperand(oper) ||
1827       parser.parseOptionalAttrDict(result.attributes) ||
1828       parser.parseColonType(type) ||
1829       parser.resolveOperand(oper, type, result.operands))
1830     return mlir::failure();
1831   mlir::Type eleTy;
1832   if (fir::LoadOp::getElementOf(eleTy, type) ||
1833       parser.addTypeToList(eleTy, result.types))
1834     return mlir::failure();
1835   return mlir::success();
1836 }
1837 
1838 static void print(mlir::OpAsmPrinter &p, fir::LoadOp &op) {
1839   p << ' ';
1840   p.printOperand(op.memref());
1841   p.printOptionalAttrDict(op.getOperation()->getAttrs(), {});
1842   p << " : " << op.memref().getType();
1843 }
1844 
1845 //===----------------------------------------------------------------------===//
1846 // DoLoopOp
1847 //===----------------------------------------------------------------------===//
1848 
1849 void fir::DoLoopOp::build(mlir::OpBuilder &builder,
1850                           mlir::OperationState &result, mlir::Value lb,
1851                           mlir::Value ub, mlir::Value step, bool unordered,
1852                           bool finalCountValue, mlir::ValueRange iterArgs,
1853                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1854   result.addOperands({lb, ub, step});
1855   result.addOperands(iterArgs);
1856   if (finalCountValue) {
1857     result.addTypes(builder.getIndexType());
1858     result.addAttribute(finalValueAttrName(result.name), builder.getUnitAttr());
1859   }
1860   for (auto v : iterArgs)
1861     result.addTypes(v.getType());
1862   mlir::Region *bodyRegion = result.addRegion();
1863   bodyRegion->push_back(new Block{});
1864   if (iterArgs.empty() && !finalCountValue)
1865     DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
1866   bodyRegion->front().addArgument(builder.getIndexType());
1867   bodyRegion->front().addArguments(iterArgs.getTypes());
1868   if (unordered)
1869     result.addAttribute(unorderedAttrName(result.name), builder.getUnitAttr());
1870   result.addAttributes(attributes);
1871 }
1872 
1873 static mlir::ParseResult parseDoLoopOp(mlir::OpAsmParser &parser,
1874                                        mlir::OperationState &result) {
1875   auto &builder = parser.getBuilder();
1876   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
1877   // Parse the induction variable followed by '='.
1878   if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual())
1879     return mlir::failure();
1880 
1881   // Parse loop bounds.
1882   auto indexType = builder.getIndexType();
1883   if (parser.parseOperand(lb) ||
1884       parser.resolveOperand(lb, indexType, result.operands) ||
1885       parser.parseKeyword("to") || parser.parseOperand(ub) ||
1886       parser.resolveOperand(ub, indexType, result.operands) ||
1887       parser.parseKeyword("step") || parser.parseOperand(step) ||
1888       parser.resolveOperand(step, indexType, result.operands))
1889     return failure();
1890 
1891   if (mlir::succeeded(parser.parseOptionalKeyword("unordered")))
1892     result.addAttribute("unordered", builder.getUnitAttr());
1893 
1894   // Parse the optional initial iteration arguments.
1895   llvm::SmallVector<mlir::OpAsmParser::OperandType> regionArgs, operands;
1896   llvm::SmallVector<mlir::Type> argTypes;
1897   auto prependCount = false;
1898   regionArgs.push_back(inductionVariable);
1899 
1900   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1901     // Parse assignment list and results type list.
1902     if (parser.parseAssignmentList(regionArgs, operands) ||
1903         parser.parseArrowTypeList(result.types))
1904       return failure();
1905     if (result.types.size() == operands.size() + 1)
1906       prependCount = true;
1907     // Resolve input operands.
1908     llvm::ArrayRef<mlir::Type> resTypes = result.types;
1909     for (auto operand_type :
1910          llvm::zip(operands, prependCount ? resTypes.drop_front() : resTypes))
1911       if (parser.resolveOperand(std::get<0>(operand_type),
1912                                 std::get<1>(operand_type), result.operands))
1913         return failure();
1914   } else if (succeeded(parser.parseOptionalArrow())) {
1915     if (parser.parseKeyword("index"))
1916       return failure();
1917     result.types.push_back(indexType);
1918     prependCount = true;
1919   }
1920 
1921   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1922     return mlir::failure();
1923 
1924   // Induction variable.
1925   if (prependCount)
1926     result.addAttribute(DoLoopOp::finalValueAttrName(result.name),
1927                         builder.getUnitAttr());
1928   else
1929     argTypes.push_back(indexType);
1930   // Loop carried variables
1931   argTypes.append(result.types.begin(), result.types.end());
1932   // Parse the body region.
1933   auto *body = result.addRegion();
1934   if (regionArgs.size() != argTypes.size())
1935     return parser.emitError(
1936         parser.getNameLoc(),
1937         "mismatch in number of loop-carried values and defined values");
1938 
1939   if (parser.parseRegion(*body, regionArgs, argTypes))
1940     return failure();
1941 
1942   DoLoopOp::ensureTerminator(*body, builder, result.location);
1943 
1944   return mlir::success();
1945 }
1946 
1947 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) {
1948   auto ivArg = val.dyn_cast<mlir::BlockArgument>();
1949   if (!ivArg)
1950     return {};
1951   assert(ivArg.getOwner() && "unlinked block argument");
1952   auto *containingInst = ivArg.getOwner()->getParentOp();
1953   return dyn_cast_or_null<fir::DoLoopOp>(containingInst);
1954 }
1955 
1956 // Lifted from loop.loop
1957 static mlir::LogicalResult verify(fir::DoLoopOp op) {
1958   // Check that the body defines as single block argument for the induction
1959   // variable.
1960   auto *body = op.getBody();
1961   if (!body->getArgument(0).getType().isIndex())
1962     return op.emitOpError(
1963         "expected body first argument to be an index argument for "
1964         "the induction variable");
1965 
1966   auto opNumResults = op.getNumResults();
1967   if (opNumResults == 0)
1968     return success();
1969 
1970   if (op.finalValue()) {
1971     if (op.unordered())
1972       return op.emitOpError("unordered loop has no final value");
1973     opNumResults--;
1974   }
1975   if (op.getNumIterOperands() != opNumResults)
1976     return op.emitOpError(
1977         "mismatch in number of loop-carried values and defined values");
1978   if (op.getNumRegionIterArgs() != opNumResults)
1979     return op.emitOpError(
1980         "mismatch in number of basic block args and defined values");
1981   auto iterOperands = op.getIterOperands();
1982   auto iterArgs = op.getRegionIterArgs();
1983   auto opResults =
1984       op.finalValue() ? op.getResults().drop_front() : op.getResults();
1985   unsigned i = 0;
1986   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
1987     if (std::get<0>(e).getType() != std::get<2>(e).getType())
1988       return op.emitOpError() << "types mismatch between " << i
1989                               << "th iter operand and defined value";
1990     if (std::get<1>(e).getType() != std::get<2>(e).getType())
1991       return op.emitOpError() << "types mismatch between " << i
1992                               << "th iter region arg and defined value";
1993 
1994     i++;
1995   }
1996   return success();
1997 }
1998 
1999 static void print(mlir::OpAsmPrinter &p, fir::DoLoopOp op) {
2000   bool printBlockTerminators = false;
2001   p << ' ' << op.getInductionVar() << " = " << op.lowerBound() << " to "
2002     << op.upperBound() << " step " << op.step();
2003   if (op.unordered())
2004     p << " unordered";
2005   if (op.hasIterOperands()) {
2006     p << " iter_args(";
2007     auto regionArgs = op.getRegionIterArgs();
2008     auto operands = op.getIterOperands();
2009     llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
2010       p << std::get<0>(it) << " = " << std::get<1>(it);
2011     });
2012     p << ") -> (" << op.getResultTypes() << ')';
2013     printBlockTerminators = true;
2014   } else if (op.finalValue()) {
2015     p << " -> " << op.getResultTypes();
2016     printBlockTerminators = true;
2017   }
2018   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
2019                                      {"unordered", "finalValue"});
2020   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
2021                 printBlockTerminators);
2022 }
2023 
2024 mlir::Region &fir::DoLoopOp::getLoopBody() { return region(); }
2025 
2026 bool fir::DoLoopOp::isDefinedOutsideOfLoop(mlir::Value value) {
2027   return !region().isAncestor(value.getParentRegion());
2028 }
2029 
2030 mlir::LogicalResult
2031 fir::DoLoopOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
2032   for (auto op : ops)
2033     op->moveBefore(*this);
2034   return success();
2035 }
2036 
2037 /// Translate a value passed as an iter_arg to the corresponding block
2038 /// argument in the body of the loop.
2039 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) {
2040   for (auto i : llvm::enumerate(initArgs()))
2041     if (iterArg == i.value())
2042       return region().front().getArgument(i.index() + 1);
2043   return {};
2044 }
2045 
2046 /// Translate the result vector (by index number) to the corresponding value
2047 /// to the `fir.result` Op.
2048 void fir::DoLoopOp::resultToSourceOps(
2049     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
2050   auto oper = finalValue() ? resultNum + 1 : resultNum;
2051   auto *term = region().front().getTerminator();
2052   if (oper < term->getNumOperands())
2053     results.push_back(term->getOperand(oper));
2054 }
2055 
2056 /// Translate the block argument (by index number) to the corresponding value
2057 /// passed as an iter_arg to the parent DoLoopOp.
2058 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) {
2059   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
2060     return initArgs()[blockArgNum - 1];
2061   return {};
2062 }
2063 
2064 //===----------------------------------------------------------------------===//
2065 // DTEntryOp
2066 //===----------------------------------------------------------------------===//
2067 
2068 static mlir::ParseResult parseDTEntryOp(mlir::OpAsmParser &parser,
2069                                         mlir::OperationState &result) {
2070   llvm::StringRef methodName;
2071   // allow `methodName` or `"methodName"`
2072   if (failed(parser.parseOptionalKeyword(&methodName))) {
2073     mlir::StringAttr methodAttr;
2074     if (parser.parseAttribute(methodAttr, fir::DTEntryOp::getMethodAttrName(),
2075                               result.attributes))
2076       return mlir::failure();
2077   } else {
2078     result.addAttribute(fir::DTEntryOp::getMethodAttrName(),
2079                         parser.getBuilder().getStringAttr(methodName));
2080   }
2081   mlir::SymbolRefAttr calleeAttr;
2082   if (parser.parseComma() ||
2083       parser.parseAttribute(calleeAttr, fir::DTEntryOp::getProcAttrName(),
2084                             result.attributes))
2085     return mlir::failure();
2086   return mlir::success();
2087 }
2088 
2089 static void print(mlir::OpAsmPrinter &p, fir::DTEntryOp &op) {
2090   p << ' ' << op.getOperation()->getAttr(fir::DTEntryOp::getMethodAttrName())
2091     << ", " << op.getOperation()->getAttr(fir::DTEntryOp::getProcAttrName());
2092 }
2093 
2094 //===----------------------------------------------------------------------===//
2095 // ReboxOp
2096 //===----------------------------------------------------------------------===//
2097 
2098 /// Get the scalar type related to a fir.box type.
2099 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>.
2100 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
2101   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
2102   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
2103     return seqTy.getEleTy();
2104   return eleTy;
2105 }
2106 
2107 /// Get the rank from a !fir.box type
2108 static unsigned getBoxRank(mlir::Type boxTy) {
2109   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
2110   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
2111     return seqTy.getDimension();
2112   return 0;
2113 }
2114 
2115 static mlir::LogicalResult verify(fir::ReboxOp op) {
2116   auto inputBoxTy = op.box().getType();
2117   if (fir::isa_unknown_size_box(inputBoxTy))
2118     return op.emitOpError("box operand must not have unknown rank or type");
2119   auto outBoxTy = op.getType();
2120   if (fir::isa_unknown_size_box(outBoxTy))
2121     return op.emitOpError("result type must not have unknown rank or type");
2122   auto inputRank = getBoxRank(inputBoxTy);
2123   auto inputEleTy = getBoxScalarEleTy(inputBoxTy);
2124   auto outRank = getBoxRank(outBoxTy);
2125   auto outEleTy = getBoxScalarEleTy(outBoxTy);
2126 
2127   if (auto slice = op.slice()) {
2128     // Slicing case
2129     if (slice.getType().cast<fir::SliceType>().getRank() != inputRank)
2130       return op.emitOpError("slice operand rank must match box operand rank");
2131     if (auto shape = op.shape()) {
2132       if (auto shiftTy = shape.getType().dyn_cast<fir::ShiftType>()) {
2133         if (shiftTy.getRank() != inputRank)
2134           return op.emitOpError("shape operand and input box ranks must match "
2135                                 "when there is a slice");
2136       } else {
2137         return op.emitOpError("shape operand must absent or be a fir.shift "
2138                               "when there is a slice");
2139       }
2140     }
2141     if (auto sliceOp = slice.getDefiningOp()) {
2142       auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank();
2143       if (slicedRank != outRank)
2144         return op.emitOpError("result type rank and rank after applying slice "
2145                               "operand must match");
2146     }
2147   } else {
2148     // Reshaping case
2149     unsigned shapeRank = inputRank;
2150     if (auto shape = op.shape()) {
2151       auto ty = shape.getType();
2152       if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) {
2153         shapeRank = shapeTy.getRank();
2154       } else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) {
2155         shapeRank = shapeShiftTy.getRank();
2156       } else {
2157         auto shiftTy = ty.cast<fir::ShiftType>();
2158         shapeRank = shiftTy.getRank();
2159         if (shapeRank != inputRank)
2160           return op.emitOpError("shape operand and input box ranks must match "
2161                                 "when the shape is a fir.shift");
2162       }
2163     }
2164     if (shapeRank != outRank)
2165       return op.emitOpError("result type and shape operand ranks must match");
2166   }
2167 
2168   if (inputEleTy != outEleTy)
2169     // TODO: check that outBoxTy is a parent type of inputBoxTy for derived
2170     // types.
2171     if (!inputEleTy.isa<fir::RecordType>())
2172       return op.emitOpError(
2173           "op input and output element types must match for intrinsic types");
2174   return mlir::success();
2175 }
2176 
2177 //===----------------------------------------------------------------------===//
2178 // ResultOp
2179 //===----------------------------------------------------------------------===//
2180 
2181 static mlir::LogicalResult verify(fir::ResultOp op) {
2182   auto *parentOp = op->getParentOp();
2183   auto results = parentOp->getResults();
2184   auto operands = op->getOperands();
2185 
2186   if (parentOp->getNumResults() != op.getNumOperands())
2187     return op.emitOpError() << "parent of result must have same arity";
2188   for (auto e : llvm::zip(results, operands))
2189     if (std::get<0>(e).getType() != std::get<1>(e).getType())
2190       return op.emitOpError()
2191              << "types mismatch between result op and its parent";
2192   return success();
2193 }
2194 
2195 //===----------------------------------------------------------------------===//
2196 // SaveResultOp
2197 //===----------------------------------------------------------------------===//
2198 
2199 static mlir::LogicalResult verify(fir::SaveResultOp op) {
2200   auto resultType = op.value().getType();
2201   if (resultType != fir::dyn_cast_ptrEleTy(op.memref().getType()))
2202     return op.emitOpError("value type must match memory reference type");
2203   if (fir::isa_unknown_size_box(resultType))
2204     return op.emitOpError("cannot save !fir.box of unknown rank or type");
2205 
2206   if (resultType.isa<fir::BoxType>()) {
2207     if (op.shape() || !op.typeparams().empty())
2208       return op.emitOpError(
2209           "must not have shape or length operands if the value is a fir.box");
2210     return mlir::success();
2211   }
2212 
2213   // fir.record or fir.array case.
2214   unsigned shapeTyRank = 0;
2215   if (auto shapeOp = op.shape()) {
2216     auto shapeTy = shapeOp.getType();
2217     if (auto s = shapeTy.dyn_cast<fir::ShapeType>())
2218       shapeTyRank = s.getRank();
2219     else
2220       shapeTyRank = shapeTy.cast<fir::ShapeShiftType>().getRank();
2221   }
2222 
2223   auto eleTy = resultType;
2224   if (auto seqTy = resultType.dyn_cast<fir::SequenceType>()) {
2225     if (seqTy.getDimension() != shapeTyRank)
2226       op.emitOpError("shape operand must be provided and have the value rank "
2227                      "when the value is a fir.array");
2228     eleTy = seqTy.getEleTy();
2229   } else {
2230     if (shapeTyRank != 0)
2231       op.emitOpError(
2232           "shape operand should only be provided if the value is a fir.array");
2233   }
2234 
2235   if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) {
2236     if (recTy.getNumLenParams() != op.typeparams().size())
2237       op.emitOpError("length parameters number must match with the value type "
2238                      "length parameters");
2239   } else if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
2240     if (op.typeparams().size() > 1)
2241       op.emitOpError("no more than one length parameter must be provided for "
2242                      "character value");
2243   } else {
2244     if (!op.typeparams().empty())
2245       op.emitOpError(
2246           "length parameters must not be provided for this value type");
2247   }
2248 
2249   return mlir::success();
2250 }
2251 
2252 //===----------------------------------------------------------------------===//
2253 // SelectOp
2254 //===----------------------------------------------------------------------===//
2255 
2256 static constexpr llvm::StringRef getCompareOffsetAttr() {
2257   return "compare_operand_offsets";
2258 }
2259 
2260 static constexpr llvm::StringRef getTargetOffsetAttr() {
2261   return "target_operand_offsets";
2262 }
2263 
2264 template <typename A, typename... AdditionalArgs>
2265 static A getSubOperands(unsigned pos, A allArgs,
2266                         mlir::DenseIntElementsAttr ranges,
2267                         AdditionalArgs &&...additionalArgs) {
2268   unsigned start = 0;
2269   for (unsigned i = 0; i < pos; ++i)
2270     start += (*(ranges.begin() + i)).getZExtValue();
2271   return allArgs.slice(start, (*(ranges.begin() + pos)).getZExtValue(),
2272                        std::forward<AdditionalArgs>(additionalArgs)...);
2273 }
2274 
2275 static mlir::MutableOperandRange
2276 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands,
2277                             StringRef offsetAttr) {
2278   Operation *owner = operands.getOwner();
2279   NamedAttribute targetOffsetAttr =
2280       *owner->getAttrDictionary().getNamed(offsetAttr);
2281   return getSubOperands(
2282       pos, operands, targetOffsetAttr.second.cast<DenseIntElementsAttr>(),
2283       mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr));
2284 }
2285 
2286 static unsigned denseElementsSize(mlir::DenseIntElementsAttr attr) {
2287   return attr.getNumElements();
2288 }
2289 
2290 llvm::Optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) {
2291   return {};
2292 }
2293 
2294 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2295 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
2296   return {};
2297 }
2298 
2299 llvm::Optional<mlir::MutableOperandRange>
2300 fir::SelectOp::getMutableSuccessorOperands(unsigned oper) {
2301   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2302                                        getTargetOffsetAttr());
2303 }
2304 
2305 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2306 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2307                                     unsigned oper) {
2308   auto a =
2309       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2310   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2311       getOperandSegmentSizeAttr());
2312   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2313 }
2314 
2315 unsigned fir::SelectOp::targetOffsetSize() {
2316   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2317       getTargetOffsetAttr()));
2318 }
2319 
2320 //===----------------------------------------------------------------------===//
2321 // SelectCaseOp
2322 //===----------------------------------------------------------------------===//
2323 
2324 llvm::Optional<mlir::OperandRange>
2325 fir::SelectCaseOp::getCompareOperands(unsigned cond) {
2326   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2327       getCompareOffsetAttr());
2328   return {getSubOperands(cond, compareArgs(), a)};
2329 }
2330 
2331 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2332 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands,
2333                                       unsigned cond) {
2334   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2335       getCompareOffsetAttr());
2336   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2337       getOperandSegmentSizeAttr());
2338   return {getSubOperands(cond, getSubOperands(1, operands, segments), a)};
2339 }
2340 
2341 llvm::Optional<mlir::MutableOperandRange>
2342 fir::SelectCaseOp::getMutableSuccessorOperands(unsigned oper) {
2343   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2344                                        getTargetOffsetAttr());
2345 }
2346 
2347 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2348 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2349                                         unsigned oper) {
2350   auto a =
2351       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2352   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2353       getOperandSegmentSizeAttr());
2354   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2355 }
2356 
2357 // parser for fir.select_case Op
2358 static mlir::ParseResult parseSelectCase(mlir::OpAsmParser &parser,
2359                                          mlir::OperationState &result) {
2360   mlir::OpAsmParser::OperandType selector;
2361   mlir::Type type;
2362   if (parseSelector(parser, result, selector, type))
2363     return mlir::failure();
2364 
2365   llvm::SmallVector<mlir::Attribute> attrs;
2366   llvm::SmallVector<mlir::OpAsmParser::OperandType> opers;
2367   llvm::SmallVector<mlir::Block *> dests;
2368   llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
2369   llvm::SmallVector<int32_t> argOffs;
2370   int32_t offSize = 0;
2371   while (true) {
2372     mlir::Attribute attr;
2373     mlir::Block *dest;
2374     llvm::SmallVector<mlir::Value> destArg;
2375     mlir::NamedAttrList temp;
2376     if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) ||
2377         parser.parseComma())
2378       return mlir::failure();
2379     attrs.push_back(attr);
2380     if (attr.dyn_cast_or_null<mlir::UnitAttr>()) {
2381       argOffs.push_back(0);
2382     } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) {
2383       mlir::OpAsmParser::OperandType oper1;
2384       mlir::OpAsmParser::OperandType oper2;
2385       if (parser.parseOperand(oper1) || parser.parseComma() ||
2386           parser.parseOperand(oper2) || parser.parseComma())
2387         return mlir::failure();
2388       opers.push_back(oper1);
2389       opers.push_back(oper2);
2390       argOffs.push_back(2);
2391       offSize += 2;
2392     } else {
2393       mlir::OpAsmParser::OperandType oper;
2394       if (parser.parseOperand(oper) || parser.parseComma())
2395         return mlir::failure();
2396       opers.push_back(oper);
2397       argOffs.push_back(1);
2398       ++offSize;
2399     }
2400     if (parser.parseSuccessorAndUseList(dest, destArg))
2401       return mlir::failure();
2402     dests.push_back(dest);
2403     destArgs.push_back(destArg);
2404     if (mlir::succeeded(parser.parseOptionalRSquare()))
2405       break;
2406     if (parser.parseComma())
2407       return mlir::failure();
2408   }
2409   result.addAttribute(fir::SelectCaseOp::getCasesAttr(),
2410                       parser.getBuilder().getArrayAttr(attrs));
2411   if (parser.resolveOperands(opers, type, result.operands))
2412     return mlir::failure();
2413   llvm::SmallVector<int32_t> targOffs;
2414   int32_t toffSize = 0;
2415   const auto count = dests.size();
2416   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2417     result.addSuccessors(dests[i]);
2418     result.addOperands(destArgs[i]);
2419     auto argSize = destArgs[i].size();
2420     targOffs.push_back(argSize);
2421     toffSize += argSize;
2422   }
2423   auto &bld = parser.getBuilder();
2424   result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(),
2425                       bld.getI32VectorAttr({1, offSize, toffSize}));
2426   result.addAttribute(getCompareOffsetAttr(), bld.getI32VectorAttr(argOffs));
2427   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(targOffs));
2428   return mlir::success();
2429 }
2430 
2431 static void print(mlir::OpAsmPrinter &p, fir::SelectCaseOp &op) {
2432   p << ' ';
2433   p.printOperand(op.getSelector());
2434   p << " : " << op.getSelector().getType() << " [";
2435   auto cases = op.getOperation()
2436                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2437                    .getValue();
2438   auto count = op.getNumConditions();
2439   for (decltype(count) i = 0; i != count; ++i) {
2440     if (i)
2441       p << ", ";
2442     p << cases[i] << ", ";
2443     if (!cases[i].isa<mlir::UnitAttr>()) {
2444       auto caseArgs = *op.getCompareOperands(i);
2445       p.printOperand(*caseArgs.begin());
2446       p << ", ";
2447       if (cases[i].isa<fir::ClosedIntervalAttr>()) {
2448         p.printOperand(*(++caseArgs.begin()));
2449         p << ", ";
2450       }
2451     }
2452     op.printSuccessorAtIndex(p, i);
2453   }
2454   p << ']';
2455   p.printOptionalAttrDict(op.getOperation()->getAttrs(),
2456                           {op.getCasesAttr(), getCompareOffsetAttr(),
2457                            getTargetOffsetAttr(),
2458                            op.getOperandSegmentSizeAttr()});
2459 }
2460 
2461 unsigned fir::SelectCaseOp::compareOffsetSize() {
2462   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2463       getCompareOffsetAttr()));
2464 }
2465 
2466 unsigned fir::SelectCaseOp::targetOffsetSize() {
2467   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2468       getTargetOffsetAttr()));
2469 }
2470 
2471 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
2472                               mlir::OperationState &result,
2473                               mlir::Value selector,
2474                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
2475                               llvm::ArrayRef<mlir::ValueRange> cmpOperands,
2476                               llvm::ArrayRef<mlir::Block *> destinations,
2477                               llvm::ArrayRef<mlir::ValueRange> destOperands,
2478                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2479   result.addOperands(selector);
2480   result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs));
2481   llvm::SmallVector<int32_t> operOffs;
2482   int32_t operSize = 0;
2483   for (auto attr : compareAttrs) {
2484     if (attr.isa<fir::ClosedIntervalAttr>()) {
2485       operOffs.push_back(2);
2486       operSize += 2;
2487     } else if (attr.isa<mlir::UnitAttr>()) {
2488       operOffs.push_back(0);
2489     } else {
2490       operOffs.push_back(1);
2491       ++operSize;
2492     }
2493   }
2494   for (auto ops : cmpOperands)
2495     result.addOperands(ops);
2496   result.addAttribute(getCompareOffsetAttr(),
2497                       builder.getI32VectorAttr(operOffs));
2498   const auto count = destinations.size();
2499   for (auto d : destinations)
2500     result.addSuccessors(d);
2501   const auto opCount = destOperands.size();
2502   llvm::SmallVector<int32_t> argOffs;
2503   int32_t sumArgs = 0;
2504   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2505     if (i < opCount) {
2506       result.addOperands(destOperands[i]);
2507       const auto argSz = destOperands[i].size();
2508       argOffs.push_back(argSz);
2509       sumArgs += argSz;
2510     } else {
2511       argOffs.push_back(0);
2512     }
2513   }
2514   result.addAttribute(getOperandSegmentSizeAttr(),
2515                       builder.getI32VectorAttr({1, operSize, sumArgs}));
2516   result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
2517   result.addAttributes(attributes);
2518 }
2519 
2520 /// This builder has a slightly simplified interface in that the list of
2521 /// operands need not be partitioned by the builder. Instead the operands are
2522 /// partitioned here, before being passed to the default builder. This
2523 /// partitioning is unchecked, so can go awry on bad input.
2524 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
2525                               mlir::OperationState &result,
2526                               mlir::Value selector,
2527                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
2528                               llvm::ArrayRef<mlir::Value> cmpOpList,
2529                               llvm::ArrayRef<mlir::Block *> destinations,
2530                               llvm::ArrayRef<mlir::ValueRange> destOperands,
2531                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2532   llvm::SmallVector<mlir::ValueRange> cmpOpers;
2533   auto iter = cmpOpList.begin();
2534   for (auto &attr : compareAttrs) {
2535     if (attr.isa<fir::ClosedIntervalAttr>()) {
2536       cmpOpers.push_back(mlir::ValueRange({iter, iter + 2}));
2537       iter += 2;
2538     } else if (attr.isa<UnitAttr>()) {
2539       cmpOpers.push_back(mlir::ValueRange{});
2540     } else {
2541       cmpOpers.push_back(mlir::ValueRange({iter, iter + 1}));
2542       ++iter;
2543     }
2544   }
2545   build(builder, result, selector, compareAttrs, cmpOpers, destinations,
2546         destOperands, attributes);
2547 }
2548 
2549 static mlir::LogicalResult verify(fir::SelectCaseOp &op) {
2550   if (!(op.getSelector().getType().isa<mlir::IntegerType>() ||
2551         op.getSelector().getType().isa<mlir::IndexType>() ||
2552         op.getSelector().getType().isa<fir::IntegerType>() ||
2553         op.getSelector().getType().isa<fir::LogicalType>() ||
2554         op.getSelector().getType().isa<fir::CharacterType>()))
2555     return op.emitOpError("must be an integer, character, or logical");
2556   auto cases = op.getOperation()
2557                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2558                    .getValue();
2559   auto count = op.getNumDest();
2560   if (count == 0)
2561     return op.emitOpError("must have at least one successor");
2562   if (op.getNumConditions() != count)
2563     return op.emitOpError("number of conditions and successors don't match");
2564   if (op.compareOffsetSize() != count)
2565     return op.emitOpError("incorrect number of compare operand groups");
2566   if (op.targetOffsetSize() != count)
2567     return op.emitOpError("incorrect number of successor operand groups");
2568   for (decltype(count) i = 0; i != count; ++i) {
2569     auto &attr = cases[i];
2570     if (!(attr.isa<fir::PointIntervalAttr>() ||
2571           attr.isa<fir::LowerBoundAttr>() || attr.isa<fir::UpperBoundAttr>() ||
2572           attr.isa<fir::ClosedIntervalAttr>() || attr.isa<mlir::UnitAttr>()))
2573       return op.emitOpError("incorrect select case attribute type");
2574   }
2575   return mlir::success();
2576 }
2577 
2578 //===----------------------------------------------------------------------===//
2579 // SelectRankOp
2580 //===----------------------------------------------------------------------===//
2581 
2582 llvm::Optional<mlir::OperandRange>
2583 fir::SelectRankOp::getCompareOperands(unsigned) {
2584   return {};
2585 }
2586 
2587 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2588 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
2589   return {};
2590 }
2591 
2592 llvm::Optional<mlir::MutableOperandRange>
2593 fir::SelectRankOp::getMutableSuccessorOperands(unsigned oper) {
2594   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2595                                        getTargetOffsetAttr());
2596 }
2597 
2598 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2599 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2600                                         unsigned oper) {
2601   auto a =
2602       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2603   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2604       getOperandSegmentSizeAttr());
2605   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2606 }
2607 
2608 unsigned fir::SelectRankOp::targetOffsetSize() {
2609   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2610       getTargetOffsetAttr()));
2611 }
2612 
2613 //===----------------------------------------------------------------------===//
2614 // SelectTypeOp
2615 //===----------------------------------------------------------------------===//
2616 
2617 llvm::Optional<mlir::OperandRange>
2618 fir::SelectTypeOp::getCompareOperands(unsigned) {
2619   return {};
2620 }
2621 
2622 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2623 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
2624   return {};
2625 }
2626 
2627 llvm::Optional<mlir::MutableOperandRange>
2628 fir::SelectTypeOp::getMutableSuccessorOperands(unsigned oper) {
2629   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
2630                                        getTargetOffsetAttr());
2631 }
2632 
2633 llvm::Optional<llvm::ArrayRef<mlir::Value>>
2634 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
2635                                         unsigned oper) {
2636   auto a =
2637       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
2638   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2639       getOperandSegmentSizeAttr());
2640   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
2641 }
2642 
2643 static ParseResult parseSelectType(OpAsmParser &parser,
2644                                    OperationState &result) {
2645   mlir::OpAsmParser::OperandType selector;
2646   mlir::Type type;
2647   if (parseSelector(parser, result, selector, type))
2648     return mlir::failure();
2649 
2650   llvm::SmallVector<mlir::Attribute> attrs;
2651   llvm::SmallVector<mlir::Block *> dests;
2652   llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
2653   while (true) {
2654     mlir::Attribute attr;
2655     mlir::Block *dest;
2656     llvm::SmallVector<mlir::Value> destArg;
2657     mlir::NamedAttrList temp;
2658     if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() ||
2659         parser.parseSuccessorAndUseList(dest, destArg))
2660       return mlir::failure();
2661     attrs.push_back(attr);
2662     dests.push_back(dest);
2663     destArgs.push_back(destArg);
2664     if (mlir::succeeded(parser.parseOptionalRSquare()))
2665       break;
2666     if (parser.parseComma())
2667       return mlir::failure();
2668   }
2669   auto &bld = parser.getBuilder();
2670   result.addAttribute(fir::SelectTypeOp::getCasesAttr(),
2671                       bld.getArrayAttr(attrs));
2672   llvm::SmallVector<int32_t> argOffs;
2673   int32_t offSize = 0;
2674   const auto count = dests.size();
2675   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2676     result.addSuccessors(dests[i]);
2677     result.addOperands(destArgs[i]);
2678     auto argSize = destArgs[i].size();
2679     argOffs.push_back(argSize);
2680     offSize += argSize;
2681   }
2682   result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(),
2683                       bld.getI32VectorAttr({1, 0, offSize}));
2684   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs));
2685   return mlir::success();
2686 }
2687 
2688 unsigned fir::SelectTypeOp::targetOffsetSize() {
2689   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
2690       getTargetOffsetAttr()));
2691 }
2692 
2693 static void print(mlir::OpAsmPrinter &p, fir::SelectTypeOp &op) {
2694   p << ' ';
2695   p.printOperand(op.getSelector());
2696   p << " : " << op.getSelector().getType() << " [";
2697   auto cases = op.getOperation()
2698                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2699                    .getValue();
2700   auto count = op.getNumConditions();
2701   for (decltype(count) i = 0; i != count; ++i) {
2702     if (i)
2703       p << ", ";
2704     p << cases[i] << ", ";
2705     op.printSuccessorAtIndex(p, i);
2706   }
2707   p << ']';
2708   p.printOptionalAttrDict(op.getOperation()->getAttrs(),
2709                           {op.getCasesAttr(), getCompareOffsetAttr(),
2710                            getTargetOffsetAttr(),
2711                            fir::SelectTypeOp::getOperandSegmentSizeAttr()});
2712 }
2713 
2714 static mlir::LogicalResult verify(fir::SelectTypeOp &op) {
2715   if (!(op.getSelector().getType().isa<fir::BoxType>()))
2716     return op.emitOpError("must be a boxed type");
2717   auto cases = op.getOperation()
2718                    ->getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr())
2719                    .getValue();
2720   auto count = op.getNumDest();
2721   if (count == 0)
2722     return op.emitOpError("must have at least one successor");
2723   if (op.getNumConditions() != count)
2724     return op.emitOpError("number of conditions and successors don't match");
2725   if (op.targetOffsetSize() != count)
2726     return op.emitOpError("incorrect number of successor operand groups");
2727   for (decltype(count) i = 0; i != count; ++i) {
2728     auto &attr = cases[i];
2729     if (!(attr.isa<fir::ExactTypeAttr>() || attr.isa<fir::SubclassAttr>() ||
2730           attr.isa<mlir::UnitAttr>()))
2731       return op.emitOpError("invalid type-case alternative");
2732   }
2733   return mlir::success();
2734 }
2735 
2736 void fir::SelectTypeOp::build(mlir::OpBuilder &builder,
2737                               mlir::OperationState &result,
2738                               mlir::Value selector,
2739                               llvm::ArrayRef<mlir::Attribute> typeOperands,
2740                               llvm::ArrayRef<mlir::Block *> destinations,
2741                               llvm::ArrayRef<mlir::ValueRange> destOperands,
2742                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2743   result.addOperands(selector);
2744   result.addAttribute(getCasesAttr(), builder.getArrayAttr(typeOperands));
2745   const auto count = destinations.size();
2746   for (mlir::Block *dest : destinations)
2747     result.addSuccessors(dest);
2748   const auto opCount = destOperands.size();
2749   llvm::SmallVector<int32_t> argOffs;
2750   int32_t sumArgs = 0;
2751   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
2752     if (i < opCount) {
2753       result.addOperands(destOperands[i]);
2754       const auto argSz = destOperands[i].size();
2755       argOffs.push_back(argSz);
2756       sumArgs += argSz;
2757     } else {
2758       argOffs.push_back(0);
2759     }
2760   }
2761   result.addAttribute(getOperandSegmentSizeAttr(),
2762                       builder.getI32VectorAttr({1, 0, sumArgs}));
2763   result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
2764   result.addAttributes(attributes);
2765 }
2766 
2767 //===----------------------------------------------------------------------===//
2768 // ShapeOp
2769 //===----------------------------------------------------------------------===//
2770 
2771 static mlir::LogicalResult verify(fir::ShapeOp &op) {
2772   auto size = op.extents().size();
2773   auto shapeTy = op.getType().dyn_cast<fir::ShapeType>();
2774   assert(shapeTy && "must be a shape type");
2775   if (shapeTy.getRank() != size)
2776     return op.emitOpError("shape type rank mismatch");
2777   return mlir::success();
2778 }
2779 
2780 //===----------------------------------------------------------------------===//
2781 // ShapeShiftOp
2782 //===----------------------------------------------------------------------===//
2783 
2784 static mlir::LogicalResult verify(fir::ShapeShiftOp &op) {
2785   auto size = op.pairs().size();
2786   if (size < 2 || size > 16 * 2)
2787     return op.emitOpError("incorrect number of args");
2788   if (size % 2 != 0)
2789     return op.emitOpError("requires a multiple of 2 args");
2790   auto shapeTy = op.getType().dyn_cast<fir::ShapeShiftType>();
2791   assert(shapeTy && "must be a shape shift type");
2792   if (shapeTy.getRank() * 2 != size)
2793     return op.emitOpError("shape type rank mismatch");
2794   return mlir::success();
2795 }
2796 
2797 //===----------------------------------------------------------------------===//
2798 // ShiftOp
2799 //===----------------------------------------------------------------------===//
2800 
2801 static mlir::LogicalResult verify(fir::ShiftOp &op) {
2802   auto size = op.origins().size();
2803   auto shiftTy = op.getType().dyn_cast<fir::ShiftType>();
2804   assert(shiftTy && "must be a shift type");
2805   if (shiftTy.getRank() != size)
2806     return op.emitOpError("shift type rank mismatch");
2807   return mlir::success();
2808 }
2809 
2810 //===----------------------------------------------------------------------===//
2811 // SliceOp
2812 //===----------------------------------------------------------------------===//
2813 
2814 /// Return the output rank of a slice op. The output rank must be between 1 and
2815 /// the rank of the array being sliced (inclusive).
2816 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) {
2817   unsigned rank = 0;
2818   if (!triples.empty()) {
2819     for (unsigned i = 1, end = triples.size(); i < end; i += 3) {
2820       auto op = triples[i].getDefiningOp();
2821       if (!mlir::isa_and_nonnull<fir::UndefOp>(op))
2822         ++rank;
2823     }
2824     assert(rank > 0);
2825   }
2826   return rank;
2827 }
2828 
2829 static mlir::LogicalResult verify(fir::SliceOp &op) {
2830   auto size = op.triples().size();
2831   if (size < 3 || size > 16 * 3)
2832     return op.emitOpError("incorrect number of args for triple");
2833   if (size % 3 != 0)
2834     return op.emitOpError("requires a multiple of 3 args");
2835   auto sliceTy = op.getType().dyn_cast<fir::SliceType>();
2836   assert(sliceTy && "must be a slice type");
2837   if (sliceTy.getRank() * 3 != size)
2838     return op.emitOpError("slice type rank mismatch");
2839   return mlir::success();
2840 }
2841 
2842 //===----------------------------------------------------------------------===//
2843 // StoreOp
2844 //===----------------------------------------------------------------------===//
2845 
2846 mlir::Type fir::StoreOp::elementType(mlir::Type refType) {
2847   return fir::dyn_cast_ptrEleTy(refType);
2848 }
2849 
2850 static mlir::ParseResult parseStoreOp(mlir::OpAsmParser &parser,
2851                                       mlir::OperationState &result) {
2852   mlir::Type type;
2853   mlir::OpAsmParser::OperandType oper;
2854   mlir::OpAsmParser::OperandType store;
2855   if (parser.parseOperand(oper) || parser.parseKeyword("to") ||
2856       parser.parseOperand(store) ||
2857       parser.parseOptionalAttrDict(result.attributes) ||
2858       parser.parseColonType(type) ||
2859       parser.resolveOperand(oper, fir::StoreOp::elementType(type),
2860                             result.operands) ||
2861       parser.resolveOperand(store, type, result.operands))
2862     return mlir::failure();
2863   return mlir::success();
2864 }
2865 
2866 static void print(mlir::OpAsmPrinter &p, fir::StoreOp &op) {
2867   p << ' ';
2868   p.printOperand(op.value());
2869   p << " to ";
2870   p.printOperand(op.memref());
2871   p.printOptionalAttrDict(op.getOperation()->getAttrs(), {});
2872   p << " : " << op.memref().getType();
2873 }
2874 
2875 static mlir::LogicalResult verify(fir::StoreOp &op) {
2876   if (op.value().getType() != fir::dyn_cast_ptrEleTy(op.memref().getType()))
2877     return op.emitOpError("store value type must match memory reference type");
2878   if (fir::isa_unknown_size_box(op.value().getType()))
2879     return op.emitOpError("cannot store !fir.box of unknown rank or type");
2880   return mlir::success();
2881 }
2882 
2883 //===----------------------------------------------------------------------===//
2884 // StringLitOp
2885 //===----------------------------------------------------------------------===//
2886 
2887 bool fir::StringLitOp::isWideValue() {
2888   auto eleTy = getType().cast<fir::SequenceType>().getEleTy();
2889   return eleTy.cast<fir::CharacterType>().getFKind() != 1;
2890 }
2891 
2892 static mlir::NamedAttribute
2893 mkNamedIntegerAttr(mlir::OpBuilder &builder, llvm::StringRef name, int64_t v) {
2894   assert(v > 0);
2895   return builder.getNamedAttr(
2896       name, builder.getIntegerAttr(builder.getIntegerType(64), v));
2897 }
2898 
2899 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2900                              fir::CharacterType inType, llvm::StringRef val,
2901                              llvm::Optional<int64_t> len) {
2902   auto valAttr = builder.getNamedAttr(value(), builder.getStringAttr(val));
2903   int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2904   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2905   result.addAttributes({valAttr, lenAttr});
2906   result.addTypes(inType);
2907 }
2908 
2909 template <typename C>
2910 static mlir::ArrayAttr convertToArrayAttr(mlir::OpBuilder &builder,
2911                                           llvm::ArrayRef<C> xlist) {
2912   llvm::SmallVector<mlir::Attribute> attrs;
2913   auto ty = builder.getIntegerType(8 * sizeof(C));
2914   for (auto ch : xlist)
2915     attrs.push_back(builder.getIntegerAttr(ty, ch));
2916   return builder.getArrayAttr(attrs);
2917 }
2918 
2919 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2920                              fir::CharacterType inType,
2921                              llvm::ArrayRef<char> vlist,
2922                              llvm::Optional<int64_t> len) {
2923   auto valAttr =
2924       builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
2925   std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2926   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2927   result.addAttributes({valAttr, lenAttr});
2928   result.addTypes(inType);
2929 }
2930 
2931 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2932                              fir::CharacterType inType,
2933                              llvm::ArrayRef<char16_t> vlist,
2934                              llvm::Optional<int64_t> len) {
2935   auto valAttr =
2936       builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
2937   std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2938   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2939   result.addAttributes({valAttr, lenAttr});
2940   result.addTypes(inType);
2941 }
2942 
2943 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result,
2944                              fir::CharacterType inType,
2945                              llvm::ArrayRef<char32_t> vlist,
2946                              llvm::Optional<int64_t> len) {
2947   auto valAttr =
2948       builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
2949   std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen();
2950   auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
2951   result.addAttributes({valAttr, lenAttr});
2952   result.addTypes(inType);
2953 }
2954 
2955 static mlir::ParseResult parseStringLitOp(mlir::OpAsmParser &parser,
2956                                           mlir::OperationState &result) {
2957   auto &builder = parser.getBuilder();
2958   mlir::Attribute val;
2959   mlir::NamedAttrList attrs;
2960   llvm::SMLoc trailingTypeLoc;
2961   if (parser.parseAttribute(val, "fake", attrs))
2962     return mlir::failure();
2963   if (auto v = val.dyn_cast<mlir::StringAttr>())
2964     result.attributes.push_back(
2965         builder.getNamedAttr(fir::StringLitOp::value(), v));
2966   else if (auto v = val.dyn_cast<mlir::ArrayAttr>())
2967     result.attributes.push_back(
2968         builder.getNamedAttr(fir::StringLitOp::xlist(), v));
2969   else
2970     return parser.emitError(parser.getCurrentLocation(),
2971                             "found an invalid constant");
2972   mlir::IntegerAttr sz;
2973   mlir::Type type;
2974   if (parser.parseLParen() ||
2975       parser.parseAttribute(sz, fir::StringLitOp::size(), result.attributes) ||
2976       parser.parseRParen() || parser.getCurrentLocation(&trailingTypeLoc) ||
2977       parser.parseColonType(type))
2978     return mlir::failure();
2979   auto charTy = type.dyn_cast<fir::CharacterType>();
2980   if (!charTy)
2981     return parser.emitError(trailingTypeLoc, "must have character type");
2982   type = fir::CharacterType::get(builder.getContext(), charTy.getFKind(),
2983                                  sz.getInt());
2984   if (!type || parser.addTypesToList(type, result.types))
2985     return mlir::failure();
2986   return mlir::success();
2987 }
2988 
2989 static void print(mlir::OpAsmPrinter &p, fir::StringLitOp &op) {
2990   p << ' ' << op.getValue() << '(';
2991   p << op.getSize().cast<mlir::IntegerAttr>().getValue() << ") : ";
2992   p.printType(op.getType());
2993 }
2994 
2995 static mlir::LogicalResult verify(fir::StringLitOp &op) {
2996   if (op.getSize().cast<mlir::IntegerAttr>().getValue().isNegative())
2997     return op.emitOpError("size must be non-negative");
2998   if (auto xl = op.getOperation()->getAttr(fir::StringLitOp::xlist())) {
2999     auto xList = xl.cast<mlir::ArrayAttr>();
3000     for (auto a : xList)
3001       if (!a.isa<mlir::IntegerAttr>())
3002         return op.emitOpError("values in list must be integers");
3003   }
3004   return mlir::success();
3005 }
3006 
3007 //===----------------------------------------------------------------------===//
3008 // UnboxProcOp
3009 //===----------------------------------------------------------------------===//
3010 
3011 static mlir::LogicalResult verify(fir::UnboxProcOp &op) {
3012   if (auto eleTy = fir::dyn_cast_ptrEleTy(op.refTuple().getType()))
3013     if (eleTy.isa<mlir::TupleType>())
3014       return mlir::success();
3015   return op.emitOpError("second output argument has bad type");
3016 }
3017 
3018 //===----------------------------------------------------------------------===//
3019 // IfOp
3020 //===----------------------------------------------------------------------===//
3021 
3022 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
3023                       mlir::Value cond, bool withElseRegion) {
3024   build(builder, result, llvm::None, cond, withElseRegion);
3025 }
3026 
3027 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
3028                       mlir::TypeRange resultTypes, mlir::Value cond,
3029                       bool withElseRegion) {
3030   result.addOperands(cond);
3031   result.addTypes(resultTypes);
3032 
3033   mlir::Region *thenRegion = result.addRegion();
3034   thenRegion->push_back(new mlir::Block());
3035   if (resultTypes.empty())
3036     IfOp::ensureTerminator(*thenRegion, builder, result.location);
3037 
3038   mlir::Region *elseRegion = result.addRegion();
3039   if (withElseRegion) {
3040     elseRegion->push_back(new mlir::Block());
3041     if (resultTypes.empty())
3042       IfOp::ensureTerminator(*elseRegion, builder, result.location);
3043   }
3044 }
3045 
3046 static mlir::ParseResult parseIfOp(OpAsmParser &parser,
3047                                    OperationState &result) {
3048   result.regions.reserve(2);
3049   mlir::Region *thenRegion = result.addRegion();
3050   mlir::Region *elseRegion = result.addRegion();
3051 
3052   auto &builder = parser.getBuilder();
3053   OpAsmParser::OperandType cond;
3054   mlir::Type i1Type = builder.getIntegerType(1);
3055   if (parser.parseOperand(cond) ||
3056       parser.resolveOperand(cond, i1Type, result.operands))
3057     return mlir::failure();
3058 
3059   if (parser.parseOptionalArrowTypeList(result.types))
3060     return mlir::failure();
3061 
3062   if (parser.parseRegion(*thenRegion, {}, {}))
3063     return mlir::failure();
3064   IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
3065 
3066   if (mlir::succeeded(parser.parseOptionalKeyword("else"))) {
3067     if (parser.parseRegion(*elseRegion, {}, {}))
3068       return mlir::failure();
3069     IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
3070   }
3071 
3072   // Parse the optional attribute list.
3073   if (parser.parseOptionalAttrDict(result.attributes))
3074     return mlir::failure();
3075   return mlir::success();
3076 }
3077 
3078 static LogicalResult verify(fir::IfOp op) {
3079   if (op.getNumResults() != 0 && op.elseRegion().empty())
3080     return op.emitOpError("must have an else block if defining values");
3081 
3082   return mlir::success();
3083 }
3084 
3085 static void print(mlir::OpAsmPrinter &p, fir::IfOp op) {
3086   bool printBlockTerminators = false;
3087   p << ' ' << op.condition();
3088   if (!op.results().empty()) {
3089     p << " -> (" << op.getResultTypes() << ')';
3090     printBlockTerminators = true;
3091   }
3092   p.printRegion(op.thenRegion(), /*printEntryBlockArgs=*/false,
3093                 printBlockTerminators);
3094 
3095   // Print the 'else' regions if it exists and has a block.
3096   auto &otherReg = op.elseRegion();
3097   if (!otherReg.empty()) {
3098     p << " else";
3099     p.printRegion(otherReg, /*printEntryBlockArgs=*/false,
3100                   printBlockTerminators);
3101   }
3102   p.printOptionalAttrDict(op->getAttrs());
3103 }
3104 
3105 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results,
3106                                   unsigned resultNum) {
3107   auto *term = thenRegion().front().getTerminator();
3108   if (resultNum < term->getNumOperands())
3109     results.push_back(term->getOperand(resultNum));
3110   term = elseRegion().front().getTerminator();
3111   if (resultNum < term->getNumOperands())
3112     results.push_back(term->getOperand(resultNum));
3113 }
3114 
3115 //===----------------------------------------------------------------------===//
3116 
3117 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) {
3118   if (attr.dyn_cast_or_null<mlir::UnitAttr>() ||
3119       attr.dyn_cast_or_null<ClosedIntervalAttr>() ||
3120       attr.dyn_cast_or_null<PointIntervalAttr>() ||
3121       attr.dyn_cast_or_null<LowerBoundAttr>() ||
3122       attr.dyn_cast_or_null<UpperBoundAttr>())
3123     return mlir::success();
3124   return mlir::failure();
3125 }
3126 
3127 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,
3128                                     unsigned dest) {
3129   unsigned o = 0;
3130   for (unsigned i = 0; i < dest; ++i) {
3131     auto &attr = cases[i];
3132     if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) {
3133       ++o;
3134       if (attr.dyn_cast_or_null<ClosedIntervalAttr>())
3135         ++o;
3136     }
3137   }
3138   return o;
3139 }
3140 
3141 mlir::ParseResult fir::parseSelector(mlir::OpAsmParser &parser,
3142                                      mlir::OperationState &result,
3143                                      mlir::OpAsmParser::OperandType &selector,
3144                                      mlir::Type &type) {
3145   if (parser.parseOperand(selector) || parser.parseColonType(type) ||
3146       parser.resolveOperand(selector, type, result.operands) ||
3147       parser.parseLSquare())
3148     return mlir::failure();
3149   return mlir::success();
3150 }
3151 
3152 /// Generic pretty-printer of a binary operation
3153 static void printBinaryOp(Operation *op, OpAsmPrinter &p) {
3154   assert(op->getNumOperands() == 2 && "binary op must have two operands");
3155   assert(op->getNumResults() == 1 && "binary op must have one result");
3156 
3157   p << ' ' << op->getOperand(0) << ", " << op->getOperand(1);
3158   p.printOptionalAttrDict(op->getAttrs());
3159   p << " : " << op->getResult(0).getType();
3160 }
3161 
3162 /// Generic pretty-printer of an unary operation
3163 static void printUnaryOp(Operation *op, OpAsmPrinter &p) {
3164   assert(op->getNumOperands() == 1 && "unary op must have one operand");
3165   assert(op->getNumResults() == 1 && "unary op must have one result");
3166 
3167   p << ' ' << op->getOperand(0);
3168   p.printOptionalAttrDict(op->getAttrs());
3169   p << " : " << op->getResult(0).getType();
3170 }
3171 
3172 bool fir::isReferenceLike(mlir::Type type) {
3173   return type.isa<fir::ReferenceType>() || type.isa<fir::HeapType>() ||
3174          type.isa<fir::PointerType>();
3175 }
3176 
3177 mlir::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module,
3178                                StringRef name, mlir::FunctionType type,
3179                                llvm::ArrayRef<mlir::NamedAttribute> attrs) {
3180   if (auto f = module.lookupSymbol<mlir::FuncOp>(name))
3181     return f;
3182   mlir::OpBuilder modBuilder(module.getBodyRegion());
3183   modBuilder.setInsertionPointToEnd(module.getBody());
3184   auto result = modBuilder.create<mlir::FuncOp>(loc, name, type, attrs);
3185   result.setVisibility(mlir::SymbolTable::Visibility::Private);
3186   return result;
3187 }
3188 
3189 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module,
3190                                   StringRef name, mlir::Type type,
3191                                   llvm::ArrayRef<mlir::NamedAttribute> attrs) {
3192   if (auto g = module.lookupSymbol<fir::GlobalOp>(name))
3193     return g;
3194   mlir::OpBuilder modBuilder(module.getBodyRegion());
3195   auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs);
3196   result.setVisibility(mlir::SymbolTable::Visibility::Private);
3197   return result;
3198 }
3199 
3200 bool fir::valueHasFirAttribute(mlir::Value value,
3201                                llvm::StringRef attributeName) {
3202   // If this is a fir.box that was loaded, the fir attributes will be on the
3203   // related fir.ref<fir.box> creation.
3204   if (value.getType().isa<fir::BoxType>())
3205     if (auto definingOp = value.getDefiningOp())
3206       if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp))
3207         value = loadOp.memref();
3208   // If this is a function argument, look in the argument attributes.
3209   if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) {
3210     if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock())
3211       if (auto funcOp =
3212               mlir::dyn_cast<mlir::FuncOp>(blockArg.getOwner()->getParentOp()))
3213         if (funcOp.getArgAttr(blockArg.getArgNumber(), attributeName))
3214           return true;
3215     return false;
3216   }
3217 
3218   if (auto definingOp = value.getDefiningOp()) {
3219     // If this is an allocated value, look at the allocation attributes.
3220     if (mlir::isa<fir::AllocMemOp>(definingOp) ||
3221         mlir::isa<AllocaOp>(definingOp))
3222       return definingOp->hasAttr(attributeName);
3223     // If this is an imported global, look at AddrOfOp and GlobalOp attributes.
3224     // Both operations are looked at because use/host associated variable (the
3225     // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate
3226     // entity (the globalOp) does not have them.
3227     if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) {
3228       if (addressOfOp->hasAttr(attributeName))
3229         return true;
3230       if (auto module = definingOp->getParentOfType<mlir::ModuleOp>())
3231         if (auto globalOp =
3232                 module.lookupSymbol<fir::GlobalOp>(addressOfOp.symbol()))
3233           return globalOp->hasAttr(attributeName);
3234     }
3235   }
3236   // TODO: Construct associated entities attributes. Decide where the fir
3237   // attributes must be placed/looked for in this case.
3238   return false;
3239 }
3240 
3241 mlir::Type fir::applyPathToType(mlir::Type eleTy, mlir::ValueRange path) {
3242   for (auto i = path.begin(), end = path.end(); eleTy && i < end;) {
3243     eleTy = llvm::TypeSwitch<mlir::Type, mlir::Type>(eleTy)
3244                 .Case<fir::RecordType>([&](fir::RecordType ty) {
3245                   if (auto *op = (*i++).getDefiningOp()) {
3246                     if (auto off = mlir::dyn_cast<fir::FieldIndexOp>(op))
3247                       return ty.getType(off.getFieldName());
3248                     if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op))
3249                       return ty.getType(fir::toInt(off));
3250                   }
3251                   return mlir::Type{};
3252                 })
3253                 .Case<fir::SequenceType>([&](fir::SequenceType ty) {
3254                   bool valid = true;
3255                   const auto rank = ty.getDimension();
3256                   for (std::remove_const_t<decltype(rank)> ii = 0;
3257                        valid && ii < rank; ++ii)
3258                     valid = i < end && fir::isa_integer((*i++).getType());
3259                   return valid ? ty.getEleTy() : mlir::Type{};
3260                 })
3261                 .Case<mlir::TupleType>([&](mlir::TupleType ty) {
3262                   if (auto *op = (*i++).getDefiningOp())
3263                     if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op))
3264                       return ty.getType(fir::toInt(off));
3265                   return mlir::Type{};
3266                 })
3267                 .Case<fir::ComplexType>([&](fir::ComplexType ty) {
3268                   if (fir::isa_integer((*i++).getType()))
3269                     return ty.getElementType();
3270                   return mlir::Type{};
3271                 })
3272                 .Case<mlir::ComplexType>([&](mlir::ComplexType ty) {
3273                   if (fir::isa_integer((*i++).getType()))
3274                     return ty.getElementType();
3275                   return mlir::Type{};
3276                 })
3277                 .Default([&](const auto &) { return mlir::Type{}; });
3278   }
3279   return eleTy;
3280 }
3281 
3282 // Tablegen operators
3283 
3284 #define GET_OP_CLASSES
3285 #include "flang/Optimizer/Dialect/FIROps.cpp.inc"
3286