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