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