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