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