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