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