1 //===-- MutableBox.cpp -- MutableBox utilities ----------------------------===// 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/Builder/MutableBox.h" 14 #include "flang/Lower/Todo.h" 15 #include "flang/Optimizer/Builder/Character.h" 16 #include "flang/Optimizer/Builder/FIRBuilder.h" 17 #include "flang/Optimizer/Builder/Runtime/Derived.h" 18 #include "flang/Optimizer/Builder/Runtime/Stop.h" 19 #include "flang/Optimizer/Dialect/FIROps.h" 20 #include "flang/Optimizer/Dialect/FIROpsSupport.h" 21 #include "flang/Optimizer/Support/FatalError.h" 22 23 /// Create a fir.box describing the new address, bounds, and length parameters 24 /// for a MutableBox \p box. 25 static mlir::Value createNewFirBox(fir::FirOpBuilder &builder, 26 mlir::Location loc, 27 const fir::MutableBoxValue &box, 28 mlir::Value addr, mlir::ValueRange lbounds, 29 mlir::ValueRange extents, 30 mlir::ValueRange lengths) { 31 if (addr.getType().isa<fir::BoxType>()) 32 // The entity is already boxed. 33 return builder.createConvert(loc, box.getBoxTy(), addr); 34 35 mlir::Value shape; 36 if (!extents.empty()) { 37 if (lbounds.empty()) { 38 auto shapeType = 39 fir::ShapeType::get(builder.getContext(), extents.size()); 40 shape = builder.create<fir::ShapeOp>(loc, shapeType, extents); 41 } else { 42 llvm::SmallVector<mlir::Value> shapeShiftBounds; 43 for (auto [lb, extent] : llvm::zip(lbounds, extents)) { 44 shapeShiftBounds.emplace_back(lb); 45 shapeShiftBounds.emplace_back(extent); 46 } 47 auto shapeShiftType = 48 fir::ShapeShiftType::get(builder.getContext(), extents.size()); 49 shape = builder.create<fir::ShapeShiftOp>(loc, shapeShiftType, 50 shapeShiftBounds); 51 } 52 } // Otherwise, this a scalar. Leave the shape empty. 53 54 // Ignore lengths if already constant in the box type (this would trigger an 55 // error in the embox). 56 llvm::SmallVector<mlir::Value> cleanedLengths; 57 auto cleanedAddr = addr; 58 if (auto charTy = box.getEleTy().dyn_cast<fir::CharacterType>()) { 59 // Cast address to box type so that both input and output type have 60 // unknown or constant lengths. 61 auto bt = box.getBaseTy(); 62 auto addrTy = addr.getType(); 63 auto type = addrTy.isa<fir::HeapType>() ? fir::HeapType::get(bt) 64 : addrTy.isa<fir::PointerType>() ? fir::PointerType::get(bt) 65 : builder.getRefType(bt); 66 cleanedAddr = builder.createConvert(loc, type, addr); 67 if (charTy.getLen() == fir::CharacterType::unknownLen()) 68 cleanedLengths.append(lengths.begin(), lengths.end()); 69 } else if (box.isDerivedWithLenParameters()) { 70 TODO(loc, "updating mutablebox of derived type with length parameters"); 71 cleanedLengths = lengths; 72 } 73 mlir::Value emptySlice; 74 return builder.create<fir::EmboxOp>(loc, box.getBoxTy(), cleanedAddr, shape, 75 emptySlice, cleanedLengths); 76 } 77 78 //===----------------------------------------------------------------------===// 79 // MutableBoxValue writer and reader 80 //===----------------------------------------------------------------------===// 81 82 namespace { 83 /// MutablePropertyWriter and MutablePropertyReader implementations are the only 84 /// places that depend on how the properties of MutableBoxValue (pointers and 85 /// allocatables) that can be modified in the lifetime of the entity (address, 86 /// extents, lower bounds, length parameters) are represented. 87 /// That is, the properties may be only stored in a fir.box in memory if we 88 /// need to enforce a single point of truth for the properties across calls. 89 /// Or, they can be tracked as independent local variables when it is safe to 90 /// do so. Using bare variables benefits from all optimization passes, even 91 /// when they are not aware of what a fir.box is and fir.box have not been 92 /// optimized out yet. 93 94 /// MutablePropertyWriter allows reading the properties of a MutableBoxValue. 95 class MutablePropertyReader { 96 public: 97 MutablePropertyReader(fir::FirOpBuilder &builder, mlir::Location loc, 98 const fir::MutableBoxValue &box, 99 bool forceIRBoxRead = false) 100 : builder{builder}, loc{loc}, box{box} { 101 if (forceIRBoxRead || !box.isDescribedByVariables()) 102 irBox = builder.create<fir::LoadOp>(loc, box.getAddr()); 103 } 104 /// Get base address of allocated/associated entity. 105 mlir::Value readBaseAddress() { 106 if (irBox) { 107 auto memrefTy = box.getBoxTy().getEleTy(); 108 if (!fir::isa_ref_type(memrefTy)) 109 memrefTy = builder.getRefType(memrefTy); 110 return builder.create<fir::BoxAddrOp>(loc, memrefTy, irBox); 111 } 112 auto addrVar = box.getMutableProperties().addr; 113 return builder.create<fir::LoadOp>(loc, addrVar); 114 } 115 /// Return {lbound, extent} values read from the MutableBoxValue given 116 /// the dimension. 117 std::pair<mlir::Value, mlir::Value> readShape(unsigned dim) { 118 auto idxTy = builder.getIndexType(); 119 if (irBox) { 120 auto dimVal = builder.createIntegerConstant(loc, idxTy, dim); 121 auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, 122 irBox, dimVal); 123 return {dimInfo.getResult(0), dimInfo.getResult(1)}; 124 } 125 const auto &mutableProperties = box.getMutableProperties(); 126 auto lb = builder.create<fir::LoadOp>(loc, mutableProperties.lbounds[dim]); 127 auto ext = builder.create<fir::LoadOp>(loc, mutableProperties.extents[dim]); 128 return {lb, ext}; 129 } 130 131 /// Return the character length. If the length was not deferred, the value 132 /// that was specified is returned (The mutable fields is not read). 133 mlir::Value readCharacterLength() { 134 if (box.hasNonDeferredLenParams()) 135 return box.nonDeferredLenParams()[0]; 136 if (irBox) 137 return fir::factory::CharacterExprHelper{builder, loc}.readLengthFromBox( 138 irBox); 139 const auto &deferred = box.getMutableProperties().deferredParams; 140 if (deferred.empty()) 141 fir::emitFatalError(loc, "allocatable entity has no length property"); 142 return builder.create<fir::LoadOp>(loc, deferred[0]); 143 } 144 145 /// Read and return all extents. If \p lbounds vector is provided, lbounds are 146 /// also read into it. 147 llvm::SmallVector<mlir::Value> 148 readShape(llvm::SmallVectorImpl<mlir::Value> *lbounds = nullptr) { 149 llvm::SmallVector<mlir::Value> extents; 150 auto rank = box.rank(); 151 for (decltype(rank) dim = 0; dim < rank; ++dim) { 152 auto [lb, extent] = readShape(dim); 153 if (lbounds) 154 lbounds->push_back(lb); 155 extents.push_back(extent); 156 } 157 return extents; 158 } 159 160 /// Read all mutable properties. Return the base address. 161 mlir::Value read(llvm::SmallVectorImpl<mlir::Value> &lbounds, 162 llvm::SmallVectorImpl<mlir::Value> &extents, 163 llvm::SmallVectorImpl<mlir::Value> &lengths) { 164 extents = readShape(&lbounds); 165 if (box.isCharacter()) 166 lengths.emplace_back(readCharacterLength()); 167 else if (box.isDerivedWithLenParameters()) 168 TODO(loc, "read allocatable or pointer derived type LEN parameters"); 169 return readBaseAddress(); 170 } 171 172 /// Return the loaded fir.box. 173 mlir::Value getIrBox() const { 174 assert(irBox); 175 return irBox; 176 } 177 178 /// Read the lower bounds 179 void getLowerBounds(llvm::SmallVectorImpl<mlir::Value> &lbounds) { 180 auto rank = box.rank(); 181 for (decltype(rank) dim = 0; dim < rank; ++dim) 182 lbounds.push_back(std::get<0>(readShape(dim))); 183 } 184 185 private: 186 fir::FirOpBuilder &builder; 187 mlir::Location loc; 188 fir::MutableBoxValue box; 189 mlir::Value irBox; 190 }; 191 192 /// MutablePropertyWriter allows modifying the properties of a MutableBoxValue. 193 class MutablePropertyWriter { 194 public: 195 MutablePropertyWriter(fir::FirOpBuilder &builder, mlir::Location loc, 196 const fir::MutableBoxValue &box) 197 : builder{builder}, loc{loc}, box{box} {} 198 /// Update MutableBoxValue with new address, shape and length parameters. 199 /// Extents and lbounds must all have index type. 200 /// lbounds can be empty in which case all ones is assumed. 201 /// Length parameters must be provided for the length parameters that are 202 /// deferred. 203 void updateMutableBox(mlir::Value addr, mlir::ValueRange lbounds, 204 mlir::ValueRange extents, mlir::ValueRange lengths) { 205 if (box.isDescribedByVariables()) 206 updateMutableProperties(addr, lbounds, extents, lengths); 207 else 208 updateIRBox(addr, lbounds, extents, lengths); 209 } 210 211 /// Update MutableBoxValue with a new fir.box. This requires that the mutable 212 /// box is not described by a set of variables, since they could not describe 213 /// all that can be described in the new fir.box (e.g. non contiguous entity). 214 void updateWithIrBox(mlir::Value newBox) { 215 assert(!box.isDescribedByVariables()); 216 builder.create<fir::StoreOp>(loc, newBox, box.getAddr()); 217 } 218 /// Set unallocated/disassociated status for the entity described by 219 /// MutableBoxValue. Deallocation is not performed by this helper. 220 void setUnallocatedStatus() { 221 if (box.isDescribedByVariables()) { 222 auto addrVar = box.getMutableProperties().addr; 223 auto nullTy = fir::dyn_cast_ptrEleTy(addrVar.getType()); 224 builder.create<fir::StoreOp>(loc, builder.createNullConstant(loc, nullTy), 225 addrVar); 226 } else { 227 // Note that the dynamic type of polymorphic entities must be reset to the 228 // declaration type of the mutable box. See Fortran 2018 7.8.2 NOTE 1. 229 // For those, we cannot simply set the address to zero. The way we are 230 // currently unallocating fir.box guarantees that we are resetting the 231 // type to the declared type. Beware if changing this. 232 // Note: the standard is not clear in Deallocate and p => NULL semantics 233 // regarding the new dynamic type the entity must have. So far, assume 234 // this is just like NULLIFY and the dynamic type must be set to the 235 // declared type, not retain the previous dynamic type. 236 auto deallocatedBox = fir::factory::createUnallocatedBox( 237 builder, loc, box.getBoxTy(), box.nonDeferredLenParams()); 238 builder.create<fir::StoreOp>(loc, deallocatedBox, box.getAddr()); 239 } 240 } 241 242 /// Copy Values from the fir.box into the property variables if any. 243 void syncMutablePropertiesFromIRBox() { 244 if (!box.isDescribedByVariables()) 245 return; 246 llvm::SmallVector<mlir::Value> lbounds; 247 llvm::SmallVector<mlir::Value> extents; 248 llvm::SmallVector<mlir::Value> lengths; 249 auto addr = 250 MutablePropertyReader{builder, loc, box, /*forceIRBoxRead=*/true}.read( 251 lbounds, extents, lengths); 252 updateMutableProperties(addr, lbounds, extents, lengths); 253 } 254 255 /// Copy Values from property variables, if any, into the fir.box. 256 void syncIRBoxFromMutableProperties() { 257 if (!box.isDescribedByVariables()) 258 return; 259 llvm::SmallVector<mlir::Value> lbounds; 260 llvm::SmallVector<mlir::Value> extents; 261 llvm::SmallVector<mlir::Value> lengths; 262 auto addr = MutablePropertyReader{builder, loc, box}.read(lbounds, extents, 263 lengths); 264 updateIRBox(addr, lbounds, extents, lengths); 265 } 266 267 private: 268 /// Update the IR box (fir.ref<fir.box<T>>) of the MutableBoxValue. 269 void updateIRBox(mlir::Value addr, mlir::ValueRange lbounds, 270 mlir::ValueRange extents, mlir::ValueRange lengths) { 271 mlir::Value irBox = 272 createNewFirBox(builder, loc, box, addr, lbounds, extents, lengths); 273 builder.create<fir::StoreOp>(loc, irBox, box.getAddr()); 274 } 275 276 /// Update the set of property variables of the MutableBoxValue. 277 void updateMutableProperties(mlir::Value addr, mlir::ValueRange lbounds, 278 mlir::ValueRange extents, 279 mlir::ValueRange lengths) { 280 auto castAndStore = [&](mlir::Value val, mlir::Value addr) { 281 auto type = fir::dyn_cast_ptrEleTy(addr.getType()); 282 builder.create<fir::StoreOp>(loc, builder.createConvert(loc, type, val), 283 addr); 284 }; 285 const auto &mutableProperties = box.getMutableProperties(); 286 castAndStore(addr, mutableProperties.addr); 287 for (auto [extent, extentVar] : 288 llvm::zip(extents, mutableProperties.extents)) 289 castAndStore(extent, extentVar); 290 if (!mutableProperties.lbounds.empty()) { 291 if (lbounds.empty()) { 292 auto one = 293 builder.createIntegerConstant(loc, builder.getIndexType(), 1); 294 for (auto lboundVar : mutableProperties.lbounds) 295 castAndStore(one, lboundVar); 296 } else { 297 for (auto [lbound, lboundVar] : 298 llvm::zip(lbounds, mutableProperties.lbounds)) 299 castAndStore(lbound, lboundVar); 300 } 301 } 302 if (box.isCharacter()) 303 // llvm::zip account for the fact that the length only needs to be stored 304 // when it is specified in the allocation and deferred in the 305 // MutableBoxValue. 306 for (auto [len, lenVar] : 307 llvm::zip(lengths, mutableProperties.deferredParams)) 308 castAndStore(len, lenVar); 309 else if (box.isDerivedWithLenParameters()) 310 TODO(loc, "update allocatable derived type length parameters"); 311 } 312 fir::FirOpBuilder &builder; 313 mlir::Location loc; 314 fir::MutableBoxValue box; 315 }; 316 317 } // namespace 318 319 mlir::Value 320 fir::factory::createUnallocatedBox(fir::FirOpBuilder &builder, 321 mlir::Location loc, mlir::Type boxType, 322 mlir::ValueRange nonDeferredParams) { 323 auto baseAddrType = boxType.dyn_cast<fir::BoxType>().getEleTy(); 324 if (!fir::isa_ref_type(baseAddrType)) 325 baseAddrType = builder.getRefType(baseAddrType); 326 auto type = fir::unwrapRefType(baseAddrType); 327 auto eleTy = fir::unwrapSequenceType(type); 328 if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) 329 if (recTy.getNumLenParams() > 0) 330 TODO(loc, "creating unallocated fir.box of derived type with length " 331 "parameters"); 332 auto nullAddr = builder.createNullConstant(loc, baseAddrType); 333 mlir::Value shape; 334 if (auto seqTy = type.dyn_cast<fir::SequenceType>()) { 335 auto zero = builder.createIntegerConstant(loc, builder.getIndexType(), 0); 336 llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), zero); 337 shape = builder.createShape( 338 loc, fir::ArrayBoxValue{nullAddr, extents, /*lbounds=*/llvm::None}); 339 } 340 // Provide dummy length parameters if they are dynamic. If a length parameter 341 // is deferred. It is set to zero here and will be set on allocation. 342 llvm::SmallVector<mlir::Value> lenParams; 343 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 344 if (charTy.getLen() == fir::CharacterType::unknownLen()) { 345 if (!nonDeferredParams.empty()) { 346 lenParams.push_back(nonDeferredParams[0]); 347 } else { 348 auto zero = builder.createIntegerConstant( 349 loc, builder.getCharacterLengthType(), 0); 350 lenParams.push_back(zero); 351 } 352 } 353 } 354 mlir::Value emptySlice; 355 return builder.create<fir::EmboxOp>(loc, boxType, nullAddr, shape, emptySlice, 356 lenParams); 357 } 358 359 fir::MutableBoxValue 360 fir::factory::createTempMutableBox(fir::FirOpBuilder &builder, 361 mlir::Location loc, mlir::Type type, 362 llvm::StringRef name) { 363 auto boxType = fir::BoxType::get(fir::HeapType::get(type)); 364 auto boxAddr = builder.createTemporary(loc, boxType, name); 365 auto box = 366 fir::MutableBoxValue(boxAddr, /*nonDeferredParams=*/mlir::ValueRange(), 367 /*mutableProperties=*/{}); 368 MutablePropertyWriter{builder, loc, box}.setUnallocatedStatus(); 369 return box; 370 } 371 372 /// Helper to decide if a MutableBoxValue must be read to a BoxValue or 373 /// can be read to a reified box value. 374 static bool readToBoxValue(const fir::MutableBoxValue &box, 375 bool mayBePolymorphic) { 376 // If this is described by a set of local variables, the value 377 // should not be tracked as a fir.box. 378 if (box.isDescribedByVariables()) 379 return false; 380 // Polymorphism might be a source of discontiguity, even on allocatables. 381 // Track value as fir.box 382 if ((box.isDerived() && mayBePolymorphic) || box.isUnlimitedPolymorphic()) 383 return true; 384 // Intrinsic allocatables are contiguous, no need to track the value by 385 // fir.box. 386 if (box.isAllocatable() || box.rank() == 0) 387 return false; 388 // Pointers are known to be contiguous at compile time iff they have the 389 // CONTIGUOUS attribute. 390 return !fir::valueHasFirAttribute(box.getAddr(), 391 fir::getContiguousAttrName()); 392 } 393 394 fir::ExtendedValue 395 fir::factory::genMutableBoxRead(fir::FirOpBuilder &builder, mlir::Location loc, 396 const fir::MutableBoxValue &box, 397 bool mayBePolymorphic) { 398 if (box.hasAssumedRank()) 399 TODO(loc, "Assumed rank allocatables or pointers"); 400 llvm::SmallVector<mlir::Value> lbounds; 401 llvm::SmallVector<mlir::Value> extents; 402 llvm::SmallVector<mlir::Value> lengths; 403 if (readToBoxValue(box, mayBePolymorphic)) { 404 auto reader = MutablePropertyReader(builder, loc, box); 405 reader.getLowerBounds(lbounds); 406 return fir::BoxValue{reader.getIrBox(), lbounds, 407 box.nonDeferredLenParams()}; 408 } 409 // Contiguous intrinsic type entity: all the data can be extracted from the 410 // fir.box. 411 auto addr = 412 MutablePropertyReader(builder, loc, box).read(lbounds, extents, lengths); 413 auto rank = box.rank(); 414 if (box.isCharacter()) { 415 auto len = lengths.empty() ? mlir::Value{} : lengths[0]; 416 if (rank) 417 return fir::CharArrayBoxValue{addr, len, extents, lbounds}; 418 return fir::CharBoxValue{addr, len}; 419 } 420 if (rank) 421 return fir::ArrayBoxValue{addr, extents, lbounds}; 422 return addr; 423 } 424 425 mlir::Value 426 fir::factory::genIsAllocatedOrAssociatedTest(fir::FirOpBuilder &builder, 427 mlir::Location loc, 428 const fir::MutableBoxValue &box) { 429 auto addr = MutablePropertyReader(builder, loc, box).readBaseAddress(); 430 return builder.genIsNotNull(loc, addr); 431 } 432 433 /// Generate finalizer call and inlined free. This does not check that the 434 /// address was allocated. 435 static void genFinalizeAndFree(fir::FirOpBuilder &builder, mlir::Location loc, 436 mlir::Value addr) { 437 // TODO: call finalizer if any. 438 439 // A heap (ALLOCATABLE) object may have been converted to a ptr (POINTER), 440 // so make sure the heap type is restored before deallocation. 441 auto cast = builder.createConvert( 442 loc, fir::HeapType::get(fir::dyn_cast_ptrEleTy(addr.getType())), addr); 443 builder.create<fir::FreeMemOp>(loc, cast); 444 } 445 446 void fir::factory::genFinalization(fir::FirOpBuilder &builder, 447 mlir::Location loc, 448 const fir::MutableBoxValue &box) { 449 auto addr = MutablePropertyReader(builder, loc, box).readBaseAddress(); 450 auto isAllocated = builder.genIsNotNull(loc, addr); 451 auto ifOp = builder.create<fir::IfOp>(loc, isAllocated, 452 /*withElseRegion=*/false); 453 auto insPt = builder.saveInsertionPoint(); 454 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 455 genFinalizeAndFree(builder, loc, addr); 456 builder.restoreInsertionPoint(insPt); 457 } 458 459 //===----------------------------------------------------------------------===// 460 // MutableBoxValue writing interface implementation 461 //===----------------------------------------------------------------------===// 462 463 void fir::factory::associateMutableBox(fir::FirOpBuilder &builder, 464 mlir::Location loc, 465 const fir::MutableBoxValue &box, 466 const fir::ExtendedValue &source, 467 mlir::ValueRange lbounds) { 468 MutablePropertyWriter writer(builder, loc, box); 469 source.match( 470 [&](const fir::UnboxedValue &addr) { 471 writer.updateMutableBox(addr, /*lbounds=*/llvm::None, 472 /*extents=*/llvm::None, /*lengths=*/llvm::None); 473 }, 474 [&](const fir::CharBoxValue &ch) { 475 writer.updateMutableBox(ch.getAddr(), /*lbounds=*/llvm::None, 476 /*extents=*/llvm::None, {ch.getLen()}); 477 }, 478 [&](const fir::ArrayBoxValue &arr) { 479 writer.updateMutableBox(arr.getAddr(), 480 lbounds.empty() ? arr.getLBounds() : lbounds, 481 arr.getExtents(), /*lengths=*/llvm::None); 482 }, 483 [&](const fir::CharArrayBoxValue &arr) { 484 writer.updateMutableBox(arr.getAddr(), 485 lbounds.empty() ? arr.getLBounds() : lbounds, 486 arr.getExtents(), {arr.getLen()}); 487 }, 488 [&](const fir::BoxValue &arr) { 489 // Rebox array fir.box to the pointer type and apply potential new lower 490 // bounds. 491 mlir::ValueRange newLbounds = lbounds.empty() 492 ? mlir::ValueRange{arr.getLBounds()} 493 : mlir::ValueRange{lbounds}; 494 if (box.isDescribedByVariables()) { 495 // LHS is a contiguous pointer described by local variables. Open RHS 496 // fir.box to update the LHS. 497 auto rawAddr = builder.create<fir::BoxAddrOp>(loc, arr.getMemTy(), 498 arr.getAddr()); 499 auto extents = fir::factory::getExtents(loc, builder, source); 500 llvm::SmallVector<mlir::Value> lenParams; 501 if (arr.isCharacter()) { 502 lenParams.emplace_back( 503 fir::factory::readCharLen(builder, loc, source)); 504 } else if (arr.isDerivedWithLenParameters()) { 505 TODO(loc, "pointer assignment to derived with length parameters"); 506 } 507 writer.updateMutableBox(rawAddr, newLbounds, extents, lenParams); 508 } else { 509 mlir::Value shift; 510 if (!newLbounds.empty()) { 511 auto shiftType = 512 fir::ShiftType::get(builder.getContext(), newLbounds.size()); 513 shift = builder.create<fir::ShiftOp>(loc, shiftType, newLbounds); 514 } 515 auto reboxed = 516 builder.create<fir::ReboxOp>(loc, box.getBoxTy(), arr.getAddr(), 517 shift, /*slice=*/mlir::Value()); 518 writer.updateWithIrBox(reboxed); 519 } 520 }, 521 [&](const fir::MutableBoxValue &) { 522 // No point implementing this, if right-hand side is a 523 // pointer/allocatable, the related MutableBoxValue has been read into 524 // another ExtendedValue category. 525 fir::emitFatalError(loc, 526 "Cannot write MutableBox to another MutableBox"); 527 }, 528 [&](const fir::ProcBoxValue &) { 529 TODO(loc, "Procedure pointer assignment"); 530 }); 531 } 532 533 void fir::factory::associateMutableBoxWithRemap( 534 fir::FirOpBuilder &builder, mlir::Location loc, 535 const fir::MutableBoxValue &box, const fir::ExtendedValue &source, 536 mlir::ValueRange lbounds, mlir::ValueRange ubounds) { 537 // Compute new extents 538 llvm::SmallVector<mlir::Value> extents; 539 auto idxTy = builder.getIndexType(); 540 if (!lbounds.empty()) { 541 auto one = builder.createIntegerConstant(loc, idxTy, 1); 542 for (auto [lb, ub] : llvm::zip(lbounds, ubounds)) { 543 auto lbi = builder.createConvert(loc, idxTy, lb); 544 auto ubi = builder.createConvert(loc, idxTy, ub); 545 auto diff = builder.create<mlir::arith::SubIOp>(loc, idxTy, ubi, lbi); 546 extents.emplace_back( 547 builder.create<mlir::arith::AddIOp>(loc, idxTy, diff, one)); 548 } 549 } else { 550 // lbounds are default. Upper bounds and extents are the same. 551 for (auto ub : ubounds) { 552 auto cast = builder.createConvert(loc, idxTy, ub); 553 extents.emplace_back(cast); 554 } 555 } 556 const auto newRank = extents.size(); 557 auto cast = [&](mlir::Value addr) -> mlir::Value { 558 // Cast base addr to new sequence type. 559 auto ty = fir::dyn_cast_ptrEleTy(addr.getType()); 560 if (auto seqTy = ty.dyn_cast<fir::SequenceType>()) { 561 fir::SequenceType::Shape shape(newRank, 562 fir::SequenceType::getUnknownExtent()); 563 ty = fir::SequenceType::get(shape, seqTy.getEleTy()); 564 } 565 return builder.createConvert(loc, builder.getRefType(ty), addr); 566 }; 567 MutablePropertyWriter writer(builder, loc, box); 568 source.match( 569 [&](const fir::UnboxedValue &addr) { 570 writer.updateMutableBox(cast(addr), lbounds, extents, 571 /*lengths=*/llvm::None); 572 }, 573 [&](const fir::CharBoxValue &ch) { 574 writer.updateMutableBox(cast(ch.getAddr()), lbounds, extents, 575 {ch.getLen()}); 576 }, 577 [&](const fir::ArrayBoxValue &arr) { 578 writer.updateMutableBox(cast(arr.getAddr()), lbounds, extents, 579 /*lengths=*/llvm::None); 580 }, 581 [&](const fir::CharArrayBoxValue &arr) { 582 writer.updateMutableBox(cast(arr.getAddr()), lbounds, extents, 583 {arr.getLen()}); 584 }, 585 [&](const fir::BoxValue &arr) { 586 // Rebox right-hand side fir.box with a new shape and type. 587 if (box.isDescribedByVariables()) { 588 // LHS is a contiguous pointer described by local variables. Open RHS 589 // fir.box to update the LHS. 590 auto rawAddr = builder.create<fir::BoxAddrOp>(loc, arr.getMemTy(), 591 arr.getAddr()); 592 llvm::SmallVector<mlir::Value> lenParams; 593 if (arr.isCharacter()) { 594 lenParams.emplace_back( 595 fir::factory::readCharLen(builder, loc, source)); 596 } else if (arr.isDerivedWithLenParameters()) { 597 TODO(loc, "pointer assignment to derived with length parameters"); 598 } 599 writer.updateMutableBox(rawAddr, lbounds, extents, lenParams); 600 } else { 601 auto shapeType = 602 fir::ShapeShiftType::get(builder.getContext(), extents.size()); 603 llvm::SmallVector<mlir::Value> shapeArgs; 604 auto idxTy = builder.getIndexType(); 605 for (auto [lbnd, ext] : llvm::zip(lbounds, extents)) { 606 auto lb = builder.createConvert(loc, idxTy, lbnd); 607 shapeArgs.push_back(lb); 608 shapeArgs.push_back(ext); 609 } 610 auto shape = 611 builder.create<fir::ShapeShiftOp>(loc, shapeType, shapeArgs); 612 auto reboxed = 613 builder.create<fir::ReboxOp>(loc, box.getBoxTy(), arr.getAddr(), 614 shape, /*slice=*/mlir::Value()); 615 writer.updateWithIrBox(reboxed); 616 } 617 }, 618 [&](const fir::MutableBoxValue &) { 619 // No point implementing this, if right-hand side is a pointer or 620 // allocatable, the related MutableBoxValue has already been read into 621 // another ExtendedValue category. 622 fir::emitFatalError(loc, 623 "Cannot write MutableBox to another MutableBox"); 624 }, 625 [&](const fir::ProcBoxValue &) { 626 TODO(loc, "Procedure pointer assignment"); 627 }); 628 } 629 630 void fir::factory::disassociateMutableBox(fir::FirOpBuilder &builder, 631 mlir::Location loc, 632 const fir::MutableBoxValue &box) { 633 MutablePropertyWriter{builder, loc, box}.setUnallocatedStatus(); 634 } 635 636 static llvm::SmallVector<mlir::Value> 637 getNewLengths(fir::FirOpBuilder &builder, mlir::Location loc, 638 const fir::MutableBoxValue &box, mlir::ValueRange lenParams) { 639 llvm::SmallVector<mlir::Value> lengths; 640 auto idxTy = builder.getIndexType(); 641 if (auto charTy = box.getEleTy().dyn_cast<fir::CharacterType>()) { 642 if (charTy.getLen() == fir::CharacterType::unknownLen()) { 643 if (box.hasNonDeferredLenParams()) 644 lengths.emplace_back( 645 builder.createConvert(loc, idxTy, box.nonDeferredLenParams()[0])); 646 else if (!lenParams.empty()) 647 lengths.emplace_back(builder.createConvert(loc, idxTy, lenParams[0])); 648 else 649 fir::emitFatalError( 650 loc, "could not deduce character lengths in character allocation"); 651 } 652 } 653 return lengths; 654 } 655 656 static mlir::Value allocateAndInitNewStorage(fir::FirOpBuilder &builder, 657 mlir::Location loc, 658 const fir::MutableBoxValue &box, 659 mlir::ValueRange extents, 660 mlir::ValueRange lenParams, 661 llvm::StringRef allocName) { 662 auto lengths = getNewLengths(builder, loc, box, lenParams); 663 auto newStorage = builder.create<fir::AllocMemOp>( 664 loc, box.getBaseTy(), allocName, lengths, extents); 665 if (box.getEleTy().isa<fir::RecordType>()) { 666 // TODO: skip runtime initialization if this is not required. Currently, 667 // there is no way to know here if a derived type needs it or not. But the 668 // information is available at compile time and could be reflected here 669 // somehow. 670 mlir::Value irBox = createNewFirBox(builder, loc, box, newStorage, 671 llvm::None, extents, lengths); 672 fir::runtime::genDerivedTypeInitialize(builder, loc, irBox); 673 } 674 return newStorage; 675 } 676 677 void fir::factory::genInlinedAllocation(fir::FirOpBuilder &builder, 678 mlir::Location loc, 679 const fir::MutableBoxValue &box, 680 mlir::ValueRange lbounds, 681 mlir::ValueRange extents, 682 mlir::ValueRange lenParams, 683 llvm::StringRef allocName) { 684 auto lengths = getNewLengths(builder, loc, box, lenParams); 685 auto heap = builder.create<fir::AllocMemOp>(loc, box.getBaseTy(), allocName, 686 lengths, extents); 687 MutablePropertyWriter{builder, loc, box}.updateMutableBox(heap, lbounds, 688 extents, lengths); 689 if (box.getEleTy().isa<fir::RecordType>()) { 690 // TODO: skip runtime initialization if this is not required. Currently, 691 // there is no way to know here if a derived type needs it or not. But the 692 // information is available at compile time and could be reflected here 693 // somehow. 694 mlir::Value irBox = fir::factory::getMutableIRBox(builder, loc, box); 695 fir::runtime::genDerivedTypeInitialize(builder, loc, irBox); 696 } 697 } 698 699 void fir::factory::genInlinedDeallocate(fir::FirOpBuilder &builder, 700 mlir::Location loc, 701 const fir::MutableBoxValue &box) { 702 auto addr = MutablePropertyReader(builder, loc, box).readBaseAddress(); 703 genFinalizeAndFree(builder, loc, addr); 704 MutablePropertyWriter{builder, loc, box}.setUnallocatedStatus(); 705 } 706 707 fir::factory::MutableBoxReallocation 708 fir::factory::genReallocIfNeeded(fir::FirOpBuilder &builder, mlir::Location loc, 709 const fir::MutableBoxValue &box, 710 mlir::ValueRange shape, 711 mlir::ValueRange lengthParams) { 712 // Implement 10.2.1.3 point 3 logic when lhs is an array. 713 auto reader = MutablePropertyReader(builder, loc, box); 714 auto addr = reader.readBaseAddress(); 715 auto i1Type = builder.getI1Type(); 716 auto addrType = addr.getType(); 717 auto isAllocated = builder.genIsNotNull(loc, addr); 718 auto ifOp = 719 builder 720 .genIfOp(loc, {i1Type, addrType}, isAllocated, 721 /*withElseRegion=*/true) 722 .genThen([&]() { 723 // The box is allocated. Check if it must be reallocated and 724 // reallocate. 725 auto mustReallocate = builder.createBool(loc, false); 726 auto compareProperty = [&](mlir::Value previous, 727 mlir::Value required) { 728 auto castPrevious = 729 builder.createConvert(loc, required.getType(), previous); 730 auto cmp = builder.create<mlir::arith::CmpIOp>( 731 loc, mlir::arith::CmpIPredicate::ne, castPrevious, required); 732 mustReallocate = builder.create<mlir::arith::SelectOp>( 733 loc, cmp, cmp, mustReallocate); 734 }; 735 llvm::SmallVector<mlir::Value> previousExtents = reader.readShape(); 736 if (!shape.empty()) 737 for (auto [previousExtent, requested] : 738 llvm::zip(previousExtents, shape)) 739 compareProperty(previousExtent, requested); 740 741 if (box.isCharacter() && !box.hasNonDeferredLenParams()) { 742 // When the allocatable length is not deferred, it must not be 743 // reallocated in case of length mismatch, instead, 744 // padding/trimming will occur in later assignment to it. 745 assert(!lengthParams.empty() && 746 "must provide length parameters for character"); 747 compareProperty(reader.readCharacterLength(), lengthParams[0]); 748 } else if (box.isDerivedWithLenParameters()) { 749 TODO(loc, "automatic allocation of derived type allocatable with " 750 "length parameters"); 751 } 752 auto ifOp = 753 builder 754 .genIfOp(loc, {addrType}, mustReallocate, 755 /*withElseRegion=*/true) 756 .genThen([&]() { 757 // If shape or length mismatch, allocate new storage. 758 // When rhs is a scalar, keep the previous shape 759 auto extents = shape.empty() 760 ? mlir::ValueRange(previousExtents) 761 : shape; 762 auto heap = allocateAndInitNewStorage( 763 builder, loc, box, extents, lengthParams, 764 ".auto.alloc"); 765 builder.create<fir::ResultOp>(loc, heap); 766 }) 767 .genElse( 768 [&]() { builder.create<fir::ResultOp>(loc, addr); }); 769 ifOp.end(); 770 auto newAddr = ifOp.getResults()[0]; 771 builder.create<fir::ResultOp>( 772 loc, mlir::ValueRange{mustReallocate, newAddr}); 773 }) 774 .genElse([&]() { 775 auto trueValue = builder.createBool(loc, true); 776 // The box is not yet allocated, simply allocate it. 777 if (shape.empty() && box.rank() != 0) { 778 // See 10.2.1.3 p3. 779 fir::runtime::genReportFatalUserError( 780 builder, loc, 781 "array left hand side must be allocated when the right hand " 782 "side is a scalar"); 783 builder.create<fir::ResultOp>(loc, 784 mlir::ValueRange{trueValue, addr}); 785 } else { 786 auto heap = allocateAndInitNewStorage( 787 builder, loc, box, shape, lengthParams, ".auto.alloc"); 788 builder.create<fir::ResultOp>(loc, 789 mlir::ValueRange{trueValue, heap}); 790 } 791 }); 792 ifOp.end(); 793 auto wasReallocated = ifOp.getResults()[0]; 794 auto newAddr = ifOp.getResults()[1]; 795 // Create an ExtentedValue for the new storage. 796 auto newValue = [&]() -> fir::ExtendedValue { 797 mlir::SmallVector<mlir::Value> extents; 798 if (box.hasRank()) { 799 if (shape.empty()) 800 extents = reader.readShape(); 801 else 802 extents.append(shape.begin(), shape.end()); 803 } 804 if (box.isCharacter()) { 805 auto len = box.hasNonDeferredLenParams() ? reader.readCharacterLength() 806 : lengthParams[0]; 807 if (box.hasRank()) 808 return fir::CharArrayBoxValue{newAddr, len, extents}; 809 return fir::CharBoxValue{newAddr, len}; 810 } 811 if (box.isDerivedWithLenParameters()) 812 TODO(loc, "reallocation of derived type entities with length parameters"); 813 if (box.hasRank()) 814 return fir::ArrayBoxValue{newAddr, extents}; 815 return newAddr; 816 }(); 817 return {newValue, addr, wasReallocated, isAllocated}; 818 } 819 820 void fir::factory::finalizeRealloc(fir::FirOpBuilder &builder, 821 mlir::Location loc, 822 const fir::MutableBoxValue &box, 823 mlir::ValueRange lbounds, 824 bool takeLboundsIfRealloc, 825 const MutableBoxReallocation &realloc) { 826 builder.genIfThen(loc, realloc.wasReallocated) 827 .genThen([&]() { 828 auto reader = MutablePropertyReader(builder, loc, box); 829 llvm::SmallVector<mlir::Value> previousLbounds; 830 if (!takeLboundsIfRealloc && box.hasRank()) 831 reader.readShape(&previousLbounds); 832 auto lbs = 833 takeLboundsIfRealloc ? lbounds : mlir::ValueRange{previousLbounds}; 834 llvm::SmallVector<mlir::Value> lenParams; 835 if (box.isCharacter()) 836 lenParams.push_back(fir::getLen(realloc.newValue)); 837 if (box.isDerivedWithLenParameters()) 838 TODO(loc, 839 "reallocation of derived type entities with length parameters"); 840 auto lengths = getNewLengths(builder, loc, box, lenParams); 841 auto heap = fir::getBase(realloc.newValue); 842 auto extents = fir::factory::getExtents(loc, builder, realloc.newValue); 843 builder.genIfThen(loc, realloc.oldAddressWasAllocated) 844 .genThen( 845 [&]() { genFinalizeAndFree(builder, loc, realloc.oldAddress); }) 846 .end(); 847 MutablePropertyWriter{builder, loc, box}.updateMutableBox( 848 heap, lbs, extents, lengths); 849 }) 850 .end(); 851 } 852 853 //===----------------------------------------------------------------------===// 854 // MutableBoxValue syncing implementation 855 //===----------------------------------------------------------------------===// 856 857 /// Depending on the implementation, allocatable/pointer descriptor and the 858 /// MutableBoxValue need to be synced before and after calls passing the 859 /// descriptor. These calls will generate the syncing if needed or be no-op. 860 mlir::Value fir::factory::getMutableIRBox(fir::FirOpBuilder &builder, 861 mlir::Location loc, 862 const fir::MutableBoxValue &box) { 863 MutablePropertyWriter{builder, loc, box}.syncIRBoxFromMutableProperties(); 864 return box.getAddr(); 865 } 866 void fir::factory::syncMutableBoxFromIRBox(fir::FirOpBuilder &builder, 867 mlir::Location loc, 868 const fir::MutableBoxValue &box) { 869 MutablePropertyWriter{builder, loc, box}.syncMutablePropertiesFromIRBox(); 870 } 871