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 "mlir/Dialect/CommonFolders.h"
18 #include "mlir/Dialect/StandardOps/IR/Ops.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/Diagnostics.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/TypeSwitch.h"
25 
26 using namespace fir;
27 
28 /// Return true if a sequence type is of some incomplete size or a record type
29 /// is malformed or contains an incomplete sequence type. An incomplete sequence
30 /// type is one with more unknown extents in the type than have been provided
31 /// via `dynamicExtents`. Sequence types with an unknown rank are incomplete by
32 /// definition.
33 static bool verifyInType(mlir::Type inType,
34                          llvm::SmallVectorImpl<llvm::StringRef> &visited,
35                          unsigned dynamicExtents = 0) {
36   if (auto st = inType.dyn_cast<fir::SequenceType>()) {
37     auto shape = st.getShape();
38     if (shape.size() == 0)
39       return true;
40     for (std::size_t i = 0, end{shape.size()}; i < end; ++i) {
41       if (shape[i] != fir::SequenceType::getUnknownExtent())
42         continue;
43       if (dynamicExtents-- == 0)
44         return true;
45     }
46   } else if (auto rt = inType.dyn_cast<fir::RecordType>()) {
47     // don't recurse if we're already visiting this one
48     if (llvm::is_contained(visited, rt.getName()))
49       return false;
50     // keep track of record types currently being visited
51     visited.push_back(rt.getName());
52     for (auto &field : rt.getTypeList())
53       if (verifyInType(field.second, visited))
54         return true;
55     visited.pop_back();
56   } else if (auto rt = inType.dyn_cast<fir::PointerType>()) {
57     return verifyInType(rt.getEleTy(), visited);
58   }
59   return false;
60 }
61 
62 static bool verifyRecordLenParams(mlir::Type inType, unsigned numLenParams) {
63   if (numLenParams > 0) {
64     if (auto rt = inType.dyn_cast<fir::RecordType>())
65       return numLenParams != rt.getNumLenParams();
66     return true;
67   }
68   return false;
69 }
70 
71 //===----------------------------------------------------------------------===//
72 // AllocaOp
73 //===----------------------------------------------------------------------===//
74 
75 mlir::Type fir::AllocaOp::getAllocatedType() {
76   return getType().cast<ReferenceType>().getEleTy();
77 }
78 
79 /// Create a legal memory reference as return type
80 mlir::Type fir::AllocaOp::wrapResultType(mlir::Type intype) {
81   // FIR semantics: memory references to memory references are disallowed
82   if (intype.isa<ReferenceType>())
83     return {};
84   return ReferenceType::get(intype);
85 }
86 
87 mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) {
88   return ReferenceType::get(ty);
89 }
90 
91 //===----------------------------------------------------------------------===//
92 // AllocMemOp
93 //===----------------------------------------------------------------------===//
94 
95 mlir::Type fir::AllocMemOp::getAllocatedType() {
96   return getType().cast<HeapType>().getEleTy();
97 }
98 
99 mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) {
100   return HeapType::get(ty);
101 }
102 
103 /// Create a legal heap reference as return type
104 mlir::Type fir::AllocMemOp::wrapResultType(mlir::Type intype) {
105   // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER
106   // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well
107   // FIR semantics: one may not allocate a memory reference value
108   if (intype.isa<ReferenceType>() || intype.isa<HeapType>() ||
109       intype.isa<PointerType>() || intype.isa<FunctionType>())
110     return {};
111   return HeapType::get(intype);
112 }
113 
114 //===----------------------------------------------------------------------===//
115 // ArrayCoorOp
116 //===----------------------------------------------------------------------===//
117 
118 static mlir::LogicalResult verify(fir::ArrayCoorOp op) {
119   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
120   auto arrTy = eleTy.dyn_cast<fir::SequenceType>();
121   if (!arrTy)
122     return op.emitOpError("must be a reference to an array");
123   auto arrDim = arrTy.getDimension();
124 
125   if (auto shapeOp = op.shape()) {
126     auto shapeTy = shapeOp.getType();
127     unsigned shapeTyRank = 0;
128     if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) {
129       shapeTyRank = s.getRank();
130     } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) {
131       shapeTyRank = ss.getRank();
132     } else {
133       auto s = shapeTy.cast<fir::ShiftType>();
134       shapeTyRank = s.getRank();
135       if (!op.memref().getType().isa<fir::BoxType>())
136         return op.emitOpError("shift can only be provided with fir.box memref");
137     }
138     if (arrDim && arrDim != shapeTyRank)
139       return op.emitOpError("rank of dimension mismatched");
140     if (shapeTyRank != op.indices().size())
141       return op.emitOpError("number of indices do not match dim rank");
142   }
143 
144   if (auto sliceOp = op.slice())
145     if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>())
146       if (sliceTy.getRank() != arrDim)
147         return op.emitOpError("rank of dimension in slice mismatched");
148 
149   return mlir::success();
150 }
151 
152 //===----------------------------------------------------------------------===//
153 // ArrayLoadOp
154 //===----------------------------------------------------------------------===//
155 
156 std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() {
157   if (auto sh = shape())
158     if (auto *op = sh.getDefiningOp()) {
159       if (auto shOp = dyn_cast<fir::ShapeOp>(op))
160         return shOp.getExtents();
161       return cast<fir::ShapeShiftOp>(op).getExtents();
162     }
163   return {};
164 }
165 
166 static mlir::LogicalResult verify(fir::ArrayLoadOp op) {
167   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
168   auto arrTy = eleTy.dyn_cast<fir::SequenceType>();
169   if (!arrTy)
170     return op.emitOpError("must be a reference to an array");
171   auto arrDim = arrTy.getDimension();
172 
173   if (auto shapeOp = op.shape()) {
174     auto shapeTy = shapeOp.getType();
175     unsigned shapeTyRank = 0;
176     if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) {
177       shapeTyRank = s.getRank();
178     } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) {
179       shapeTyRank = ss.getRank();
180     } else {
181       auto s = shapeTy.cast<fir::ShiftType>();
182       shapeTyRank = s.getRank();
183       if (!op.memref().getType().isa<fir::BoxType>())
184         return op.emitOpError("shift can only be provided with fir.box memref");
185     }
186     if (arrDim && arrDim != shapeTyRank)
187       return op.emitOpError("rank of dimension mismatched");
188   }
189 
190   if (auto sliceOp = op.slice())
191     if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>())
192       if (sliceTy.getRank() != arrDim)
193         return op.emitOpError("rank of dimension in slice mismatched");
194 
195   return mlir::success();
196 }
197 
198 //===----------------------------------------------------------------------===//
199 // BoxAddrOp
200 //===----------------------------------------------------------------------===//
201 
202 mlir::OpFoldResult fir::BoxAddrOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
203   if (auto v = val().getDefiningOp()) {
204     if (auto box = dyn_cast<fir::EmboxOp>(v))
205       return box.memref();
206     if (auto box = dyn_cast<fir::EmboxCharOp>(v))
207       return box.memref();
208   }
209   return {};
210 }
211 
212 //===----------------------------------------------------------------------===//
213 // BoxCharLenOp
214 //===----------------------------------------------------------------------===//
215 
216 mlir::OpFoldResult
217 fir::BoxCharLenOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
218   if (auto v = val().getDefiningOp()) {
219     if (auto box = dyn_cast<fir::EmboxCharOp>(v))
220       return box.len();
221   }
222   return {};
223 }
224 
225 //===----------------------------------------------------------------------===//
226 // BoxDimsOp
227 //===----------------------------------------------------------------------===//
228 
229 /// Get the result types packed in a tuple tuple
230 mlir::Type fir::BoxDimsOp::getTupleType() {
231   // note: triple, but 4 is nearest power of 2
232   llvm::SmallVector<mlir::Type, 4> triple{
233       getResult(0).getType(), getResult(1).getType(), getResult(2).getType()};
234   return mlir::TupleType::get(getContext(), triple);
235 }
236 
237 //===----------------------------------------------------------------------===//
238 // CallOp
239 //===----------------------------------------------------------------------===//
240 
241 mlir::FunctionType fir::CallOp::getFunctionType() {
242   return mlir::FunctionType::get(getContext(), getOperandTypes(),
243                                  getResultTypes());
244 }
245 
246 static void printCallOp(mlir::OpAsmPrinter &p, fir::CallOp &op) {
247   auto callee = op.callee();
248   bool isDirect = callee.hasValue();
249   p << ' ';
250   if (isDirect)
251     p << callee.getValue();
252   else
253     p << op.getOperand(0);
254   p << '(' << op->getOperands().drop_front(isDirect ? 0 : 1) << ')';
255   p.printOptionalAttrDict(op->getAttrs(), {"callee"});
256   auto resultTypes{op.getResultTypes()};
257   llvm::SmallVector<Type, 8> argTypes(
258       llvm::drop_begin(op.getOperandTypes(), isDirect ? 0 : 1));
259   p << " : " << FunctionType::get(op.getContext(), argTypes, resultTypes);
260 }
261 
262 static mlir::ParseResult parseCallOp(mlir::OpAsmParser &parser,
263                                      mlir::OperationState &result) {
264   llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> operands;
265   if (parser.parseOperandList(operands))
266     return mlir::failure();
267 
268   mlir::NamedAttrList attrs;
269   mlir::SymbolRefAttr funcAttr;
270   bool isDirect = operands.empty();
271   if (isDirect)
272     if (parser.parseAttribute(funcAttr, "callee", attrs))
273       return mlir::failure();
274 
275   Type type;
276   if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) ||
277       parser.parseOptionalAttrDict(attrs) || parser.parseColon() ||
278       parser.parseType(type))
279     return mlir::failure();
280 
281   auto funcType = type.dyn_cast<mlir::FunctionType>();
282   if (!funcType)
283     return parser.emitError(parser.getNameLoc(), "expected function type");
284   if (isDirect) {
285     if (parser.resolveOperands(operands, funcType.getInputs(),
286                                parser.getNameLoc(), result.operands))
287       return mlir::failure();
288   } else {
289     auto funcArgs =
290         llvm::ArrayRef<mlir::OpAsmParser::OperandType>(operands).drop_front();
291     if (parser.resolveOperand(operands[0], funcType, result.operands) ||
292         parser.resolveOperands(funcArgs, funcType.getInputs(),
293                                parser.getNameLoc(), result.operands))
294       return mlir::failure();
295   }
296   result.addTypes(funcType.getResults());
297   result.attributes = attrs;
298   return mlir::success();
299 }
300 
301 //===----------------------------------------------------------------------===//
302 // CmpOp
303 //===----------------------------------------------------------------------===//
304 
305 template <typename OPTY>
306 static void printCmpOp(OpAsmPrinter &p, OPTY op) {
307   p << ' ';
308   auto predSym = mlir::symbolizeCmpFPredicate(
309       op->template getAttrOfType<mlir::IntegerAttr>(
310             OPTY::getPredicateAttrName())
311           .getInt());
312   assert(predSym.hasValue() && "invalid symbol value for predicate");
313   p << '"' << mlir::stringifyCmpFPredicate(predSym.getValue()) << '"' << ", ";
314   p.printOperand(op.lhs());
315   p << ", ";
316   p.printOperand(op.rhs());
317   p.printOptionalAttrDict(op->getAttrs(),
318                           /*elidedAttrs=*/{OPTY::getPredicateAttrName()});
319   p << " : " << op.lhs().getType();
320 }
321 
322 template <typename OPTY>
323 static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser,
324                                     mlir::OperationState &result) {
325   llvm::SmallVector<mlir::OpAsmParser::OperandType, 2> ops;
326   mlir::NamedAttrList attrs;
327   mlir::Attribute predicateNameAttr;
328   mlir::Type type;
329   if (parser.parseAttribute(predicateNameAttr, OPTY::getPredicateAttrName(),
330                             attrs) ||
331       parser.parseComma() || parser.parseOperandList(ops, 2) ||
332       parser.parseOptionalAttrDict(attrs) || parser.parseColonType(type) ||
333       parser.resolveOperands(ops, type, result.operands))
334     return failure();
335 
336   if (!predicateNameAttr.isa<mlir::StringAttr>())
337     return parser.emitError(parser.getNameLoc(),
338                             "expected string comparison predicate attribute");
339 
340   // Rewrite string attribute to an enum value.
341   llvm::StringRef predicateName =
342       predicateNameAttr.cast<mlir::StringAttr>().getValue();
343   auto predicate = fir::CmpcOp::getPredicateByName(predicateName);
344   auto builder = parser.getBuilder();
345   mlir::Type i1Type = builder.getI1Type();
346   attrs.set(OPTY::getPredicateAttrName(),
347             builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
348   result.attributes = attrs;
349   result.addTypes({i1Type});
350   return success();
351 }
352 
353 //===----------------------------------------------------------------------===//
354 // CmpcOp
355 //===----------------------------------------------------------------------===//
356 
357 void fir::buildCmpCOp(OpBuilder &builder, OperationState &result,
358                       CmpFPredicate predicate, Value lhs, Value rhs) {
359   result.addOperands({lhs, rhs});
360   result.types.push_back(builder.getI1Type());
361   result.addAttribute(
362       fir::CmpcOp::getPredicateAttrName(),
363       builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
364 }
365 
366 mlir::CmpFPredicate fir::CmpcOp::getPredicateByName(llvm::StringRef name) {
367   auto pred = mlir::symbolizeCmpFPredicate(name);
368   assert(pred.hasValue() && "invalid predicate name");
369   return pred.getValue();
370 }
371 
372 static void printCmpcOp(OpAsmPrinter &p, fir::CmpcOp op) { printCmpOp(p, op); }
373 
374 mlir::ParseResult fir::parseCmpcOp(mlir::OpAsmParser &parser,
375                                    mlir::OperationState &result) {
376   return parseCmpOp<fir::CmpcOp>(parser, result);
377 }
378 
379 //===----------------------------------------------------------------------===//
380 // ConvertOp
381 //===----------------------------------------------------------------------===//
382 
383 void fir::ConvertOp::getCanonicalizationPatterns(
384     OwningRewritePatternList &results, MLIRContext *context) {}
385 
386 mlir::OpFoldResult fir::ConvertOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
387   if (value().getType() == getType())
388     return value();
389   if (matchPattern(value(), m_Op<fir::ConvertOp>())) {
390     auto inner = cast<fir::ConvertOp>(value().getDefiningOp());
391     // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a
392     if (auto toTy = getType().dyn_cast<fir::LogicalType>())
393       if (auto fromTy = inner.value().getType().dyn_cast<fir::LogicalType>())
394         if (inner.getType().isa<mlir::IntegerType>() && (toTy == fromTy))
395           return inner.value();
396     // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a
397     if (auto toTy = getType().dyn_cast<mlir::IntegerType>())
398       if (auto fromTy = inner.value().getType().dyn_cast<mlir::IntegerType>())
399         if (inner.getType().isa<fir::LogicalType>() && (toTy == fromTy) &&
400             (fromTy.getWidth() == 1))
401           return inner.value();
402   }
403   return {};
404 }
405 
406 bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) {
407   return ty.isa<mlir::IntegerType>() || ty.isa<mlir::IndexType>() ||
408          ty.isa<fir::IntegerType>() || ty.isa<fir::LogicalType>();
409 }
410 
411 bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) {
412   return ty.isa<mlir::FloatType>() || ty.isa<fir::RealType>();
413 }
414 
415 bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) {
416   return ty.isa<fir::ReferenceType>() || ty.isa<fir::PointerType>() ||
417          ty.isa<fir::HeapType>() || ty.isa<mlir::MemRefType>() ||
418          ty.isa<mlir::FunctionType>() || ty.isa<fir::TypeDescType>();
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // CoordinateOp
423 //===----------------------------------------------------------------------===//
424 
425 static void print(mlir::OpAsmPrinter &p, fir::CoordinateOp op) {
426   p << ' ' << op.ref() << ", " << op.coor();
427   p.printOptionalAttrDict(op->getAttrs(), /*elideAttrs=*/{"baseType"});
428   p << " : ";
429   p.printFunctionalType(op.getOperandTypes(), op->getResultTypes());
430 }
431 
432 static mlir::ParseResult parseCoordinateCustom(mlir::OpAsmParser &parser,
433                                                mlir::OperationState &result) {
434   mlir::OpAsmParser::OperandType memref;
435   if (parser.parseOperand(memref) || parser.parseComma())
436     return mlir::failure();
437   llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> coorOperands;
438   if (parser.parseOperandList(coorOperands))
439     return mlir::failure();
440   llvm::SmallVector<mlir::OpAsmParser::OperandType, 16> allOperands;
441   allOperands.push_back(memref);
442   allOperands.append(coorOperands.begin(), coorOperands.end());
443   mlir::FunctionType funcTy;
444   auto loc = parser.getCurrentLocation();
445   if (parser.parseOptionalAttrDict(result.attributes) ||
446       parser.parseColonType(funcTy) ||
447       parser.resolveOperands(allOperands, funcTy.getInputs(), loc,
448                              result.operands))
449     return failure();
450   parser.addTypesToList(funcTy.getResults(), result.types);
451   result.addAttribute("baseType", mlir::TypeAttr::get(funcTy.getInput(0)));
452   return mlir::success();
453 }
454 
455 static mlir::LogicalResult verify(fir::CoordinateOp op) {
456   auto refTy = op.ref().getType();
457   if (fir::isa_ref_type(refTy)) {
458     auto eleTy = fir::dyn_cast_ptrEleTy(refTy);
459     if (auto arrTy = eleTy.dyn_cast<fir::SequenceType>()) {
460       if (arrTy.hasUnknownShape())
461         return op.emitOpError("cannot find coordinate in unknown shape");
462       if (arrTy.getConstantRows() < arrTy.getDimension() - 1)
463         return op.emitOpError("cannot find coordinate with unknown extents");
464     }
465     if (!(fir::isa_aggregate(eleTy) || fir::isa_complex(eleTy) ||
466           fir::isa_char_string(eleTy)))
467       return op.emitOpError("cannot apply coordinate_of to this type");
468   }
469   // Recovering a LEN type parameter only makes sense from a boxed value. For a
470   // bare reference, the LEN type parameters must be passed as additional
471   // arguments to `op`.
472   for (auto co : op.coor())
473     if (dyn_cast_or_null<fir::LenParamIndexOp>(co.getDefiningOp())) {
474       if (op.getNumOperands() != 2)
475         return op.emitOpError("len_param_index must be last argument");
476       if (!op.ref().getType().isa<BoxType>())
477         return op.emitOpError("len_param_index must be used on box type");
478     }
479   return mlir::success();
480 }
481 
482 //===----------------------------------------------------------------------===//
483 // DispatchOp
484 //===----------------------------------------------------------------------===//
485 
486 mlir::FunctionType fir::DispatchOp::getFunctionType() {
487   return mlir::FunctionType::get(getContext(), getOperandTypes(),
488                                  getResultTypes());
489 }
490 
491 //===----------------------------------------------------------------------===//
492 // DispatchTableOp
493 //===----------------------------------------------------------------------===//
494 
495 void fir::DispatchTableOp::appendTableEntry(mlir::Operation *op) {
496   assert(mlir::isa<fir::DTEntryOp>(*op) && "operation must be a DTEntryOp");
497   auto &block = getBlock();
498   block.getOperations().insert(block.end(), op);
499 }
500 
501 //===----------------------------------------------------------------------===//
502 // EmboxOp
503 //===----------------------------------------------------------------------===//
504 
505 static mlir::LogicalResult verify(fir::EmboxOp op) {
506   auto eleTy = fir::dyn_cast_ptrEleTy(op.memref().getType());
507   bool isArray = false;
508   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) {
509     eleTy = seqTy.getEleTy();
510     isArray = true;
511   }
512   if (op.hasLenParams()) {
513     auto lenPs = op.numLenParams();
514     if (auto rt = eleTy.dyn_cast<fir::RecordType>()) {
515       if (lenPs != rt.getNumLenParams())
516         return op.emitOpError("number of LEN params does not correspond"
517                               " to the !fir.type type");
518     } else if (auto strTy = eleTy.dyn_cast<fir::CharacterType>()) {
519       if (strTy.getLen() != fir::CharacterType::unknownLen())
520         return op.emitOpError("CHARACTER already has static LEN");
521     } else {
522       return op.emitOpError("LEN parameters require CHARACTER or derived type");
523     }
524     for (auto lp : op.lenParams())
525       if (!fir::isa_integer(lp.getType()))
526         return op.emitOpError("LEN parameters must be integral type");
527   }
528   if (op.getShape() && !isArray)
529     return op.emitOpError("shape must not be provided for a scalar");
530   if (op.getSlice() && !isArray)
531     return op.emitOpError("slice must not be provided for a scalar");
532   return mlir::success();
533 }
534 
535 //===----------------------------------------------------------------------===//
536 // GenTypeDescOp
537 //===----------------------------------------------------------------------===//
538 
539 void fir::GenTypeDescOp::build(OpBuilder &, OperationState &result,
540                                mlir::TypeAttr inty) {
541   result.addAttribute("in_type", inty);
542   result.addTypes(TypeDescType::get(inty.getValue()));
543 }
544 
545 //===----------------------------------------------------------------------===//
546 // GlobalOp
547 //===----------------------------------------------------------------------===//
548 
549 static ParseResult parseGlobalOp(OpAsmParser &parser, OperationState &result) {
550   // Parse the optional linkage
551   llvm::StringRef linkage;
552   auto &builder = parser.getBuilder();
553   if (mlir::succeeded(parser.parseOptionalKeyword(&linkage))) {
554     if (fir::GlobalOp::verifyValidLinkage(linkage))
555       return mlir::failure();
556     mlir::StringAttr linkAttr = builder.getStringAttr(linkage);
557     result.addAttribute(fir::GlobalOp::linkageAttrName(), linkAttr);
558   }
559 
560   // Parse the name as a symbol reference attribute.
561   mlir::SymbolRefAttr nameAttr;
562   if (parser.parseAttribute(nameAttr, fir::GlobalOp::symbolAttrName(),
563                             result.attributes))
564     return mlir::failure();
565   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
566                       nameAttr.getRootReference());
567 
568   bool simpleInitializer = false;
569   if (mlir::succeeded(parser.parseOptionalLParen())) {
570     Attribute attr;
571     if (parser.parseAttribute(attr, "initVal", result.attributes) ||
572         parser.parseRParen())
573       return mlir::failure();
574     simpleInitializer = true;
575   }
576 
577   if (succeeded(parser.parseOptionalKeyword("constant"))) {
578     // if "constant" keyword then mark this as a constant, not a variable
579     result.addAttribute("constant", builder.getUnitAttr());
580   }
581 
582   mlir::Type globalType;
583   if (parser.parseColonType(globalType))
584     return mlir::failure();
585 
586   result.addAttribute(fir::GlobalOp::typeAttrName(result.name),
587                       mlir::TypeAttr::get(globalType));
588 
589   if (simpleInitializer) {
590     result.addRegion();
591   } else {
592     // Parse the optional initializer body.
593     auto parseResult = parser.parseOptionalRegion(
594         *result.addRegion(), /*arguments=*/llvm::None, /*argTypes=*/llvm::None);
595     if (parseResult.hasValue() && mlir::failed(*parseResult))
596       return mlir::failure();
597   }
598 
599   return mlir::success();
600 }
601 
602 void fir::GlobalOp::appendInitialValue(mlir::Operation *op) {
603   getBlock().getOperations().push_back(op);
604 }
605 
606 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
607                           StringRef name, bool isConstant, Type type,
608                           Attribute initialVal, StringAttr linkage,
609                           ArrayRef<NamedAttribute> attrs) {
610   result.addRegion();
611   result.addAttribute(typeAttrName(result.name), mlir::TypeAttr::get(type));
612   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
613                       builder.getStringAttr(name));
614   result.addAttribute(symbolAttrName(),
615                       SymbolRefAttr::get(builder.getContext(), name));
616   if (isConstant)
617     result.addAttribute(constantAttrName(result.name), builder.getUnitAttr());
618   if (initialVal)
619     result.addAttribute(initValAttrName(result.name), initialVal);
620   if (linkage)
621     result.addAttribute(linkageAttrName(), linkage);
622   result.attributes.append(attrs.begin(), attrs.end());
623 }
624 
625 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
626                           StringRef name, Type type, Attribute initialVal,
627                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
628   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
629 }
630 
631 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
632                           StringRef name, bool isConstant, Type type,
633                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
634   build(builder, result, name, isConstant, type, {}, linkage, attrs);
635 }
636 
637 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
638                           StringRef name, Type type, StringAttr linkage,
639                           ArrayRef<NamedAttribute> attrs) {
640   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
641 }
642 
643 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
644                           StringRef name, bool isConstant, Type type,
645                           ArrayRef<NamedAttribute> attrs) {
646   build(builder, result, name, isConstant, type, StringAttr{}, attrs);
647 }
648 
649 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
650                           StringRef name, Type type,
651                           ArrayRef<NamedAttribute> attrs) {
652   build(builder, result, name, /*isConstant=*/false, type, attrs);
653 }
654 
655 mlir::ParseResult fir::GlobalOp::verifyValidLinkage(StringRef linkage) {
656   // Supporting only a subset of the LLVM linkage types for now
657   static const char *validNames[] = {"common", "internal", "linkonce", "weak"};
658   return mlir::success(llvm::is_contained(validNames, linkage));
659 }
660 
661 //===----------------------------------------------------------------------===//
662 // InsertValueOp
663 //===----------------------------------------------------------------------===//
664 
665 static bool checkIsIntegerConstant(mlir::Value v, int64_t conVal) {
666   if (auto c = dyn_cast_or_null<mlir::ConstantOp>(v.getDefiningOp())) {
667     auto attr = c.getValue();
668     if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>())
669       return iattr.getInt() == conVal;
670   }
671   return false;
672 }
673 static bool isZero(mlir::Value v) { return checkIsIntegerConstant(v, 0); }
674 static bool isOne(mlir::Value v) { return checkIsIntegerConstant(v, 1); }
675 
676 // Undo some complex patterns created in the front-end and turn them back into
677 // complex ops.
678 template <typename FltOp, typename CpxOp>
679 struct UndoComplexPattern : public mlir::RewritePattern {
680   UndoComplexPattern(mlir::MLIRContext *ctx)
681       : mlir::RewritePattern("fir.insert_value", 2, ctx) {}
682 
683   mlir::LogicalResult
684   matchAndRewrite(mlir::Operation *op,
685                   mlir::PatternRewriter &rewriter) const override {
686     auto insval = dyn_cast_or_null<fir::InsertValueOp>(op);
687     if (!insval || !insval.getType().isa<fir::ComplexType>())
688       return mlir::failure();
689     auto insval2 =
690         dyn_cast_or_null<fir::InsertValueOp>(insval.adt().getDefiningOp());
691     if (!insval2 || !isa<fir::UndefOp>(insval2.adt().getDefiningOp()))
692       return mlir::failure();
693     auto binf = dyn_cast_or_null<FltOp>(insval.val().getDefiningOp());
694     auto binf2 = dyn_cast_or_null<FltOp>(insval2.val().getDefiningOp());
695     if (!binf || !binf2 || insval.coor().size() != 1 ||
696         !isOne(insval.coor()[0]) || insval2.coor().size() != 1 ||
697         !isZero(insval2.coor()[0]))
698       return mlir::failure();
699     auto eai =
700         dyn_cast_or_null<fir::ExtractValueOp>(binf.lhs().getDefiningOp());
701     auto ebi =
702         dyn_cast_or_null<fir::ExtractValueOp>(binf.rhs().getDefiningOp());
703     auto ear =
704         dyn_cast_or_null<fir::ExtractValueOp>(binf2.lhs().getDefiningOp());
705     auto ebr =
706         dyn_cast_or_null<fir::ExtractValueOp>(binf2.rhs().getDefiningOp());
707     if (!eai || !ebi || !ear || !ebr || ear.adt() != eai.adt() ||
708         ebr.adt() != ebi.adt() || eai.coor().size() != 1 ||
709         !isOne(eai.coor()[0]) || ebi.coor().size() != 1 ||
710         !isOne(ebi.coor()[0]) || ear.coor().size() != 1 ||
711         !isZero(ear.coor()[0]) || ebr.coor().size() != 1 ||
712         !isZero(ebr.coor()[0]))
713       return mlir::failure();
714     rewriter.replaceOpWithNewOp<CpxOp>(op, ear.adt(), ebr.adt());
715     return mlir::success();
716   }
717 };
718 
719 void fir::InsertValueOp::getCanonicalizationPatterns(
720     mlir::OwningRewritePatternList &results, mlir::MLIRContext *context) {
721   results.insert<UndoComplexPattern<mlir::AddFOp, fir::AddcOp>,
722                  UndoComplexPattern<mlir::SubFOp, fir::SubcOp>>(context);
723 }
724 
725 //===----------------------------------------------------------------------===//
726 // IterWhileOp
727 //===----------------------------------------------------------------------===//
728 
729 void fir::IterWhileOp::build(mlir::OpBuilder &builder,
730                              mlir::OperationState &result, mlir::Value lb,
731                              mlir::Value ub, mlir::Value step,
732                              mlir::Value iterate, bool finalCountValue,
733                              mlir::ValueRange iterArgs,
734                              llvm::ArrayRef<mlir::NamedAttribute> attributes) {
735   result.addOperands({lb, ub, step, iterate});
736   if (finalCountValue) {
737     result.addTypes(builder.getIndexType());
738     result.addAttribute(finalValueAttrName(result.name), builder.getUnitAttr());
739   }
740   result.addTypes(iterate.getType());
741   result.addOperands(iterArgs);
742   for (auto v : iterArgs)
743     result.addTypes(v.getType());
744   mlir::Region *bodyRegion = result.addRegion();
745   bodyRegion->push_back(new Block{});
746   bodyRegion->front().addArgument(builder.getIndexType());
747   bodyRegion->front().addArgument(iterate.getType());
748   bodyRegion->front().addArguments(iterArgs.getTypes());
749   result.addAttributes(attributes);
750 }
751 
752 static mlir::ParseResult parseIterWhileOp(mlir::OpAsmParser &parser,
753                                           mlir::OperationState &result) {
754   auto &builder = parser.getBuilder();
755   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
756   if (parser.parseLParen() || parser.parseRegionArgument(inductionVariable) ||
757       parser.parseEqual())
758     return mlir::failure();
759 
760   // Parse loop bounds.
761   auto indexType = builder.getIndexType();
762   auto i1Type = builder.getIntegerType(1);
763   if (parser.parseOperand(lb) ||
764       parser.resolveOperand(lb, indexType, result.operands) ||
765       parser.parseKeyword("to") || parser.parseOperand(ub) ||
766       parser.resolveOperand(ub, indexType, result.operands) ||
767       parser.parseKeyword("step") || parser.parseOperand(step) ||
768       parser.parseRParen() ||
769       parser.resolveOperand(step, indexType, result.operands))
770     return mlir::failure();
771 
772   mlir::OpAsmParser::OperandType iterateVar, iterateInput;
773   if (parser.parseKeyword("and") || parser.parseLParen() ||
774       parser.parseRegionArgument(iterateVar) || parser.parseEqual() ||
775       parser.parseOperand(iterateInput) || parser.parseRParen() ||
776       parser.resolveOperand(iterateInput, i1Type, result.operands))
777     return mlir::failure();
778 
779   // Parse the initial iteration arguments.
780   llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> regionArgs;
781   auto prependCount = false;
782 
783   // Induction variable.
784   regionArgs.push_back(inductionVariable);
785   regionArgs.push_back(iterateVar);
786 
787   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
788     llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> operands;
789     llvm::SmallVector<mlir::Type, 4> regionTypes;
790     // Parse assignment list and results type list.
791     if (parser.parseAssignmentList(regionArgs, operands) ||
792         parser.parseArrowTypeList(regionTypes))
793       return failure();
794     if (regionTypes.size() == operands.size() + 2)
795       prependCount = true;
796     llvm::ArrayRef<mlir::Type> resTypes = regionTypes;
797     resTypes = prependCount ? resTypes.drop_front(2) : resTypes;
798     // Resolve input operands.
799     for (auto operand_type : llvm::zip(operands, resTypes))
800       if (parser.resolveOperand(std::get<0>(operand_type),
801                                 std::get<1>(operand_type), result.operands))
802         return failure();
803     if (prependCount) {
804       result.addTypes(regionTypes);
805     } else {
806       result.addTypes(i1Type);
807       result.addTypes(resTypes);
808     }
809   } else if (succeeded(parser.parseOptionalArrow())) {
810     llvm::SmallVector<mlir::Type, 4> typeList;
811     if (parser.parseLParen() || parser.parseTypeList(typeList) ||
812         parser.parseRParen())
813       return failure();
814     // Type list must be "(index, i1)".
815     if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() ||
816         !typeList[1].isSignlessInteger(1))
817       return failure();
818     result.addTypes(typeList);
819     prependCount = true;
820   } else {
821     result.addTypes(i1Type);
822   }
823 
824   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
825     return mlir::failure();
826 
827   llvm::SmallVector<mlir::Type, 4> argTypes;
828   // Induction variable (hidden)
829   if (prependCount)
830     result.addAttribute(IterWhileOp::finalValueAttrName(result.name),
831                         builder.getUnitAttr());
832   else
833     argTypes.push_back(indexType);
834   // Loop carried variables (including iterate)
835   argTypes.append(result.types.begin(), result.types.end());
836   // Parse the body region.
837   auto *body = result.addRegion();
838   if (regionArgs.size() != argTypes.size())
839     return parser.emitError(
840         parser.getNameLoc(),
841         "mismatch in number of loop-carried values and defined values");
842 
843   if (parser.parseRegion(*body, regionArgs, argTypes))
844     return failure();
845 
846   fir::IterWhileOp::ensureTerminator(*body, builder, result.location);
847 
848   return mlir::success();
849 }
850 
851 static mlir::LogicalResult verify(fir::IterWhileOp op) {
852   // Check that the body defines as single block argument for the induction
853   // variable.
854   auto *body = op.getBody();
855   if (!body->getArgument(1).getType().isInteger(1))
856     return op.emitOpError(
857         "expected body second argument to be an index argument for "
858         "the induction variable");
859   if (!body->getArgument(0).getType().isIndex())
860     return op.emitOpError(
861         "expected body first argument to be an index argument for "
862         "the induction variable");
863 
864   auto opNumResults = op.getNumResults();
865   if (op.finalValue()) {
866     // Result type must be "(index, i1, ...)".
867     if (!op.getResult(0).getType().isa<mlir::IndexType>())
868       return op.emitOpError("result #0 expected to be index");
869     if (!op.getResult(1).getType().isSignlessInteger(1))
870       return op.emitOpError("result #1 expected to be i1");
871     opNumResults--;
872   } else {
873     // iterate_while always returns the early exit induction value.
874     // Result type must be "(i1, ...)"
875     if (!op.getResult(0).getType().isSignlessInteger(1))
876       return op.emitOpError("result #0 expected to be i1");
877   }
878   if (opNumResults == 0)
879     return mlir::failure();
880   if (op.getNumIterOperands() != opNumResults)
881     return op.emitOpError(
882         "mismatch in number of loop-carried values and defined values");
883   if (op.getNumRegionIterArgs() != opNumResults)
884     return op.emitOpError(
885         "mismatch in number of basic block args and defined values");
886   auto iterOperands = op.getIterOperands();
887   auto iterArgs = op.getRegionIterArgs();
888   auto opResults =
889       op.finalValue() ? op.getResults().drop_front() : op.getResults();
890   unsigned i = 0;
891   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
892     if (std::get<0>(e).getType() != std::get<2>(e).getType())
893       return op.emitOpError() << "types mismatch between " << i
894                               << "th iter operand and defined value";
895     if (std::get<1>(e).getType() != std::get<2>(e).getType())
896       return op.emitOpError() << "types mismatch between " << i
897                               << "th iter region arg and defined value";
898 
899     i++;
900   }
901   return mlir::success();
902 }
903 
904 static void print(mlir::OpAsmPrinter &p, fir::IterWhileOp op) {
905   p << " (" << op.getInductionVar() << " = " << op.lowerBound() << " to "
906     << op.upperBound() << " step " << op.step() << ") and (";
907   assert(op.hasIterOperands());
908   auto regionArgs = op.getRegionIterArgs();
909   auto operands = op.getIterOperands();
910   p << regionArgs.front() << " = " << *operands.begin() << ")";
911   if (regionArgs.size() > 1) {
912     p << " iter_args(";
913     llvm::interleaveComma(
914         llvm::zip(regionArgs.drop_front(), operands.drop_front()), p,
915         [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); });
916     p << ") -> (";
917     llvm::interleaveComma(
918         llvm::drop_begin(op.getResultTypes(), op.finalValue() ? 0 : 1), p);
919     p << ")";
920   } else if (op.finalValue()) {
921     p << " -> (" << op.getResultTypes() << ')';
922   }
923   p.printOptionalAttrDictWithKeyword(op->getAttrs(), {"finalValue"});
924   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
925                 /*printBlockTerminators=*/true);
926 }
927 
928 mlir::Region &fir::IterWhileOp::getLoopBody() { return region(); }
929 
930 bool fir::IterWhileOp::isDefinedOutsideOfLoop(mlir::Value value) {
931   return !region().isAncestor(value.getParentRegion());
932 }
933 
934 mlir::LogicalResult
935 fir::IterWhileOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
936   for (auto op : ops)
937     op->moveBefore(*this);
938   return success();
939 }
940 
941 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) {
942   for (auto i : llvm::enumerate(initArgs()))
943     if (iterArg == i.value())
944       return region().front().getArgument(i.index() + 1);
945   return {};
946 }
947 
948 void fir::IterWhileOp::resultToSourceOps(
949     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
950   auto oper = finalValue() ? resultNum + 1 : resultNum;
951   auto *term = region().front().getTerminator();
952   if (oper < term->getNumOperands())
953     results.push_back(term->getOperand(oper));
954 }
955 
956 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) {
957   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
958     return initArgs()[blockArgNum - 1];
959   return {};
960 }
961 
962 //===----------------------------------------------------------------------===//
963 // LoadOp
964 //===----------------------------------------------------------------------===//
965 
966 /// Get the element type of a reference like type; otherwise null
967 static mlir::Type elementTypeOf(mlir::Type ref) {
968   return llvm::TypeSwitch<mlir::Type, mlir::Type>(ref)
969       .Case<ReferenceType, PointerType, HeapType>(
970           [](auto type) { return type.getEleTy(); })
971       .Default([](mlir::Type) { return mlir::Type{}; });
972 }
973 
974 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) {
975   if ((ele = elementTypeOf(ref)))
976     return mlir::success();
977   return mlir::failure();
978 }
979 
980 //===----------------------------------------------------------------------===//
981 // DoLoopOp
982 //===----------------------------------------------------------------------===//
983 
984 void fir::DoLoopOp::build(mlir::OpBuilder &builder,
985                           mlir::OperationState &result, mlir::Value lb,
986                           mlir::Value ub, mlir::Value step, bool unordered,
987                           bool finalCountValue, mlir::ValueRange iterArgs,
988                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
989   result.addOperands({lb, ub, step});
990   result.addOperands(iterArgs);
991   if (finalCountValue) {
992     result.addTypes(builder.getIndexType());
993     result.addAttribute(finalValueAttrName(result.name), builder.getUnitAttr());
994   }
995   for (auto v : iterArgs)
996     result.addTypes(v.getType());
997   mlir::Region *bodyRegion = result.addRegion();
998   bodyRegion->push_back(new Block{});
999   if (iterArgs.empty() && !finalCountValue)
1000     DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
1001   bodyRegion->front().addArgument(builder.getIndexType());
1002   bodyRegion->front().addArguments(iterArgs.getTypes());
1003   if (unordered)
1004     result.addAttribute(unorderedAttrName(result.name), builder.getUnitAttr());
1005   result.addAttributes(attributes);
1006 }
1007 
1008 static mlir::ParseResult parseDoLoopOp(mlir::OpAsmParser &parser,
1009                                        mlir::OperationState &result) {
1010   auto &builder = parser.getBuilder();
1011   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
1012   // Parse the induction variable followed by '='.
1013   if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual())
1014     return mlir::failure();
1015 
1016   // Parse loop bounds.
1017   auto indexType = builder.getIndexType();
1018   if (parser.parseOperand(lb) ||
1019       parser.resolveOperand(lb, indexType, result.operands) ||
1020       parser.parseKeyword("to") || parser.parseOperand(ub) ||
1021       parser.resolveOperand(ub, indexType, result.operands) ||
1022       parser.parseKeyword("step") || parser.parseOperand(step) ||
1023       parser.resolveOperand(step, indexType, result.operands))
1024     return failure();
1025 
1026   if (mlir::succeeded(parser.parseOptionalKeyword("unordered")))
1027     result.addAttribute("unordered", builder.getUnitAttr());
1028 
1029   // Parse the optional initial iteration arguments.
1030   llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> regionArgs, operands;
1031   llvm::SmallVector<mlir::Type, 4> argTypes;
1032   auto prependCount = false;
1033   regionArgs.push_back(inductionVariable);
1034 
1035   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1036     // Parse assignment list and results type list.
1037     if (parser.parseAssignmentList(regionArgs, operands) ||
1038         parser.parseArrowTypeList(result.types))
1039       return failure();
1040     if (result.types.size() == operands.size() + 1)
1041       prependCount = true;
1042     // Resolve input operands.
1043     llvm::ArrayRef<mlir::Type> resTypes = result.types;
1044     for (auto operand_type :
1045          llvm::zip(operands, prependCount ? resTypes.drop_front() : resTypes))
1046       if (parser.resolveOperand(std::get<0>(operand_type),
1047                                 std::get<1>(operand_type), result.operands))
1048         return failure();
1049   } else if (succeeded(parser.parseOptionalArrow())) {
1050     if (parser.parseKeyword("index"))
1051       return failure();
1052     result.types.push_back(indexType);
1053     prependCount = true;
1054   }
1055 
1056   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1057     return mlir::failure();
1058 
1059   // Induction variable.
1060   if (prependCount)
1061     result.addAttribute(DoLoopOp::finalValueAttrName(result.name),
1062                         builder.getUnitAttr());
1063   else
1064     argTypes.push_back(indexType);
1065   // Loop carried variables
1066   argTypes.append(result.types.begin(), result.types.end());
1067   // Parse the body region.
1068   auto *body = result.addRegion();
1069   if (regionArgs.size() != argTypes.size())
1070     return parser.emitError(
1071         parser.getNameLoc(),
1072         "mismatch in number of loop-carried values and defined values");
1073 
1074   if (parser.parseRegion(*body, regionArgs, argTypes))
1075     return failure();
1076 
1077   DoLoopOp::ensureTerminator(*body, builder, result.location);
1078 
1079   return mlir::success();
1080 }
1081 
1082 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) {
1083   auto ivArg = val.dyn_cast<mlir::BlockArgument>();
1084   if (!ivArg)
1085     return {};
1086   assert(ivArg.getOwner() && "unlinked block argument");
1087   auto *containingInst = ivArg.getOwner()->getParentOp();
1088   return dyn_cast_or_null<fir::DoLoopOp>(containingInst);
1089 }
1090 
1091 // Lifted from loop.loop
1092 static mlir::LogicalResult verify(fir::DoLoopOp op) {
1093   // Check that the body defines as single block argument for the induction
1094   // variable.
1095   auto *body = op.getBody();
1096   if (!body->getArgument(0).getType().isIndex())
1097     return op.emitOpError(
1098         "expected body first argument to be an index argument for "
1099         "the induction variable");
1100 
1101   auto opNumResults = op.getNumResults();
1102   if (opNumResults == 0)
1103     return success();
1104 
1105   if (op.finalValue()) {
1106     if (op.unordered())
1107       return op.emitOpError("unordered loop has no final value");
1108     opNumResults--;
1109   }
1110   if (op.getNumIterOperands() != opNumResults)
1111     return op.emitOpError(
1112         "mismatch in number of loop-carried values and defined values");
1113   if (op.getNumRegionIterArgs() != opNumResults)
1114     return op.emitOpError(
1115         "mismatch in number of basic block args and defined values");
1116   auto iterOperands = op.getIterOperands();
1117   auto iterArgs = op.getRegionIterArgs();
1118   auto opResults =
1119       op.finalValue() ? op.getResults().drop_front() : op.getResults();
1120   unsigned i = 0;
1121   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
1122     if (std::get<0>(e).getType() != std::get<2>(e).getType())
1123       return op.emitOpError() << "types mismatch between " << i
1124                               << "th iter operand and defined value";
1125     if (std::get<1>(e).getType() != std::get<2>(e).getType())
1126       return op.emitOpError() << "types mismatch between " << i
1127                               << "th iter region arg and defined value";
1128 
1129     i++;
1130   }
1131   return success();
1132 }
1133 
1134 static void print(mlir::OpAsmPrinter &p, fir::DoLoopOp op) {
1135   bool printBlockTerminators = false;
1136   p << ' ' << op.getInductionVar() << " = " << op.lowerBound() << " to "
1137     << op.upperBound() << " step " << op.step();
1138   if (op.unordered())
1139     p << " unordered";
1140   if (op.hasIterOperands()) {
1141     p << " iter_args(";
1142     auto regionArgs = op.getRegionIterArgs();
1143     auto operands = op.getIterOperands();
1144     llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
1145       p << std::get<0>(it) << " = " << std::get<1>(it);
1146     });
1147     p << ") -> (" << op.getResultTypes() << ')';
1148     printBlockTerminators = true;
1149   } else if (op.finalValue()) {
1150     p << " -> " << op.getResultTypes();
1151     printBlockTerminators = true;
1152   }
1153   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
1154                                      {"unordered", "finalValue"});
1155   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
1156                 printBlockTerminators);
1157 }
1158 
1159 mlir::Region &fir::DoLoopOp::getLoopBody() { return region(); }
1160 
1161 bool fir::DoLoopOp::isDefinedOutsideOfLoop(mlir::Value value) {
1162   return !region().isAncestor(value.getParentRegion());
1163 }
1164 
1165 mlir::LogicalResult
1166 fir::DoLoopOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
1167   for (auto op : ops)
1168     op->moveBefore(*this);
1169   return success();
1170 }
1171 
1172 /// Translate a value passed as an iter_arg to the corresponding block
1173 /// argument in the body of the loop.
1174 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) {
1175   for (auto i : llvm::enumerate(initArgs()))
1176     if (iterArg == i.value())
1177       return region().front().getArgument(i.index() + 1);
1178   return {};
1179 }
1180 
1181 /// Translate the result vector (by index number) to the corresponding value
1182 /// to the `fir.result` Op.
1183 void fir::DoLoopOp::resultToSourceOps(
1184     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
1185   auto oper = finalValue() ? resultNum + 1 : resultNum;
1186   auto *term = region().front().getTerminator();
1187   if (oper < term->getNumOperands())
1188     results.push_back(term->getOperand(oper));
1189 }
1190 
1191 /// Translate the block argument (by index number) to the corresponding value
1192 /// passed as an iter_arg to the parent DoLoopOp.
1193 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) {
1194   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
1195     return initArgs()[blockArgNum - 1];
1196   return {};
1197 }
1198 
1199 //===----------------------------------------------------------------------===//
1200 // ReboxOp
1201 //===----------------------------------------------------------------------===//
1202 
1203 /// Get the scalar type related to a fir.box type.
1204 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>.
1205 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
1206   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
1207   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
1208     return seqTy.getEleTy();
1209   return eleTy;
1210 }
1211 
1212 /// Get the rank from a !fir.box type
1213 static unsigned getBoxRank(mlir::Type boxTy) {
1214   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
1215   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
1216     return seqTy.getDimension();
1217   return 0;
1218 }
1219 
1220 static mlir::LogicalResult verify(fir::ReboxOp op) {
1221   auto inputBoxTy = op.box().getType();
1222   if (fir::isa_unknown_size_box(inputBoxTy))
1223     return op.emitOpError("box operand must not have unknown rank or type");
1224   auto outBoxTy = op.getType();
1225   if (fir::isa_unknown_size_box(outBoxTy))
1226     return op.emitOpError("result type must not have unknown rank or type");
1227   auto inputRank = getBoxRank(inputBoxTy);
1228   auto inputEleTy = getBoxScalarEleTy(inputBoxTy);
1229   auto outRank = getBoxRank(outBoxTy);
1230   auto outEleTy = getBoxScalarEleTy(outBoxTy);
1231 
1232   if (auto slice = op.slice()) {
1233     // Slicing case
1234     if (slice.getType().cast<fir::SliceType>().getRank() != inputRank)
1235       return op.emitOpError("slice operand rank must match box operand rank");
1236     if (auto shape = op.shape()) {
1237       if (auto shiftTy = shape.getType().dyn_cast<fir::ShiftType>()) {
1238         if (shiftTy.getRank() != inputRank)
1239           return op.emitOpError("shape operand and input box ranks must match "
1240                                 "when there is a slice");
1241       } else {
1242         return op.emitOpError("shape operand must absent or be a fir.shift "
1243                               "when there is a slice");
1244       }
1245     }
1246     if (auto sliceOp = slice.getDefiningOp()) {
1247       auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank();
1248       if (slicedRank != outRank)
1249         return op.emitOpError("result type rank and rank after applying slice "
1250                               "operand must match");
1251     }
1252   } else {
1253     // Reshaping case
1254     unsigned shapeRank = inputRank;
1255     if (auto shape = op.shape()) {
1256       auto ty = shape.getType();
1257       if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) {
1258         shapeRank = shapeTy.getRank();
1259       } else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) {
1260         shapeRank = shapeShiftTy.getRank();
1261       } else {
1262         auto shiftTy = ty.cast<fir::ShiftType>();
1263         shapeRank = shiftTy.getRank();
1264         if (shapeRank != inputRank)
1265           return op.emitOpError("shape operand and input box ranks must match "
1266                                 "when the shape is a fir.shift");
1267       }
1268     }
1269     if (shapeRank != outRank)
1270       return op.emitOpError("result type and shape operand ranks must match");
1271   }
1272 
1273   if (inputEleTy != outEleTy)
1274     // TODO: check that outBoxTy is a parent type of inputBoxTy for derived
1275     // types.
1276     if (!inputEleTy.isa<fir::RecordType>())
1277       return op.emitOpError(
1278           "op input and output element types must match for intrinsic types");
1279   return mlir::success();
1280 }
1281 
1282 //===----------------------------------------------------------------------===//
1283 // ResultOp
1284 //===----------------------------------------------------------------------===//
1285 
1286 static mlir::LogicalResult verify(fir::ResultOp op) {
1287   auto *parentOp = op->getParentOp();
1288   auto results = parentOp->getResults();
1289   auto operands = op->getOperands();
1290 
1291   if (parentOp->getNumResults() != op.getNumOperands())
1292     return op.emitOpError() << "parent of result must have same arity";
1293   for (auto e : llvm::zip(results, operands))
1294     if (std::get<0>(e).getType() != std::get<1>(e).getType())
1295       return op.emitOpError()
1296              << "types mismatch between result op and its parent";
1297   return success();
1298 }
1299 
1300 //===----------------------------------------------------------------------===//
1301 // SelectOp
1302 //===----------------------------------------------------------------------===//
1303 
1304 static constexpr llvm::StringRef getCompareOffsetAttr() {
1305   return "compare_operand_offsets";
1306 }
1307 
1308 static constexpr llvm::StringRef getTargetOffsetAttr() {
1309   return "target_operand_offsets";
1310 }
1311 
1312 template <typename A, typename... AdditionalArgs>
1313 static A getSubOperands(unsigned pos, A allArgs,
1314                         mlir::DenseIntElementsAttr ranges,
1315                         AdditionalArgs &&...additionalArgs) {
1316   unsigned start = 0;
1317   for (unsigned i = 0; i < pos; ++i)
1318     start += (*(ranges.begin() + i)).getZExtValue();
1319   return allArgs.slice(start, (*(ranges.begin() + pos)).getZExtValue(),
1320                        std::forward<AdditionalArgs>(additionalArgs)...);
1321 }
1322 
1323 static mlir::MutableOperandRange
1324 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands,
1325                             StringRef offsetAttr) {
1326   Operation *owner = operands.getOwner();
1327   NamedAttribute targetOffsetAttr =
1328       *owner->getAttrDictionary().getNamed(offsetAttr);
1329   return getSubOperands(
1330       pos, operands, targetOffsetAttr.second.cast<DenseIntElementsAttr>(),
1331       mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr));
1332 }
1333 
1334 static unsigned denseElementsSize(mlir::DenseIntElementsAttr attr) {
1335   return attr.getNumElements();
1336 }
1337 
1338 llvm::Optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) {
1339   return {};
1340 }
1341 
1342 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1343 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
1344   return {};
1345 }
1346 
1347 llvm::Optional<mlir::MutableOperandRange>
1348 fir::SelectOp::getMutableSuccessorOperands(unsigned oper) {
1349   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1350                                        getTargetOffsetAttr());
1351 }
1352 
1353 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1354 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1355                                     unsigned oper) {
1356   auto a =
1357       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1358   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1359       getOperandSegmentSizeAttr());
1360   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1361 }
1362 
1363 unsigned fir::SelectOp::targetOffsetSize() {
1364   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1365       getTargetOffsetAttr()));
1366 }
1367 
1368 //===----------------------------------------------------------------------===//
1369 // SelectCaseOp
1370 //===----------------------------------------------------------------------===//
1371 
1372 llvm::Optional<mlir::OperandRange>
1373 fir::SelectCaseOp::getCompareOperands(unsigned cond) {
1374   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1375       getCompareOffsetAttr());
1376   return {getSubOperands(cond, compareArgs(), a)};
1377 }
1378 
1379 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1380 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands,
1381                                       unsigned cond) {
1382   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1383       getCompareOffsetAttr());
1384   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1385       getOperandSegmentSizeAttr());
1386   return {getSubOperands(cond, getSubOperands(1, operands, segments), a)};
1387 }
1388 
1389 llvm::Optional<mlir::MutableOperandRange>
1390 fir::SelectCaseOp::getMutableSuccessorOperands(unsigned oper) {
1391   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1392                                        getTargetOffsetAttr());
1393 }
1394 
1395 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1396 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1397                                         unsigned oper) {
1398   auto a =
1399       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1400   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1401       getOperandSegmentSizeAttr());
1402   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1403 }
1404 
1405 // parser for fir.select_case Op
1406 static mlir::ParseResult parseSelectCase(mlir::OpAsmParser &parser,
1407                                          mlir::OperationState &result) {
1408   mlir::OpAsmParser::OperandType selector;
1409   mlir::Type type;
1410   if (parseSelector(parser, result, selector, type))
1411     return mlir::failure();
1412 
1413   llvm::SmallVector<mlir::Attribute, 8> attrs;
1414   llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> opers;
1415   llvm::SmallVector<mlir::Block *, 8> dests;
1416   llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs;
1417   llvm::SmallVector<int32_t, 8> argOffs;
1418   int32_t offSize = 0;
1419   while (true) {
1420     mlir::Attribute attr;
1421     mlir::Block *dest;
1422     llvm::SmallVector<mlir::Value, 8> destArg;
1423     mlir::NamedAttrList temp;
1424     if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) ||
1425         parser.parseComma())
1426       return mlir::failure();
1427     attrs.push_back(attr);
1428     if (attr.dyn_cast_or_null<mlir::UnitAttr>()) {
1429       argOffs.push_back(0);
1430     } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) {
1431       mlir::OpAsmParser::OperandType oper1;
1432       mlir::OpAsmParser::OperandType oper2;
1433       if (parser.parseOperand(oper1) || parser.parseComma() ||
1434           parser.parseOperand(oper2) || parser.parseComma())
1435         return mlir::failure();
1436       opers.push_back(oper1);
1437       opers.push_back(oper2);
1438       argOffs.push_back(2);
1439       offSize += 2;
1440     } else {
1441       mlir::OpAsmParser::OperandType oper;
1442       if (parser.parseOperand(oper) || parser.parseComma())
1443         return mlir::failure();
1444       opers.push_back(oper);
1445       argOffs.push_back(1);
1446       ++offSize;
1447     }
1448     if (parser.parseSuccessorAndUseList(dest, destArg))
1449       return mlir::failure();
1450     dests.push_back(dest);
1451     destArgs.push_back(destArg);
1452     if (mlir::succeeded(parser.parseOptionalRSquare()))
1453       break;
1454     if (parser.parseComma())
1455       return mlir::failure();
1456   }
1457   result.addAttribute(fir::SelectCaseOp::getCasesAttr(),
1458                       parser.getBuilder().getArrayAttr(attrs));
1459   if (parser.resolveOperands(opers, type, result.operands))
1460     return mlir::failure();
1461   llvm::SmallVector<int32_t, 8> targOffs;
1462   int32_t toffSize = 0;
1463   const auto count = dests.size();
1464   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
1465     result.addSuccessors(dests[i]);
1466     result.addOperands(destArgs[i]);
1467     auto argSize = destArgs[i].size();
1468     targOffs.push_back(argSize);
1469     toffSize += argSize;
1470   }
1471   auto &bld = parser.getBuilder();
1472   result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(),
1473                       bld.getI32VectorAttr({1, offSize, toffSize}));
1474   result.addAttribute(getCompareOffsetAttr(), bld.getI32VectorAttr(argOffs));
1475   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(targOffs));
1476   return mlir::success();
1477 }
1478 
1479 unsigned fir::SelectCaseOp::compareOffsetSize() {
1480   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1481       getCompareOffsetAttr()));
1482 }
1483 
1484 unsigned fir::SelectCaseOp::targetOffsetSize() {
1485   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1486       getTargetOffsetAttr()));
1487 }
1488 
1489 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
1490                               mlir::OperationState &result,
1491                               mlir::Value selector,
1492                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
1493                               llvm::ArrayRef<mlir::ValueRange> cmpOperands,
1494                               llvm::ArrayRef<mlir::Block *> destinations,
1495                               llvm::ArrayRef<mlir::ValueRange> destOperands,
1496                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1497   result.addOperands(selector);
1498   result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs));
1499   llvm::SmallVector<int32_t, 8> operOffs;
1500   int32_t operSize = 0;
1501   for (auto attr : compareAttrs) {
1502     if (attr.isa<fir::ClosedIntervalAttr>()) {
1503       operOffs.push_back(2);
1504       operSize += 2;
1505     } else if (attr.isa<mlir::UnitAttr>()) {
1506       operOffs.push_back(0);
1507     } else {
1508       operOffs.push_back(1);
1509       ++operSize;
1510     }
1511   }
1512   for (auto ops : cmpOperands)
1513     result.addOperands(ops);
1514   result.addAttribute(getCompareOffsetAttr(),
1515                       builder.getI32VectorAttr(operOffs));
1516   const auto count = destinations.size();
1517   for (auto d : destinations)
1518     result.addSuccessors(d);
1519   const auto opCount = destOperands.size();
1520   llvm::SmallVector<int32_t, 8> argOffs;
1521   int32_t sumArgs = 0;
1522   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
1523     if (i < opCount) {
1524       result.addOperands(destOperands[i]);
1525       const auto argSz = destOperands[i].size();
1526       argOffs.push_back(argSz);
1527       sumArgs += argSz;
1528     } else {
1529       argOffs.push_back(0);
1530     }
1531   }
1532   result.addAttribute(getOperandSegmentSizeAttr(),
1533                       builder.getI32VectorAttr({1, operSize, sumArgs}));
1534   result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
1535   result.addAttributes(attributes);
1536 }
1537 
1538 /// This builder has a slightly simplified interface in that the list of
1539 /// operands need not be partitioned by the builder. Instead the operands are
1540 /// partitioned here, before being passed to the default builder. This
1541 /// partitioning is unchecked, so can go awry on bad input.
1542 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
1543                               mlir::OperationState &result,
1544                               mlir::Value selector,
1545                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
1546                               llvm::ArrayRef<mlir::Value> cmpOpList,
1547                               llvm::ArrayRef<mlir::Block *> destinations,
1548                               llvm::ArrayRef<mlir::ValueRange> destOperands,
1549                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1550   llvm::SmallVector<mlir::ValueRange, 16> cmpOpers;
1551   auto iter = cmpOpList.begin();
1552   for (auto &attr : compareAttrs) {
1553     if (attr.isa<fir::ClosedIntervalAttr>()) {
1554       cmpOpers.push_back(mlir::ValueRange({iter, iter + 2}));
1555       iter += 2;
1556     } else if (attr.isa<UnitAttr>()) {
1557       cmpOpers.push_back(mlir::ValueRange{});
1558     } else {
1559       cmpOpers.push_back(mlir::ValueRange({iter, iter + 1}));
1560       ++iter;
1561     }
1562   }
1563   build(builder, result, selector, compareAttrs, cmpOpers, destinations,
1564         destOperands, attributes);
1565 }
1566 
1567 //===----------------------------------------------------------------------===//
1568 // SelectRankOp
1569 //===----------------------------------------------------------------------===//
1570 
1571 llvm::Optional<mlir::OperandRange>
1572 fir::SelectRankOp::getCompareOperands(unsigned) {
1573   return {};
1574 }
1575 
1576 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1577 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
1578   return {};
1579 }
1580 
1581 llvm::Optional<mlir::MutableOperandRange>
1582 fir::SelectRankOp::getMutableSuccessorOperands(unsigned oper) {
1583   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1584                                        getTargetOffsetAttr());
1585 }
1586 
1587 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1588 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1589                                         unsigned oper) {
1590   auto a =
1591       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1592   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1593       getOperandSegmentSizeAttr());
1594   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1595 }
1596 
1597 unsigned fir::SelectRankOp::targetOffsetSize() {
1598   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1599       getTargetOffsetAttr()));
1600 }
1601 
1602 //===----------------------------------------------------------------------===//
1603 // SelectTypeOp
1604 //===----------------------------------------------------------------------===//
1605 
1606 llvm::Optional<mlir::OperandRange>
1607 fir::SelectTypeOp::getCompareOperands(unsigned) {
1608   return {};
1609 }
1610 
1611 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1612 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
1613   return {};
1614 }
1615 
1616 llvm::Optional<mlir::MutableOperandRange>
1617 fir::SelectTypeOp::getMutableSuccessorOperands(unsigned oper) {
1618   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1619                                        getTargetOffsetAttr());
1620 }
1621 
1622 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1623 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1624                                         unsigned oper) {
1625   auto a =
1626       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1627   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1628       getOperandSegmentSizeAttr());
1629   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1630 }
1631 
1632 static ParseResult parseSelectType(OpAsmParser &parser,
1633                                    OperationState &result) {
1634   mlir::OpAsmParser::OperandType selector;
1635   mlir::Type type;
1636   if (parseSelector(parser, result, selector, type))
1637     return mlir::failure();
1638 
1639   llvm::SmallVector<mlir::Attribute, 8> attrs;
1640   llvm::SmallVector<mlir::Block *, 8> dests;
1641   llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs;
1642   while (true) {
1643     mlir::Attribute attr;
1644     mlir::Block *dest;
1645     llvm::SmallVector<mlir::Value, 8> destArg;
1646     mlir::NamedAttrList temp;
1647     if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() ||
1648         parser.parseSuccessorAndUseList(dest, destArg))
1649       return mlir::failure();
1650     attrs.push_back(attr);
1651     dests.push_back(dest);
1652     destArgs.push_back(destArg);
1653     if (mlir::succeeded(parser.parseOptionalRSquare()))
1654       break;
1655     if (parser.parseComma())
1656       return mlir::failure();
1657   }
1658   auto &bld = parser.getBuilder();
1659   result.addAttribute(fir::SelectTypeOp::getCasesAttr(),
1660                       bld.getArrayAttr(attrs));
1661   llvm::SmallVector<int32_t, 8> argOffs;
1662   int32_t offSize = 0;
1663   const auto count = dests.size();
1664   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
1665     result.addSuccessors(dests[i]);
1666     result.addOperands(destArgs[i]);
1667     auto argSize = destArgs[i].size();
1668     argOffs.push_back(argSize);
1669     offSize += argSize;
1670   }
1671   result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(),
1672                       bld.getI32VectorAttr({1, 0, offSize}));
1673   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs));
1674   return mlir::success();
1675 }
1676 
1677 unsigned fir::SelectTypeOp::targetOffsetSize() {
1678   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1679       getTargetOffsetAttr()));
1680 }
1681 
1682 //===----------------------------------------------------------------------===//
1683 // SliceOp
1684 //===----------------------------------------------------------------------===//
1685 
1686 /// Return the output rank of a slice op. The output rank must be between 1 and
1687 /// the rank of the array being sliced (inclusive).
1688 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) {
1689   unsigned rank = 0;
1690   if (!triples.empty()) {
1691     for (unsigned i = 1, end = triples.size(); i < end; i += 3) {
1692       auto op = triples[i].getDefiningOp();
1693       if (!mlir::isa_and_nonnull<fir::UndefOp>(op))
1694         ++rank;
1695     }
1696     assert(rank > 0);
1697   }
1698   return rank;
1699 }
1700 
1701 //===----------------------------------------------------------------------===//
1702 // StoreOp
1703 //===----------------------------------------------------------------------===//
1704 
1705 mlir::Type fir::StoreOp::elementType(mlir::Type refType) {
1706   if (auto ref = refType.dyn_cast<ReferenceType>())
1707     return ref.getEleTy();
1708   if (auto ref = refType.dyn_cast<PointerType>())
1709     return ref.getEleTy();
1710   if (auto ref = refType.dyn_cast<HeapType>())
1711     return ref.getEleTy();
1712   return {};
1713 }
1714 
1715 //===----------------------------------------------------------------------===//
1716 // StringLitOp
1717 //===----------------------------------------------------------------------===//
1718 
1719 bool fir::StringLitOp::isWideValue() {
1720   auto eleTy = getType().cast<fir::SequenceType>().getEleTy();
1721   return eleTy.cast<fir::CharacterType>().getFKind() != 1;
1722 }
1723 
1724 //===----------------------------------------------------------------------===//
1725 // IfOp
1726 //===----------------------------------------------------------------------===//
1727 
1728 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
1729                       mlir::Value cond, bool withElseRegion) {
1730   build(builder, result, llvm::None, cond, withElseRegion);
1731 }
1732 
1733 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
1734                       mlir::TypeRange resultTypes, mlir::Value cond,
1735                       bool withElseRegion) {
1736   result.addOperands(cond);
1737   result.addTypes(resultTypes);
1738 
1739   mlir::Region *thenRegion = result.addRegion();
1740   thenRegion->push_back(new mlir::Block());
1741   if (resultTypes.empty())
1742     IfOp::ensureTerminator(*thenRegion, builder, result.location);
1743 
1744   mlir::Region *elseRegion = result.addRegion();
1745   if (withElseRegion) {
1746     elseRegion->push_back(new mlir::Block());
1747     if (resultTypes.empty())
1748       IfOp::ensureTerminator(*elseRegion, builder, result.location);
1749   }
1750 }
1751 
1752 static mlir::ParseResult parseIfOp(OpAsmParser &parser,
1753                                    OperationState &result) {
1754   result.regions.reserve(2);
1755   mlir::Region *thenRegion = result.addRegion();
1756   mlir::Region *elseRegion = result.addRegion();
1757 
1758   auto &builder = parser.getBuilder();
1759   OpAsmParser::OperandType cond;
1760   mlir::Type i1Type = builder.getIntegerType(1);
1761   if (parser.parseOperand(cond) ||
1762       parser.resolveOperand(cond, i1Type, result.operands))
1763     return mlir::failure();
1764 
1765   if (parser.parseOptionalArrowTypeList(result.types))
1766     return mlir::failure();
1767 
1768   if (parser.parseRegion(*thenRegion, {}, {}))
1769     return mlir::failure();
1770   IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
1771 
1772   if (mlir::succeeded(parser.parseOptionalKeyword("else"))) {
1773     if (parser.parseRegion(*elseRegion, {}, {}))
1774       return mlir::failure();
1775     IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
1776   }
1777 
1778   // Parse the optional attribute list.
1779   if (parser.parseOptionalAttrDict(result.attributes))
1780     return mlir::failure();
1781   return mlir::success();
1782 }
1783 
1784 static LogicalResult verify(fir::IfOp op) {
1785   if (op.getNumResults() != 0 && op.elseRegion().empty())
1786     return op.emitOpError("must have an else block if defining values");
1787 
1788   return mlir::success();
1789 }
1790 
1791 static void print(mlir::OpAsmPrinter &p, fir::IfOp op) {
1792   bool printBlockTerminators = false;
1793   p << ' ' << op.condition();
1794   if (!op.results().empty()) {
1795     p << " -> (" << op.getResultTypes() << ')';
1796     printBlockTerminators = true;
1797   }
1798   p.printRegion(op.thenRegion(), /*printEntryBlockArgs=*/false,
1799                 printBlockTerminators);
1800 
1801   // Print the 'else' regions if it exists and has a block.
1802   auto &otherReg = op.elseRegion();
1803   if (!otherReg.empty()) {
1804     p << " else";
1805     p.printRegion(otherReg, /*printEntryBlockArgs=*/false,
1806                   printBlockTerminators);
1807   }
1808   p.printOptionalAttrDict(op->getAttrs());
1809 }
1810 
1811 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results,
1812                                   unsigned resultNum) {
1813   auto *term = thenRegion().front().getTerminator();
1814   if (resultNum < term->getNumOperands())
1815     results.push_back(term->getOperand(resultNum));
1816   term = elseRegion().front().getTerminator();
1817   if (resultNum < term->getNumOperands())
1818     results.push_back(term->getOperand(resultNum));
1819 }
1820 
1821 //===----------------------------------------------------------------------===//
1822 
1823 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) {
1824   if (attr.dyn_cast_or_null<mlir::UnitAttr>() ||
1825       attr.dyn_cast_or_null<ClosedIntervalAttr>() ||
1826       attr.dyn_cast_or_null<PointIntervalAttr>() ||
1827       attr.dyn_cast_or_null<LowerBoundAttr>() ||
1828       attr.dyn_cast_or_null<UpperBoundAttr>())
1829     return mlir::success();
1830   return mlir::failure();
1831 }
1832 
1833 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,
1834                                     unsigned dest) {
1835   unsigned o = 0;
1836   for (unsigned i = 0; i < dest; ++i) {
1837     auto &attr = cases[i];
1838     if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) {
1839       ++o;
1840       if (attr.dyn_cast_or_null<ClosedIntervalAttr>())
1841         ++o;
1842     }
1843   }
1844   return o;
1845 }
1846 
1847 mlir::ParseResult fir::parseSelector(mlir::OpAsmParser &parser,
1848                                      mlir::OperationState &result,
1849                                      mlir::OpAsmParser::OperandType &selector,
1850                                      mlir::Type &type) {
1851   if (parser.parseOperand(selector) || parser.parseColonType(type) ||
1852       parser.resolveOperand(selector, type, result.operands) ||
1853       parser.parseLSquare())
1854     return mlir::failure();
1855   return mlir::success();
1856 }
1857 
1858 /// Generic pretty-printer of a binary operation
1859 static void printBinaryOp(Operation *op, OpAsmPrinter &p) {
1860   assert(op->getNumOperands() == 2 && "binary op must have two operands");
1861   assert(op->getNumResults() == 1 && "binary op must have one result");
1862 
1863   p << ' ' << op->getOperand(0) << ", " << op->getOperand(1);
1864   p.printOptionalAttrDict(op->getAttrs());
1865   p << " : " << op->getResult(0).getType();
1866 }
1867 
1868 /// Generic pretty-printer of an unary operation
1869 static void printUnaryOp(Operation *op, OpAsmPrinter &p) {
1870   assert(op->getNumOperands() == 1 && "unary op must have one operand");
1871   assert(op->getNumResults() == 1 && "unary op must have one result");
1872 
1873   p << ' ' << op->getOperand(0);
1874   p.printOptionalAttrDict(op->getAttrs());
1875   p << " : " << op->getResult(0).getType();
1876 }
1877 
1878 bool fir::isReferenceLike(mlir::Type type) {
1879   return type.isa<fir::ReferenceType>() || type.isa<fir::HeapType>() ||
1880          type.isa<fir::PointerType>();
1881 }
1882 
1883 mlir::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module,
1884                                StringRef name, mlir::FunctionType type,
1885                                llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1886   if (auto f = module.lookupSymbol<mlir::FuncOp>(name))
1887     return f;
1888   mlir::OpBuilder modBuilder(module.getBodyRegion());
1889   modBuilder.setInsertionPoint(module.getBody()->getTerminator());
1890   auto result = modBuilder.create<mlir::FuncOp>(loc, name, type, attrs);
1891   result.setVisibility(mlir::SymbolTable::Visibility::Private);
1892   return result;
1893 }
1894 
1895 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module,
1896                                   StringRef name, mlir::Type type,
1897                                   llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1898   if (auto g = module.lookupSymbol<fir::GlobalOp>(name))
1899     return g;
1900   mlir::OpBuilder modBuilder(module.getBodyRegion());
1901   auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs);
1902   result.setVisibility(mlir::SymbolTable::Visibility::Private);
1903   return result;
1904 }
1905 
1906 bool fir::valueHasFirAttribute(mlir::Value value,
1907                                llvm::StringRef attributeName) {
1908   // If this is a fir.box that was loaded, the fir attributes will be on the
1909   // related fir.ref<fir.box> creation.
1910   if (value.getType().isa<fir::BoxType>())
1911     if (auto definingOp = value.getDefiningOp())
1912       if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp))
1913         value = loadOp.memref();
1914   // If this is a function argument, look in the argument attributes.
1915   if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) {
1916     if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock())
1917       if (auto funcOp =
1918               mlir::dyn_cast<mlir::FuncOp>(blockArg.getOwner()->getParentOp()))
1919         if (funcOp.getArgAttr(blockArg.getArgNumber(), attributeName))
1920           return true;
1921     return false;
1922   }
1923 
1924   if (auto definingOp = value.getDefiningOp()) {
1925     // If this is an allocated value, look at the allocation attributes.
1926     if (mlir::isa<fir::AllocMemOp>(definingOp) ||
1927         mlir::isa<AllocaOp>(definingOp))
1928       return definingOp->hasAttr(attributeName);
1929     // If this is an imported global, look at AddrOfOp and GlobalOp attributes.
1930     // Both operations are looked at because use/host associated variable (the
1931     // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate
1932     // entity (the globalOp) does not have them.
1933     if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) {
1934       if (addressOfOp->hasAttr(attributeName))
1935         return true;
1936       if (auto module = definingOp->getParentOfType<mlir::ModuleOp>())
1937         if (auto globalOp =
1938                 module.lookupSymbol<fir::GlobalOp>(addressOfOp.symbol()))
1939           return globalOp->hasAttr(attributeName);
1940     }
1941   }
1942   // TODO: Construct associated entities attributes. Decide where the fir
1943   // attributes must be placed/looked for in this case.
1944   return false;
1945 }
1946 
1947 // Tablegen operators
1948 
1949 #define GET_OP_CLASSES
1950 #include "flang/Optimizer/Dialect/FIROps.cpp.inc"
1951