Debian Codegraph @

flang/lib/Optimizer/Builder/MutableBox.cpp

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