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