Debian Codegraph @

flang/lib/Optimizer/Builder/HLFIRTools.cpp

raw
1 //===-- HLFIRTools.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 // Tools to manipulate HLFIR variable and expressions
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "flang/Optimizer/Builder/HLFIRTools.h"
14 #include "flang/Optimizer/Builder/Character.h"
15 #include "flang/Optimizer/Builder/FIRBuilder.h"
16 #include "flang/Optimizer/Builder/MutableBox.h"
17 #include "flang/Optimizer/Builder/Runtime/Allocatable.h"
18 #include "flang/Optimizer/Builder/Todo.h"
19 #include "flang/Optimizer/HLFIR/HLFIROps.h"
20 #include "mlir/IR/IRMapping.h"
21 #include "mlir/Support/LLVM.h"
22 #include "llvm/ADT/TypeSwitch.h"
23 #include <optional>
24
25 // Return explicit extents. If the base is a fir.box, this won't read it to
26 // return the extents and will instead return an empty vector.
27 llvm::SmallVector<mlir::Value>
28 hlfir::getExplicitExtentsFromShape(mlir::Value shape,
29 fir::FirOpBuilder &builder) {
30 llvm::SmallVector<mlir::Value> result;
31 auto *shapeOp = shape.getDefiningOp();
32 if (auto s = mlir::dyn_cast_or_null<fir::ShapeOp>(shapeOp)) {
33 auto e = s.getExtents();
34 result.append(e.begin(), e.end());
35 } else if (auto s = mlir::dyn_cast_or_null<fir::ShapeShiftOp>(shapeOp)) {
36 auto e = s.getExtents();
37 result.append(e.begin(), e.end());
38 } else if (mlir::dyn_cast_or_null<fir::ShiftOp>(shapeOp)) {
39 return {};
40 } else if (auto s = mlir::dyn_cast_or_null<hlfir::ShapeOfOp>(shapeOp)) {
41 hlfir::ExprType expr = mlir::cast<hlfir::ExprType>(s.getExpr().getType());
42 llvm::ArrayRef<int64_t> exprShape = expr.getShape();
43 mlir::Type indexTy = builder.getIndexType();
44 fir::ShapeType shapeTy = mlir::cast<fir::ShapeType>(shape.getType());
45 result.reserve(shapeTy.getRank());
46 for (unsigned i = 0; i < shapeTy.getRank(); ++i) {
47 int64_t extent = exprShape[i];
48 mlir::Value extentVal;
49 if (extent == expr.getUnknownExtent()) {
50 auto op = builder.create<hlfir::GetExtentOp>(shape.getLoc(), shape, i);
51 extentVal = op.getResult();
52 } else {
53 extentVal =
54 builder.createIntegerConstant(shape.getLoc(), indexTy, extent);
55 }
56 result.emplace_back(extentVal);
57 }
58 } else {
59 TODO(shape.getLoc(), "read fir.shape to get extents");
60 }
61 return result;
62 }
63 static llvm::SmallVector<mlir::Value>
64 getExplicitExtents(fir::FortranVariableOpInterface var,
65 fir::FirOpBuilder &builder) {
66 if (mlir::Value shape = var.getShape())
67 return hlfir::getExplicitExtentsFromShape(var.getShape(), builder);
68 return {};
69 }
70
71 // Return explicit lower bounds. For pointers and allocatables, this will not
72 // read the lower bounds and instead return an empty vector.
73 static llvm::SmallVector<mlir::Value>
74 getExplicitLboundsFromShape(mlir::Value shape) {
75 llvm::SmallVector<mlir::Value> result;
76 auto *shapeOp = shape.getDefiningOp();
77 if (auto s = mlir::dyn_cast_or_null<fir::ShapeOp>(shapeOp)) {
78 return {};
79 } else if (auto s = mlir::dyn_cast_or_null<fir::ShapeShiftOp>(shapeOp)) {
80 auto e = s.getOrigins();
81 result.append(e.begin(), e.end());
82 } else if (auto s = mlir::dyn_cast_or_null<fir::ShiftOp>(shapeOp)) {
83 auto e = s.getOrigins();
84 result.append(e.begin(), e.end());
85 } else {
86 TODO(shape.getLoc(), "read fir.shape to get lower bounds");
87 }
88 return result;
89 }
90 static llvm::SmallVector<mlir::Value>
91 getExplicitLbounds(fir::FortranVariableOpInterface var) {
92 if (mlir::Value shape = var.getShape())
93 return getExplicitLboundsFromShape(shape);
94 return {};
95 }
96
97 static void
98 genLboundsAndExtentsFromBox(mlir::Location loc, fir::FirOpBuilder &builder,
99 hlfir::Entity boxEntity,
100 llvm::SmallVectorImpl<mlir::Value> &lbounds,
101 llvm::SmallVectorImpl<mlir::Value> *extents) {
102 assert(mlir::isa<fir::BaseBoxType>(boxEntity.getType()) && "must be a box");
103 mlir::Type idxTy = builder.getIndexType();
104 const int rank = boxEntity.getRank();
105 for (int i = 0; i < rank; ++i) {
106 mlir::Value dim = builder.createIntegerConstant(loc, idxTy, i);
107 auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy,
108 boxEntity, dim);
109 lbounds.push_back(dimInfo.getLowerBound());
110 if (extents)
111 extents->push_back(dimInfo.getExtent());
112 }
113 }
114
115 static llvm::SmallVector<mlir::Value>
116 getNonDefaultLowerBounds(mlir::Location loc, fir::FirOpBuilder &builder,
117 hlfir::Entity entity) {
118 assert(!entity.isAssumedRank() &&
119 "cannot compute assumed rank bounds statically");
120 if (!entity.mayHaveNonDefaultLowerBounds())
121 return {};
122 if (auto varIface = entity.getIfVariableInterface()) {
123 llvm::SmallVector<mlir::Value> lbounds = getExplicitLbounds(varIface);
124 if (!lbounds.empty())
125 return lbounds;
126 }
127 if (entity.isMutableBox())
128 entity = hlfir::derefPointersAndAllocatables(loc, builder, entity);
129 llvm::SmallVector<mlir::Value> lowerBounds;
130 genLboundsAndExtentsFromBox(loc, builder, entity, lowerBounds,
131 /*extents=*/nullptr);
132 return lowerBounds;
133 }
134
135 static llvm::SmallVector<mlir::Value> toSmallVector(mlir::ValueRange range) {
136 llvm::SmallVector<mlir::Value> res;
137 res.append(range.begin(), range.end());
138 return res;
139 }
140
141 static llvm::SmallVector<mlir::Value> getExplicitTypeParams(hlfir::Entity var) {
142 if (auto varIface = var.getMaybeDereferencedVariableInterface())
143 return toSmallVector(varIface.getExplicitTypeParams());
144 return {};
145 }
146
147 static mlir::Value tryGettingNonDeferredCharLen(hlfir::Entity var) {
148 if (auto varIface = var.getMaybeDereferencedVariableInterface())
149 if (!varIface.getExplicitTypeParams().empty())
150 return varIface.getExplicitTypeParams()[0];
151 return mlir::Value{};
152 }
153
154 static mlir::Value genCharacterVariableLength(mlir::Location loc,
155 fir::FirOpBuilder &builder,
156 hlfir::Entity var) {
157 if (mlir::Value len = tryGettingNonDeferredCharLen(var))
158 return len;
159 auto charType = mlir::cast<fir::CharacterType>(var.getFortranElementType());
160 if (charType.hasConstantLen())
161 return builder.createIntegerConstant(loc, builder.getIndexType(),
162 charType.getLen());
163 if (var.isMutableBox())
164 var = hlfir::Entity{builder.create<fir::LoadOp>(loc, var)};
165 mlir::Value len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
166 var.getFirBase());
167 assert(len && "failed to retrieve length");
168 return len;
169 }
170
171 static fir::CharBoxValue genUnboxChar(mlir::Location loc,
172 fir::FirOpBuilder &builder,
173 mlir::Value boxChar) {
174 if (auto emboxChar = boxChar.getDefiningOp<fir::EmboxCharOp>())
175 return {emboxChar.getMemref(), emboxChar.getLen()};
176 mlir::Type refType = fir::ReferenceType::get(
177 mlir::cast<fir::BoxCharType>(boxChar.getType()).getEleTy());
178 auto unboxed = builder.create<fir::UnboxCharOp>(
179 loc, refType, builder.getIndexType(), boxChar);
180 mlir::Value addr = unboxed.getResult(0);
181 mlir::Value len = unboxed.getResult(1);
182 if (auto varIface = boxChar.getDefiningOp<fir::FortranVariableOpInterface>())
183 if (mlir::Value explicitlen = varIface.getExplicitCharLen())
184 len = explicitlen;
185 return {addr, len};
186 }
187
188 mlir::Value hlfir::Entity::getFirBase() const {
189 if (fir::FortranVariableOpInterface variable = getIfVariableInterface()) {
190 if (auto declareOp =
191 mlir::dyn_cast<hlfir::DeclareOp>(variable.getOperation()))
192 return declareOp.getOriginalBase();
193 if (auto associateOp =
194 mlir::dyn_cast<hlfir::AssociateOp>(variable.getOperation()))
195 return associateOp.getFirBase();
196 }
197 return getBase();
198 }
199
200 static bool isShapeWithLowerBounds(mlir::Value shape) {
201 if (!shape)
202 return false;
203 auto shapeTy = shape.getType();
204 return mlir::isa<fir::ShiftType>(shapeTy) ||
205 mlir::isa<fir::ShapeShiftType>(shapeTy);
206 }
207
208 bool hlfir::Entity::mayHaveNonDefaultLowerBounds() const {
209 if (!isBoxAddressOrValue() || isScalar())
210 return false;
211 if (isMutableBox())
212 return true;
213 if (auto varIface = getIfVariableInterface())
214 return isShapeWithLowerBounds(varIface.getShape());
215 // Go through chain of fir.box converts.
216 if (auto convert = getDefiningOp<fir::ConvertOp>())
217 return hlfir::Entity{convert.getValue()}.mayHaveNonDefaultLowerBounds();
218 // TODO: Embox and Rebox do not have hlfir variable interface, but are
219 // easy to reason about.
220 return true;
221 }
222
223 fir::FortranVariableOpInterface
224 hlfir::genDeclare(mlir::Location loc, fir::FirOpBuilder &builder,
225 const fir::ExtendedValue &exv, llvm::StringRef name,
226 fir::FortranVariableFlagsAttr flags, mlir::Value dummyScope,
227 cuf::DataAttributeAttr dataAttr) {
228
229 mlir::Value base = fir::getBase(exv);
230 assert(fir::conformsWithPassByRef(base.getType()) &&
231 "entity being declared must be in memory");
232 mlir::Value shapeOrShift;
233 llvm::SmallVector<mlir::Value> lenParams;
234 exv.match(
235 [&](const fir::CharBoxValue &box) {
236 lenParams.emplace_back(box.getLen());
237 },
238 [&](const fir::ArrayBoxValue &) {
239 shapeOrShift = builder.createShape(loc, exv);
240 },
241 [&](const fir::CharArrayBoxValue &box) {
242 shapeOrShift = builder.createShape(loc, exv);
243 lenParams.emplace_back(box.getLen());
244 },
245 [&](const fir::BoxValue &box) {
246 if (!box.getLBounds().empty())
247 shapeOrShift = builder.createShape(loc, exv);
248 lenParams.append(box.getExplicitParameters().begin(),
249 box.getExplicitParameters().end());
250 },
251 [&](const fir::MutableBoxValue &box) {
252 lenParams.append(box.nonDeferredLenParams().begin(),
253 box.nonDeferredLenParams().end());
254 },
255 [](const auto &) {});
256 auto declareOp = builder.create<hlfir::DeclareOp>(
257 loc, base, name, shapeOrShift, lenParams, dummyScope, flags, dataAttr);
258 return mlir::cast<fir::FortranVariableOpInterface>(declareOp.getOperation());
259 }
260
261 hlfir::AssociateOp
262 hlfir::genAssociateExpr(mlir::Location loc, fir::FirOpBuilder &builder,
263 hlfir::Entity value, mlir::Type variableType,
264 llvm::StringRef name,
265 std::optional<mlir::NamedAttribute> attr) {
266 assert(value.isValue() && "must not be a variable");
267 mlir::Value shape{};
268 if (value.isArray())
269 shape = genShape(loc, builder, value);
270
271 mlir::Value source = value;
272 // Lowered scalar expression values for numerical and logical may have a
273 // different type than what is required for the type in memory (logical
274 // expressions are typically manipulated as i1, but needs to be stored
275 // according to the fir.logical<kind> so that the storage size is correct).
276 // Character length mismatches are ignored (it is ok for one to be dynamic
277 // and the other static).
278 mlir::Type varEleTy = getFortranElementType(variableType);
279 mlir::Type valueEleTy = getFortranElementType(value.getType());
280 if (varEleTy != valueEleTy && !(mlir::isa<fir::CharacterType>(valueEleTy) &&
281 mlir::isa<fir::CharacterType>(varEleTy))) {
282 assert(value.isScalar() && fir::isa_trivial(value.getType()));
283 source = builder.createConvert(loc, fir::unwrapPassByRefType(variableType),
284 value);
285 }
286 llvm::SmallVector<mlir::Value> lenParams;
287 genLengthParameters(loc, builder, value, lenParams);
288 if (attr) {
289 assert(name.empty() && "It attribute is provided, no-name is expected");
290 return builder.create<hlfir::AssociateOp>(loc, source, shape, lenParams,
291 fir::FortranVariableFlagsAttr{},
292 llvm::ArrayRef{*attr});
293 }
294 return builder.create<hlfir::AssociateOp>(loc, source, name, shape, lenParams,
295 fir::FortranVariableFlagsAttr{});
296 }
297
298 mlir::Value hlfir::genVariableRawAddress(mlir::Location loc,
299 fir::FirOpBuilder &builder,
300 hlfir::Entity var) {
301 assert(var.isVariable() && "only address of variables can be taken");
302 mlir::Value baseAddr = var.getFirBase();
303 if (var.isMutableBox())
304 baseAddr = builder.create<fir::LoadOp>(loc, baseAddr);
305 // Get raw address.
306 if (mlir::isa<fir::BoxCharType>(var.getType()))
307 baseAddr = genUnboxChar(loc, builder, var.getBase()).getAddr();
308 if (mlir::isa<fir::BaseBoxType>(baseAddr.getType()))
309 baseAddr = builder.create<fir::BoxAddrOp>(loc, baseAddr);
310 return baseAddr;
311 }
312
313 mlir::Value hlfir::genVariableBoxChar(mlir::Location loc,
314 fir::FirOpBuilder &builder,
315 hlfir::Entity var) {
316 assert(var.isVariable() && "only address of variables can be taken");
317 if (mlir::isa<fir::BoxCharType>(var.getType()))
318 return var;
319 mlir::Value addr = genVariableRawAddress(loc, builder, var);
320 llvm::SmallVector<mlir::Value> lengths;
321 genLengthParameters(loc, builder, var, lengths);
322 assert(lengths.size() == 1);
323 auto charType = mlir::cast<fir::CharacterType>(var.getFortranElementType());
324 auto boxCharType =
325 fir::BoxCharType::get(builder.getContext(), charType.getFKind());
326 auto scalarAddr =
327 builder.createConvert(loc, fir::ReferenceType::get(charType), addr);
328 return builder.create<fir::EmboxCharOp>(loc, boxCharType, scalarAddr,
329 lengths[0]);
330 }
331
332 hlfir::Entity hlfir::genVariableBox(mlir::Location loc,
333 fir::FirOpBuilder &builder,
334 hlfir::Entity var) {
335 assert(var.isVariable() && "must be a variable");
336 var = hlfir::derefPointersAndAllocatables(loc, builder, var);
337 if (mlir::isa<fir::BaseBoxType>(var.getType()))
338 return var;
339 // Note: if the var is not a fir.box/fir.class at that point, it has default
340 // lower bounds and is not polymorphic.
341 mlir::Value shape =
342 var.isArray() ? hlfir::genShape(loc, builder, var) : mlir::Value{};
343 llvm::SmallVector<mlir::Value> typeParams;
344 auto maybeCharType =
345 mlir::dyn_cast<fir::CharacterType>(var.getFortranElementType());
346 if (!maybeCharType || maybeCharType.hasDynamicLen())
347 hlfir::genLengthParameters(loc, builder, var, typeParams);
348 mlir::Value addr = var.getBase();
349 if (mlir::isa<fir::BoxCharType>(var.getType()))
350 addr = genVariableRawAddress(loc, builder, var);
351 mlir::Type boxType = fir::BoxType::get(var.getElementOrSequenceType());
352 auto embox =
353 builder.create<fir::EmboxOp>(loc, boxType, addr, shape,
354 /*slice=*/mlir::Value{}, typeParams);
355 return hlfir::Entity{embox.getResult()};
356 }
357
358 hlfir::Entity hlfir::loadTrivialScalar(mlir::Location loc,
359 fir::FirOpBuilder &builder,
360 Entity entity) {
361 entity = derefPointersAndAllocatables(loc, builder, entity);
362 if (entity.isVariable() && entity.isScalar() &&
363 fir::isa_trivial(entity.getFortranElementType())) {
364 return Entity{builder.create<fir::LoadOp>(loc, entity)};
365 }
366 return entity;
367 }
368
369 hlfir::Entity hlfir::getElementAt(mlir::Location loc,
370 fir::FirOpBuilder &builder, Entity entity,
371 mlir::ValueRange oneBasedIndices) {
372 if (entity.isScalar())
373 return entity;
374 llvm::SmallVector<mlir::Value> lenParams;
375 genLengthParameters(loc, builder, entity, lenParams);
376 if (mlir::isa<hlfir::ExprType>(entity.getType()))
377 return hlfir::Entity{builder.create<hlfir::ApplyOp>(
378 loc, entity, oneBasedIndices, lenParams)};
379 // Build hlfir.designate. The lower bounds may need to be added to
380 // the oneBasedIndices since hlfir.designate expect indices
381 // based on the array operand lower bounds.
382 mlir::Type resultType = hlfir::getVariableElementType(entity);
383 hlfir::DesignateOp designate;
384 llvm::SmallVector<mlir::Value> lbounds =
385 getNonDefaultLowerBounds(loc, builder, entity);
386 if (!lbounds.empty()) {
387 llvm::SmallVector<mlir::Value> indices;
388 mlir::Type idxTy = builder.getIndexType();
389 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
390 for (auto [oneBased, lb] : llvm::zip(oneBasedIndices, lbounds)) {
391 auto lbIdx = builder.createConvert(loc, idxTy, lb);
392 auto oneBasedIdx = builder.createConvert(loc, idxTy, oneBased);
393 auto shift = builder.create<mlir::arith::SubIOp>(loc, lbIdx, one);
394 mlir::Value index =
395 builder.create<mlir::arith::AddIOp>(loc, oneBasedIdx, shift);
396 indices.push_back(index);
397 }
398 designate = builder.create<hlfir::DesignateOp>(loc, resultType, entity,
399 indices, lenParams);
400 } else {
401 designate = builder.create<hlfir::DesignateOp>(loc, resultType, entity,
402 oneBasedIndices, lenParams);
403 }
404 return mlir::cast<fir::FortranVariableOpInterface>(designate.getOperation());
405 }
406
407 static mlir::Value genUBound(mlir::Location loc, fir::FirOpBuilder &builder,
408 mlir::Value lb, mlir::Value extent,
409 mlir::Value one) {
410 if (auto constantLb = fir::getIntIfConstant(lb))
411 if (*constantLb == 1)
412 return extent;
413 extent = builder.createConvert(loc, one.getType(), extent);
414 lb = builder.createConvert(loc, one.getType(), lb);
415 auto add = builder.create<mlir::arith::AddIOp>(loc, lb, extent);
416 return builder.create<mlir::arith::SubIOp>(loc, add, one);
417 }
418
419 llvm::SmallVector<std::pair<mlir::Value, mlir::Value>>
420 hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder,
421 Entity entity) {
422 if (mlir::isa<hlfir::ExprType>(entity.getType()))
423 TODO(loc, "bounds of expressions in hlfir");
424 auto [exv, cleanup] = translateToExtendedValue(loc, builder, entity);
425 assert(!cleanup && "translation of entity should not yield cleanup");
426 if (const auto *mutableBox = exv.getBoxOf<fir::MutableBoxValue>())
427 exv = fir::factory::genMutableBoxRead(builder, loc, *mutableBox);
428 mlir::Type idxTy = builder.getIndexType();
429 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
430 llvm::SmallVector<std::pair<mlir::Value, mlir::Value>> result;
431 for (unsigned dim = 0; dim < exv.rank(); ++dim) {
432 mlir::Value extent = fir::factory::readExtent(builder, loc, exv, dim);
433 mlir::Value lb = fir::factory::readLowerBound(builder, loc, exv, dim, one);
434 mlir::Value ub = genUBound(loc, builder, lb, extent, one);
435 result.push_back({lb, ub});
436 }
437 return result;
438 }
439
440 llvm::SmallVector<std::pair<mlir::Value, mlir::Value>>
441 hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder,
442 mlir::Value shape) {
443 assert((mlir::isa<fir::ShapeShiftType>(shape.getType()) ||
444 mlir::isa<fir::ShapeType>(shape.getType())) &&
445 "shape must contain extents");
446 auto extents = hlfir::getExplicitExtentsFromShape(shape, builder);
447 auto lowers = getExplicitLboundsFromShape(shape);
448 assert(lowers.empty() || lowers.size() == extents.size());
449 mlir::Type idxTy = builder.getIndexType();
450 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
451 llvm::SmallVector<std::pair<mlir::Value, mlir::Value>> result;
452 for (auto extent : llvm::enumerate(extents)) {
453 mlir::Value lb = lowers.empty() ? one : lowers[extent.index()];
454 mlir::Value ub = lowers.empty()
455 ? extent.value()
456 : genUBound(loc, builder, lb, extent.value(), one);
457 result.push_back({lb, ub});
458 }
459 return result;
460 }
461
462 llvm::SmallVector<mlir::Value> hlfir::genLowerbounds(mlir::Location loc,
463 fir::FirOpBuilder &builder,
464 mlir::Value shape,
465 unsigned rank) {
466 llvm::SmallVector<mlir::Value> lbounds;
467 if (shape)
468 lbounds = getExplicitLboundsFromShape(shape);
469 if (!lbounds.empty())
470 return lbounds;
471 mlir::Value one =
472 builder.createIntegerConstant(loc, builder.getIndexType(), 1);
473 return llvm::SmallVector<mlir::Value>(rank, one);
474 }
475
476 static hlfir::Entity followShapeInducingSource(hlfir::Entity entity) {
477 while (true) {
478 if (auto reassoc = entity.getDefiningOp<hlfir::NoReassocOp>()) {
479 entity = hlfir::Entity{reassoc.getVal()};
480 continue;
481 }
482 if (auto asExpr = entity.getDefiningOp<hlfir::AsExprOp>()) {
483 entity = hlfir::Entity{asExpr.getVar()};
484 continue;
485 }
486 break;
487 }
488 return entity;
489 }
490
491 static mlir::Value computeVariableExtent(mlir::Location loc,
492 fir::FirOpBuilder &builder,
493 hlfir::Entity variable,
494 fir::SequenceType seqTy,
495 unsigned dim) {
496 mlir::Type idxTy = builder.getIndexType();
497 if (seqTy.getShape().size() > dim) {
498 fir::SequenceType::Extent typeExtent = seqTy.getShape()[dim];
499 if (typeExtent != fir::SequenceType::getUnknownExtent())
500 return builder.createIntegerConstant(loc, idxTy, typeExtent);
501 }
502 assert(mlir::isa<fir::BaseBoxType>(variable.getType()) &&
503 "array variable with dynamic extent must be boxed");
504 mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim);
505 auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy,
506 variable, dimVal);
507 return dimInfo.getExtent();
508 }
509 llvm::SmallVector<mlir::Value> getVariableExtents(mlir::Location loc,
510 fir::FirOpBuilder &builder,
511 hlfir::Entity variable) {
512 llvm::SmallVector<mlir::Value> extents;
513 if (fir::FortranVariableOpInterface varIface =
514 variable.getIfVariableInterface()) {
515 extents = getExplicitExtents(varIface, builder);
516 if (!extents.empty())
517 return extents;
518 }
519
520 if (variable.isMutableBox())
521 variable = hlfir::derefPointersAndAllocatables(loc, builder, variable);
522 // Use the type shape information, and/or the fir.box/fir.class shape
523 // information if any extents are not static.
524 fir::SequenceType seqTy = mlir::cast<fir::SequenceType>(
525 hlfir::getFortranElementOrSequenceType(variable.getType()));
526 unsigned rank = seqTy.getShape().size();
527 for (unsigned dim = 0; dim < rank; ++dim)
528 extents.push_back(
529 computeVariableExtent(loc, builder, variable, seqTy, dim));
530 return extents;
531 }
532
533 static mlir::Value tryRetrievingShapeOrShift(hlfir::Entity entity) {
534 if (mlir::isa<hlfir::ExprType>(entity.getType())) {
535 if (auto elemental = entity.getDefiningOp<hlfir::ElementalOp>())
536 return elemental.getShape();
537 return mlir::Value{};
538 }
539 if (auto varIface = entity.getIfVariableInterface())
540 return varIface.getShape();
541 return {};
542 }
543
544 mlir::Value hlfir::genShape(mlir::Location loc, fir::FirOpBuilder &builder,
545 hlfir::Entity entity) {
546 assert(entity.isArray() && "entity must be an array");
547 entity = followShapeInducingSource(entity);
548 assert(entity && "what?");
549 if (auto shape = tryRetrievingShapeOrShift(entity)) {
550 if (mlir::isa<fir::ShapeType>(shape.getType()))
551 return shape;
552 if (mlir::isa<fir::ShapeShiftType>(shape.getType()))
553 if (auto s = shape.getDefiningOp<fir::ShapeShiftOp>())
554 return builder.create<fir::ShapeOp>(loc, s.getExtents());
555 }
556 if (mlir::isa<hlfir::ExprType>(entity.getType()))
557 return builder.create<hlfir::ShapeOfOp>(loc, entity.getBase());
558 // There is no shape lying around for this entity. Retrieve the extents and
559 // build a new fir.shape.
560 return builder.create<fir::ShapeOp>(loc,
561 getVariableExtents(loc, builder, entity));
562 }
563
564 llvm::SmallVector<mlir::Value>
565 hlfir::getIndexExtents(mlir::Location loc, fir::FirOpBuilder &builder,
566 mlir::Value shape) {
567 llvm::SmallVector<mlir::Value> extents =
568 hlfir::getExplicitExtentsFromShape(shape, builder);
569 mlir::Type indexType = builder.getIndexType();
570 for (auto &extent : extents)
571 extent = builder.createConvert(loc, indexType, extent);
572 return extents;
573 }
574
575 mlir::Value hlfir::genExtent(mlir::Location loc, fir::FirOpBuilder &builder,
576 hlfir::Entity entity, unsigned dim) {
577 entity = followShapeInducingSource(entity);
578 if (auto shape = tryRetrievingShapeOrShift(entity)) {
579 auto extents = hlfir::getExplicitExtentsFromShape(shape, builder);
580 if (!extents.empty()) {
581 assert(extents.size() > dim && "bad inquiry");
582 return extents[dim];
583 }
584 }
585 if (entity.isVariable()) {
586 if (entity.isMutableBox())
587 entity = hlfir::derefPointersAndAllocatables(loc, builder, entity);
588 // Use the type shape information, and/or the fir.box/fir.class shape
589 // information if any extents are not static.
590 fir::SequenceType seqTy = mlir::cast<fir::SequenceType>(
591 hlfir::getFortranElementOrSequenceType(entity.getType()));
592 return computeVariableExtent(loc, builder, entity, seqTy, dim);
593 }
594 TODO(loc, "get extent from HLFIR expr without producer holding the shape");
595 }
596
597 mlir::Value hlfir::genLBound(mlir::Location loc, fir::FirOpBuilder &builder,
598 hlfir::Entity entity, unsigned dim) {
599 if (!entity.mayHaveNonDefaultLowerBounds())
600 return builder.createIntegerConstant(loc, builder.getIndexType(), 1);
601 if (auto shape = tryRetrievingShapeOrShift(entity)) {
602 auto lbounds = getExplicitLboundsFromShape(shape);
603 if (!lbounds.empty()) {
604 assert(lbounds.size() > dim && "bad inquiry");
605 return lbounds[dim];
606 }
607 }
608 if (entity.isMutableBox())
609 entity = hlfir::derefPointersAndAllocatables(loc, builder, entity);
610 assert(mlir::isa<fir::BaseBoxType>(entity.getType()) && "must be a box");
611 mlir::Type idxTy = builder.getIndexType();
612 mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim);
613 auto dimInfo =
614 builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, entity, dimVal);
615 return dimInfo.getLowerBound();
616 }
617
618 void hlfir::genLengthParameters(mlir::Location loc, fir::FirOpBuilder &builder,
619 Entity entity,
620 llvm::SmallVectorImpl<mlir::Value> &result) {
621 if (!entity.hasLengthParameters())
622 return;
623 if (mlir::isa<hlfir::ExprType>(entity.getType())) {
624 mlir::Value expr = entity;
625 if (auto reassoc = expr.getDefiningOp<hlfir::NoReassocOp>())
626 expr = reassoc.getVal();
627 // Going through fir::ExtendedValue would create a temp,
628 // which is not desired for an inquiry.
629 // TODO: make this an interface when adding further character producing ops.
630 if (auto concat = expr.getDefiningOp<hlfir::ConcatOp>()) {
631 result.push_back(concat.getLength());
632 return;
633 } else if (auto concat = expr.getDefiningOp<hlfir::SetLengthOp>()) {
634 result.push_back(concat.getLength());
635 return;
636 } else if (auto asExpr = expr.getDefiningOp<hlfir::AsExprOp>()) {
637 hlfir::genLengthParameters(loc, builder, hlfir::Entity{asExpr.getVar()},
638 result);
639 return;
640 } else if (auto elemental = expr.getDefiningOp<hlfir::ElementalOp>()) {
641 result.append(elemental.getTypeparams().begin(),
642 elemental.getTypeparams().end());
643 return;
644 } else if (auto apply = expr.getDefiningOp<hlfir::ApplyOp>()) {
645 result.append(apply.getTypeparams().begin(), apply.getTypeparams().end());
646 return;
647 }
648 if (entity.isCharacter()) {
649 result.push_back(builder.create<hlfir::GetLengthOp>(loc, expr));
650 return;
651 }
652 TODO(loc, "inquire PDTs length parameters of hlfir.expr");
653 }
654
655 if (entity.isCharacter()) {
656 result.push_back(genCharacterVariableLength(loc, builder, entity));
657 return;
658 }
659 TODO(loc, "inquire PDTs length parameters in HLFIR");
660 }
661
662 mlir::Value hlfir::genCharLength(mlir::Location loc, fir::FirOpBuilder &builder,
663 hlfir::Entity entity) {
664 llvm::SmallVector<mlir::Value, 1> lenParams;
665 genLengthParameters(loc, builder, entity, lenParams);
666 assert(lenParams.size() == 1 && "characters must have one length parameters");
667 return lenParams[0];
668 }
669
670 mlir::Value hlfir::genRank(mlir::Location loc, fir::FirOpBuilder &builder,
671 hlfir::Entity entity, mlir::Type resultType) {
672 if (!entity.isAssumedRank())
673 return builder.createIntegerConstant(loc, resultType, entity.getRank());
674 assert(entity.isBoxAddressOrValue() &&
675 "assumed-ranks are box addresses or values");
676 return builder.create<fir::BoxRankOp>(loc, resultType, entity);
677 }
678
679 // Return a "shape" that can be used in fir.embox/fir.rebox with \p exv base.
680 static mlir::Value asEmboxShape(mlir::Location loc, fir::FirOpBuilder &builder,
681 const fir::ExtendedValue &exv,
682 mlir::Value shape) {
683 if (!shape)
684 return shape;
685 // fir.rebox does not need and does not accept extents (fir.shape or
686 // fir.shape_shift) since this information is already in the input fir.box,
687 // it only accepts fir.shift because local lower bounds may not be reflected
688 // in the fir.box.
689 if (mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType()) &&
690 !mlir::isa<fir::ShiftType>(shape.getType()))
691 return builder.createShape(loc, exv);
692 return shape;
693 }
694
695 std::pair<mlir::Value, mlir::Value> hlfir::genVariableFirBaseShapeAndParams(
696 mlir::Location loc, fir::FirOpBuilder &builder, Entity entity,
697 llvm::SmallVectorImpl<mlir::Value> &typeParams) {
698 auto [exv, cleanup] = translateToExtendedValue(loc, builder, entity);
699 assert(!cleanup && "variable to Exv should not produce cleanup");
700 if (entity.hasLengthParameters()) {
701 auto params = fir::getTypeParams(exv);
702 typeParams.append(params.begin(), params.end());
703 }
704 if (entity.isScalar())
705 return {fir::getBase(exv), mlir::Value{}};
706 if (auto variableInterface = entity.getIfVariableInterface())
707 return {fir::getBase(exv),
708 asEmboxShape(loc, builder, exv, variableInterface.getShape())};
709 return {fir::getBase(exv), builder.createShape(loc, exv)};
710 }
711
712 hlfir::Entity hlfir::derefPointersAndAllocatables(mlir::Location loc,
713 fir::FirOpBuilder &builder,
714 Entity entity) {
715 if (entity.isMutableBox()) {
716 hlfir::Entity boxLoad{builder.create<fir::LoadOp>(loc, entity)};
717 if (entity.isScalar()) {
718 if (!entity.isPolymorphic() && !entity.hasLengthParameters())
719 return hlfir::Entity{builder.create<fir::BoxAddrOp>(loc, boxLoad)};
720 mlir::Type elementType = boxLoad.getFortranElementType();
721 if (auto charType = mlir::dyn_cast<fir::CharacterType>(elementType)) {
722 mlir::Value base = builder.create<fir::BoxAddrOp>(loc, boxLoad);
723 if (charType.hasConstantLen())
724 return hlfir::Entity{base};
725 mlir::Value len = genCharacterVariableLength(loc, builder, entity);
726 auto boxCharType =
727 fir::BoxCharType::get(builder.getContext(), charType.getFKind());
728 return hlfir::Entity{
729 builder.create<fir::EmboxCharOp>(loc, boxCharType, base, len)
730 .getResult()};
731 }
732 }
733 // Otherwise, the entity is either an array, a polymorphic entity, or a
734 // derived type with length parameters. All these entities require a fir.box
735 // or fir.class to hold bounds, dynamic type or length parameter
736 // information. Keep them boxed.
737 return boxLoad;
738 } else if (entity.isProcedurePointer()) {
739 return hlfir::Entity{builder.create<fir::LoadOp>(loc, entity)};
740 }
741 return entity;
742 }
743
744 mlir::Type hlfir::getVariableElementType(hlfir::Entity variable) {
745 assert(variable.isVariable() && "entity must be a variable");
746 if (variable.isScalar())
747 return variable.getType();
748 mlir::Type eleTy = variable.getFortranElementType();
749 if (variable.isPolymorphic())
750 return fir::ClassType::get(eleTy);
751 if (auto charType = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
752 if (charType.hasDynamicLen())
753 return fir::BoxCharType::get(charType.getContext(), charType.getFKind());
754 } else if (fir::isRecordWithTypeParameters(eleTy)) {
755 return fir::BoxType::get(eleTy);
756 }
757 return fir::ReferenceType::get(eleTy);
758 }
759
760 mlir::Type hlfir::getEntityElementType(hlfir::Entity entity) {
761 if (entity.isVariable())
762 return getVariableElementType(entity);
763 if (entity.isScalar())
764 return entity.getType();
765 auto exprType = mlir::dyn_cast<hlfir::ExprType>(entity.getType());
766 assert(exprType && "array value must be an hlfir.expr");
767 return exprType.getElementExprType();
768 }
769
770 static hlfir::ExprType getArrayExprType(mlir::Type elementType,
771 mlir::Value shape, bool isPolymorphic) {
772 unsigned rank = mlir::cast<fir::ShapeType>(shape.getType()).getRank();
773 hlfir::ExprType::Shape typeShape(rank, hlfir::ExprType::getUnknownExtent());
774 if (auto shapeOp = shape.getDefiningOp<fir::ShapeOp>())
775 for (auto extent : llvm::enumerate(shapeOp.getExtents()))
776 if (auto cstExtent = fir::getIntIfConstant(extent.value()))
777 typeShape[extent.index()] = *cstExtent;
778 return hlfir::ExprType::get(elementType.getContext(), typeShape, elementType,
779 isPolymorphic);
780 }
781
782 hlfir::ElementalOp hlfir::genElementalOp(
783 mlir::Location loc, fir::FirOpBuilder &builder, mlir::Type elementType,
784 mlir::Value shape, mlir::ValueRange typeParams,
785 const ElementalKernelGenerator &genKernel, bool isUnordered,
786 mlir::Value polymorphicMold, mlir::Type exprType) {
787 if (!exprType)
788 exprType = getArrayExprType(elementType, shape, !!polymorphicMold);
789 auto elementalOp = builder.create<hlfir::ElementalOp>(
790 loc, exprType, shape, polymorphicMold, typeParams, isUnordered);
791 auto insertPt = builder.saveInsertionPoint();
792 builder.setInsertionPointToStart(elementalOp.getBody());
793 mlir::Value elementResult = genKernel(loc, builder, elementalOp.getIndices());
794 // Numerical and logical scalars may be lowered to another type than the
795 // Fortran expression type (e.g i1 instead of fir.logical). Array expression
796 // values are typed according to their Fortran type. Insert a cast if needed
797 // here.
798 if (fir::isa_trivial(elementResult.getType()))
799 elementResult = builder.createConvert(loc, elementType, elementResult);
800 builder.create<hlfir::YieldElementOp>(loc, elementResult);
801 builder.restoreInsertionPoint(insertPt);
802 return elementalOp;
803 }
804
805 // TODO: we do not actually need to clone the YieldElementOp,
806 // because returning its getElementValue() operand should be enough
807 // for all callers of this function.
808 hlfir::YieldElementOp
809 hlfir::inlineElementalOp(mlir::Location loc, fir::FirOpBuilder &builder,
810 hlfir::ElementalOp elemental,
811 mlir::ValueRange oneBasedIndices) {
812 // hlfir.elemental region is a SizedRegion<1>.
813 assert(elemental.getRegion().hasOneBlock() &&
814 "expect elemental region to have one block");
815 mlir::IRMapping mapper;
816 mapper.map(elemental.getIndices(), oneBasedIndices);
817 mlir::Operation *newOp;
818 for (auto &op : elemental.getRegion().back().getOperations())
819 newOp = builder.clone(op, mapper);
820 auto yield = mlir::dyn_cast_or_null<hlfir::YieldElementOp>(newOp);
821 assert(yield && "last ElementalOp operation must be am hlfir.yield_element");
822 return yield;
823 }
824
825 mlir::Value hlfir::inlineElementalOp(
826 mlir::Location loc, fir::FirOpBuilder &builder,
827 hlfir::ElementalOpInterface elemental, mlir::ValueRange oneBasedIndices,
828 mlir::IRMapping &mapper,
829 const std::function<bool(hlfir::ElementalOp)> &mustRecursivelyInline) {
830 mlir::Region &region = elemental.getElementalRegion();
831 // hlfir.elemental region is a SizedRegion<1>.
832 assert(region.hasOneBlock() && "elemental region must have one block");
833 mapper.map(elemental.getIndices(), oneBasedIndices);
834 for (auto &op : region.front().without_terminator()) {
835 if (auto apply = mlir::dyn_cast<hlfir::ApplyOp>(op))
836 if (auto appliedElemental =
837 apply.getExpr().getDefiningOp<hlfir::ElementalOp>())
838 if (mustRecursivelyInline(appliedElemental)) {
839 llvm::SmallVector<mlir::Value> clonedApplyIndices;
840 for (auto indice : apply.getIndices())
841 clonedApplyIndices.push_back(mapper.lookupOrDefault(indice));
842 hlfir::ElementalOpInterface elementalIface =
843 mlir::cast<hlfir::ElementalOpInterface>(
844 appliedElemental.getOperation());
845 mlir::Value inlined = inlineElementalOp(loc, builder, elementalIface,
846 clonedApplyIndices, mapper,
847 mustRecursivelyInline);
848 mapper.map(apply.getResult(), inlined);
849 continue;
850 }
851 (void)builder.clone(op, mapper);
852 }
853 return mapper.lookupOrDefault(elemental.getElementEntity());
854 }
855
856 hlfir::LoopNest hlfir::genLoopNest(mlir::Location loc,
857 fir::FirOpBuilder &builder,
858 mlir::ValueRange extents, bool isUnordered) {
859 hlfir::LoopNest loopNest;
860 assert(!extents.empty() && "must have at least one extent");
861 auto insPt = builder.saveInsertionPoint();
862 loopNest.oneBasedIndices.assign(extents.size(), mlir::Value{});
863 // Build loop nest from column to row.
864 auto one = builder.create<mlir::arith::ConstantIndexOp>(loc, 1);
865 mlir::Type indexType = builder.getIndexType();
866 unsigned dim = extents.size() - 1;
867 for (auto extent : llvm::reverse(extents)) {
868 auto ub = builder.createConvert(loc, indexType, extent);
869 loopNest.innerLoop =
870 builder.create<fir::DoLoopOp>(loc, one, ub, one, isUnordered);
871 builder.setInsertionPointToStart(loopNest.innerLoop.getBody());
872 // Reverse the indices so they are in column-major order.
873 loopNest.oneBasedIndices[dim--] = loopNest.innerLoop.getInductionVar();
874 if (!loopNest.outerLoop)
875 loopNest.outerLoop = loopNest.innerLoop;
876 }
877 builder.restoreInsertionPoint(insPt);
878 return loopNest;
879 }
880
881 static fir::ExtendedValue translateVariableToExtendedValue(
882 mlir::Location loc, fir::FirOpBuilder &builder, hlfir::Entity variable,
883 bool forceHlfirBase = false, bool contiguousHint = false) {
884 assert(variable.isVariable() && "must be a variable");
885 // When going towards FIR, use the original base value to avoid
886 // introducing descriptors at runtime when they are not required.
887 // This is not done for assumed-rank since the fir::ExtendedValue cannot
888 // held the related lower bounds in an vector. The lower bounds of the
889 // descriptor must always be used instead.
890
891 mlir::Value base = (forceHlfirBase || variable.isAssumedRank())
892 ? variable.getBase()
893 : variable.getFirBase();
894 if (variable.isMutableBox())
895 return fir::MutableBoxValue(base, getExplicitTypeParams(variable),
896 fir::MutableProperties{});
897
898 if (mlir::isa<fir::BaseBoxType>(base.getType())) {
899 const bool contiguous = variable.isSimplyContiguous() || contiguousHint;
900 const bool isAssumedRank = variable.isAssumedRank();
901 if (!contiguous || variable.isPolymorphic() ||
902 variable.isDerivedWithLengthParameters() || variable.isOptional() ||
903 isAssumedRank) {
904 llvm::SmallVector<mlir::Value> nonDefaultLbounds;
905 if (!isAssumedRank)
906 nonDefaultLbounds = getNonDefaultLowerBounds(loc, builder, variable);
907 return fir::BoxValue(base, nonDefaultLbounds,
908 getExplicitTypeParams(variable));
909 }
910 // Otherwise, the variable can be represented in a fir::ExtendedValue
911 // without the overhead of a fir.box.
912 base = genVariableRawAddress(loc, builder, variable);
913 }
914
915 if (variable.isScalar()) {
916 if (variable.isCharacter()) {
917 if (mlir::isa<fir::BoxCharType>(base.getType()))
918 return genUnboxChar(loc, builder, base);
919 mlir::Value len = genCharacterVariableLength(loc, builder, variable);
920 return fir::CharBoxValue{base, len};
921 }
922 return base;
923 }
924 llvm::SmallVector<mlir::Value> extents;
925 llvm::SmallVector<mlir::Value> nonDefaultLbounds;
926 if (mlir::isa<fir::BaseBoxType>(variable.getType()) &&
927 !variable.getIfVariableInterface() &&
928 variable.mayHaveNonDefaultLowerBounds()) {
929 // This special case avoids generating two sets of identical
930 // fir.box_dim to get both the lower bounds and extents.
931 genLboundsAndExtentsFromBox(loc, builder, variable, nonDefaultLbounds,
932 &extents);
933 } else {
934 extents = getVariableExtents(loc, builder, variable);
935 nonDefaultLbounds = getNonDefaultLowerBounds(loc, builder, variable);
936 }
937 if (variable.isCharacter())
938 return fir::CharArrayBoxValue{
939 base, genCharacterVariableLength(loc, builder, variable), extents,
940 nonDefaultLbounds};
941 return fir::ArrayBoxValue{base, extents, nonDefaultLbounds};
942 }
943
944 fir::ExtendedValue
945 hlfir::translateToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
946 fir::FortranVariableOpInterface var,
947 bool forceHlfirBase) {
948 return translateVariableToExtendedValue(loc, builder, var, forceHlfirBase);
949 }
950
951 std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>
952 hlfir::translateToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
953 hlfir::Entity entity, bool contiguousHint) {
954 if (entity.isVariable())
955 return {translateVariableToExtendedValue(loc, builder, entity, false,
956 contiguousHint),
957 std::nullopt};
958
959 if (entity.isProcedure()) {
960 if (fir::isCharacterProcedureTuple(entity.getType())) {
961 auto [boxProc, len] = fir::factory::extractCharacterProcedureTuple(
962 builder, loc, entity, /*openBoxProc=*/false);
963 return {fir::CharBoxValue{boxProc, len}, std::nullopt};
964 }
965 return {static_cast<mlir::Value>(entity), std::nullopt};
966 }
967
968 if (mlir::isa<hlfir::ExprType>(entity.getType())) {
969 mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
970 hlfir::AssociateOp associate = hlfir::genAssociateExpr(
971 loc, builder, entity, entity.getType(), "", byRefAttr);
972 auto *bldr = &builder;
973 hlfir::CleanupFunction cleanup = [bldr, loc, associate]() -> void {
974 bldr->create<hlfir::EndAssociateOp>(loc, associate);
975 };
976 hlfir::Entity temp{associate.getBase()};
977 return {translateToExtendedValue(loc, builder, temp).first, cleanup};
978 }
979 return {{static_cast<mlir::Value>(entity)}, {}};
980 }
981
982 std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>
983 hlfir::convertToValue(mlir::Location loc, fir::FirOpBuilder &builder,
984 hlfir::Entity entity) {
985 // Load scalar references to integer, logical, real, or complex value
986 // to an mlir value, dereference allocatable and pointers, and get rid
987 // of fir.box that are not needed or create a copy into contiguous memory.
988 auto derefedAndLoadedEntity = loadTrivialScalar(loc, builder, entity);
989 return translateToExtendedValue(loc, builder, derefedAndLoadedEntity);
990 }
991
992 static fir::ExtendedValue placeTrivialInMemory(mlir::Location loc,
993 fir::FirOpBuilder &builder,
994 mlir::Value val,
995 mlir::Type targetType) {
996 auto temp = builder.createTemporary(loc, targetType);
997 if (targetType != val.getType())
998 builder.createStoreWithConvert(loc, val, temp);
999 else
1000 builder.create<fir::StoreOp>(loc, val, temp);
1001 return temp;
1002 }
1003
1004 std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>
1005 hlfir::convertToBox(mlir::Location loc, fir::FirOpBuilder &builder,
1006 hlfir::Entity entity, mlir::Type targetType) {
1007 // fir::factory::createBoxValue is not meant to deal with procedures.
1008 // Dereference procedure pointers here.
1009 if (entity.isProcedurePointer())
1010 entity = hlfir::derefPointersAndAllocatables(loc, builder, entity);
1011
1012 auto [exv, cleanup] = translateToExtendedValue(loc, builder, entity);
1013 // Procedure entities should not go through createBoxValue that embox
1014 // object entities. Return the fir.boxproc directly.
1015 if (entity.isProcedure())
1016 return {exv, cleanup};
1017 mlir::Value base = fir::getBase(exv);
1018 if (fir::isa_trivial(base.getType()))
1019 exv = placeTrivialInMemory(loc, builder, base, targetType);
1020 fir::BoxValue box = fir::factory::createBoxValue(builder, loc, exv);
1021 return {box, cleanup};
1022 }
1023
1024 std::pair<fir::ExtendedValue, std::optional<hlfir::CleanupFunction>>
1025 hlfir::convertToAddress(mlir::Location loc, fir::FirOpBuilder &builder,
1026 hlfir::Entity entity, mlir::Type targetType) {
1027 hlfir::Entity derefedEntity =
1028 hlfir::derefPointersAndAllocatables(loc, builder, entity);
1029 auto [exv, cleanup] =
1030 hlfir::translateToExtendedValue(loc, builder, derefedEntity);
1031 mlir::Value base = fir::getBase(exv);
1032 if (fir::isa_trivial(base.getType()))
1033 exv = placeTrivialInMemory(loc, builder, base, targetType);
1034 return {exv, cleanup};
1035 }
1036
1037 /// Clone:
1038 /// ```
1039 /// hlfir.elemental_addr %shape : !fir.shape<1> {
1040 /// ^bb0(%i : index)
1041 /// .....
1042 /// %hlfir.yield %scalarAddress : fir.ref<T>
1043 /// }
1044 /// ```
1045 //
1046 /// into
1047 ///
1048 /// ```
1049 /// %expr = hlfir.elemental %shape : (!fir.shape<1>) -> hlfir.expr<?xT> {
1050 /// ^bb0(%i : index)
1051 /// .....
1052 /// %value = fir.load %scalarAddress : fir.ref<T>
1053 /// %hlfir.yield_element %value : T
1054 /// }
1055 /// ```
1056 hlfir::ElementalOp
1057 hlfir::cloneToElementalOp(mlir::Location loc, fir::FirOpBuilder &builder,
1058 hlfir::ElementalAddrOp elementalAddrOp) {
1059 hlfir::Entity scalarAddress =
1060 hlfir::Entity{mlir::cast<hlfir::YieldOp>(
1061 elementalAddrOp.getBody().back().getTerminator())
1062 .getEntity()};
1063 llvm::SmallVector<mlir::Value, 1> typeParams;
1064 hlfir::genLengthParameters(loc, builder, scalarAddress, typeParams);
1065
1066 builder.setInsertionPointAfter(elementalAddrOp);
1067 auto genKernel = [&](mlir::Location l, fir::FirOpBuilder &b,
1068 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
1069 mlir::IRMapping mapper;
1070 mapper.map(elementalAddrOp.getIndices(), oneBasedIndices);
1071 mlir::Operation *newOp = nullptr;
1072 for (auto &op : elementalAddrOp.getBody().back().getOperations())
1073 newOp = b.clone(op, mapper);
1074 auto newYielOp = mlir::dyn_cast_or_null<hlfir::YieldOp>(newOp);
1075 assert(newYielOp && "hlfir.elemental_addr is ill formed");
1076 hlfir::Entity newAddr{newYielOp.getEntity()};
1077 newYielOp->erase();
1078 return hlfir::loadTrivialScalar(l, b, newAddr);
1079 };
1080 mlir::Type elementType = scalarAddress.getFortranElementType();
1081 return hlfir::genElementalOp(
1082 loc, builder, elementType, elementalAddrOp.getShape(), typeParams,
1083 genKernel, !elementalAddrOp.isOrdered(), elementalAddrOp.getMold());
1084 }
1085
1086 bool hlfir::elementalOpMustProduceTemp(hlfir::ElementalOp elemental) {
1087 for (mlir::Operation *useOp : elemental->getUsers())
1088 if (auto destroy = mlir::dyn_cast<hlfir::DestroyOp>(useOp))
1089 if (destroy.mustFinalizeExpr())
1090 return true;
1091
1092 return false;
1093 }
1094
1095 std::pair<hlfir::Entity, mlir::Value>
1096 hlfir::createTempFromMold(mlir::Location loc, fir::FirOpBuilder &builder,
1097 hlfir::Entity mold) {
1098 llvm::SmallVector<mlir::Value> lenParams;
1099 hlfir::genLengthParameters(loc, builder, mold, lenParams);
1100 llvm::StringRef tmpName{".tmp"};
1101 mlir::Value alloc;
1102 mlir::Value isHeapAlloc;
1103 mlir::Value shape{};
1104 fir::FortranVariableFlagsAttr declAttrs;
1105
1106 if (mold.isPolymorphic()) {
1107 // Create unallocated polymorphic temporary using the dynamic type
1108 // of the mold. The static type of the temporary matches
1109 // the static type of the mold, but then the dynamic type
1110 // of the mold is applied to the temporary's descriptor.
1111
1112 if (mold.isArray())
1113 hlfir::genShape(loc, builder, mold);
1114
1115 // Create polymorphic allocatable box on the stack.
1116 mlir::Type boxHeapType = fir::HeapType::get(fir::unwrapRefType(
1117 mlir::cast<fir::BaseBoxType>(mold.getType()).getEleTy()));
1118 // The box must be initialized, because AllocatableApplyMold
1119 // may read its contents (e.g. for checking whether it is allocated).
1120 alloc = fir::factory::genNullBoxStorage(builder, loc,
1121 fir::ClassType::get(boxHeapType));
1122 // The temporary is unallocated even after AllocatableApplyMold below.
1123 // If the temporary is used as assignment LHS it will be automatically
1124 // allocated on the heap, as long as we use Assign family
1125 // runtime functions. So set MustFree to true.
1126 isHeapAlloc = builder.createBool(loc, true);
1127 declAttrs = fir::FortranVariableFlagsAttr::get(
1128 builder.getContext(), fir::FortranVariableFlagsEnum::allocatable);
1129 } else if (mold.isArray()) {
1130 mlir::Type sequenceType =
1131 hlfir::getFortranElementOrSequenceType(mold.getType());
1132 shape = hlfir::genShape(loc, builder, mold);
1133 auto extents = hlfir::getIndexExtents(loc, builder, shape);
1134 alloc = builder.createHeapTemporary(loc, sequenceType, tmpName, extents,
1135 lenParams);
1136 isHeapAlloc = builder.createBool(loc, true);
1137 } else {
1138 alloc = builder.createTemporary(loc, mold.getFortranElementType(), tmpName,
1139 /*shape=*/std::nullopt, lenParams);
1140 isHeapAlloc = builder.createBool(loc, false);
1141 }
1142 auto declareOp =
1143 builder.create<hlfir::DeclareOp>(loc, alloc, tmpName, shape, lenParams,
1144 /*dummy_scope=*/nullptr, declAttrs);
1145 if (mold.isPolymorphic()) {
1146 int rank = mold.getRank();
1147 // TODO: should probably read rank from the mold.
1148 if (rank < 0)
1149 TODO(loc, "create temporary for assumed rank polymorphic");
1150 fir::runtime::genAllocatableApplyMold(builder, loc, alloc,
1151 mold.getFirBase(), rank);
1152 }
1153
1154 return {hlfir::Entity{declareOp.getBase()}, isHeapAlloc};
1155 }
1156
1157 hlfir::Entity hlfir::createStackTempFromMold(mlir::Location loc,
1158 fir::FirOpBuilder &builder,
1159 hlfir::Entity mold) {
1160 llvm::SmallVector<mlir::Value> lenParams;
1161 hlfir::genLengthParameters(loc, builder, mold, lenParams);
1162 llvm::StringRef tmpName{".tmp"};
1163 mlir::Value alloc;
1164 mlir::Value shape{};
1165 fir::FortranVariableFlagsAttr declAttrs;
1166
1167 if (mold.isPolymorphic()) {
1168 // genAllocatableApplyMold does heap allocation
1169 TODO(loc, "createStackTempFromMold for polymorphic type");
1170 } else if (mold.isArray()) {
1171 mlir::Type sequenceType =
1172 hlfir::getFortranElementOrSequenceType(mold.getType());
1173 shape = hlfir::genShape(loc, builder, mold);
1174 auto extents = hlfir::getIndexExtents(loc, builder, shape);
1175 alloc =
1176 builder.createTemporary(loc, sequenceType, tmpName, extents, lenParams);
1177 } else {
1178 alloc = builder.createTemporary(loc, mold.getFortranElementType(), tmpName,
1179 /*shape=*/std::nullopt, lenParams);
1180 }
1181 auto declareOp =
1182 builder.create<hlfir::DeclareOp>(loc, alloc, tmpName, shape, lenParams,
1183 /*dummy_scope=*/nullptr, declAttrs);
1184 return hlfir::Entity{declareOp.getBase()};
1185 }
1186
1187 hlfir::EntityWithAttributes
1188 hlfir::convertCharacterKind(mlir::Location loc, fir::FirOpBuilder &builder,
1189 hlfir::Entity scalarChar, int toKind) {
1190 auto src = hlfir::convertToAddress(loc, builder, scalarChar,
1191 scalarChar.getFortranElementType());
1192 assert(src.first.getCharBox() && "must be scalar character");
1193 fir::CharBoxValue res = fir::factory::convertCharacterKind(
1194 builder, loc, *src.first.getCharBox(), toKind);
1195 if (src.second.has_value())
1196 src.second.value()();
1197
1198 return hlfir::EntityWithAttributes{builder.create<hlfir::DeclareOp>(
1199 loc, res.getAddr(), ".temp.kindconvert", /*shape=*/nullptr,
1200 /*typeparams=*/mlir::ValueRange{res.getLen()},
1201 /*dummy_scope=*/nullptr, fir::FortranVariableFlagsAttr{})};
1202 }
1203
1204 std::pair<hlfir::Entity, std::optional<hlfir::CleanupFunction>>
1205 hlfir::genTypeAndKindConvert(mlir::Location loc, fir::FirOpBuilder &builder,
1206 hlfir::Entity source, mlir::Type toType,
1207 bool preserveLowerBounds) {
1208 mlir::Type fromType = source.getFortranElementType();
1209 toType = hlfir::getFortranElementType(toType);
1210 if (!toType || fromType == toType ||
1211 !(fir::isa_trivial(toType) || mlir::isa<fir::CharacterType>(toType)))
1212 return {source, std::nullopt};
1213
1214 std::optional<int> toKindCharConvert;
1215 if (auto toCharTy = mlir::dyn_cast<fir::CharacterType>(toType)) {
1216 if (auto fromCharTy = mlir::dyn_cast<fir::CharacterType>(fromType))
1217 if (toCharTy.getFKind() != fromCharTy.getFKind()) {
1218 toKindCharConvert = toCharTy.getFKind();
1219 // Preserve source length (padding/truncation will occur in assignment
1220 // if needed).
1221 toType = fir::CharacterType::get(
1222 fromType.getContext(), toCharTy.getFKind(), fromCharTy.getLen());
1223 }
1224 // Do not convert in case of character length mismatch only, hlfir.assign
1225 // deals with it.
1226 if (!toKindCharConvert)
1227 return {source, std::nullopt};
1228 }
1229
1230 if (source.getRank() == 0) {
1231 mlir::Value cast = toKindCharConvert
1232 ? mlir::Value{hlfir::convertCharacterKind(
1233 loc, builder, source, *toKindCharConvert)}
1234 : builder.convertWithSemantics(loc, toType, source);
1235 return {hlfir::Entity{cast}, std::nullopt};
1236 }
1237
1238 mlir::Value shape = hlfir::genShape(loc, builder, source);
1239 auto genKernel = [source, toType, toKindCharConvert](
1240 mlir::Location loc, fir::FirOpBuilder &builder,
1241 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
1242 auto elementPtr =
1243 hlfir::getElementAt(loc, builder, source, oneBasedIndices);
1244 auto val = hlfir::loadTrivialScalar(loc, builder, elementPtr);
1245 if (toKindCharConvert)
1246 return hlfir::convertCharacterKind(loc, builder, val, *toKindCharConvert);
1247 return hlfir::EntityWithAttributes{
1248 builder.convertWithSemantics(loc, toType, val)};
1249 };
1250 llvm::SmallVector<mlir::Value, 1> lenParams;
1251 hlfir::genLengthParameters(loc, builder, source, lenParams);
1252 mlir::Value convertedRhs =
1253 hlfir::genElementalOp(loc, builder, toType, shape, lenParams, genKernel,
1254 /*isUnordered=*/true);
1255
1256 if (preserveLowerBounds && source.mayHaveNonDefaultLowerBounds()) {
1257 hlfir::AssociateOp associate =
1258 genAssociateExpr(loc, builder, hlfir::Entity{convertedRhs},
1259 convertedRhs.getType(), ".tmp.keeplbounds");
1260 fir::ShapeOp shapeOp = associate.getShape().getDefiningOp<fir::ShapeOp>();
1261 assert(shapeOp && "associate shape must be a fir.shape");
1262 const unsigned rank = shapeOp.getExtents().size();
1263 llvm::SmallVector<mlir::Value> lbAndExtents;
1264 for (unsigned dim = 0; dim < rank; ++dim) {
1265 lbAndExtents.push_back(hlfir::genLBound(loc, builder, source, dim));
1266 lbAndExtents.push_back(shapeOp.getExtents()[dim]);
1267 }
1268 auto shapeShiftType = fir::ShapeShiftType::get(builder.getContext(), rank);
1269 mlir::Value shapeShift =
1270 builder.create<fir::ShapeShiftOp>(loc, shapeShiftType, lbAndExtents);
1271 auto declareOp = builder.create<hlfir::DeclareOp>(
1272 loc, associate.getFirBase(), *associate.getUniqName(), shapeShift,
1273 associate.getTypeparams(), /*dummy_scope=*/nullptr,
1274 /*flags=*/fir::FortranVariableFlagsAttr{});
1275 hlfir::Entity castWithLbounds =
1276 mlir::cast<fir::FortranVariableOpInterface>(declareOp.getOperation());
1277 fir::FirOpBuilder *bldr = &builder;
1278 auto cleanup = [loc, bldr, convertedRhs, associate]() {
1279 bldr->create<hlfir::EndAssociateOp>(loc, associate);
1280 bldr->create<hlfir::DestroyOp>(loc, convertedRhs);
1281 };
1282 return {castWithLbounds, cleanup};
1283 }
1284
1285 fir::FirOpBuilder *bldr = &builder;
1286 auto cleanup = [loc, bldr, convertedRhs]() {
1287 bldr->create<hlfir::DestroyOp>(loc, convertedRhs);
1288 };
1289 return {hlfir::Entity{convertedRhs}, cleanup};
1290 }