Debian Codegraph @

flang/lib/Optimizer/Builder/FIRBuilder.cpp

raw
1 //===-- FIRBuilder.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 #include "flang/Optimizer/Builder/FIRBuilder.h"
10 #include "flang/Optimizer/Builder/BoxValue.h"
11 #include "flang/Optimizer/Builder/Character.h"
12 #include "flang/Optimizer/Builder/Complex.h"
13 #include "flang/Optimizer/Builder/MutableBox.h"
14 #include "flang/Optimizer/Builder/Runtime/Assign.h"
15 #include "flang/Optimizer/Builder/Runtime/Derived.h"
16 #include "flang/Optimizer/Builder/Todo.h"
17 #include "flang/Optimizer/Dialect/FIRAttr.h"
18 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
19 #include "flang/Optimizer/Dialect/FIRType.h"
20 #include "flang/Optimizer/Support/FatalError.h"
21 #include "flang/Optimizer/Support/InternalNames.h"
22 #include "flang/Optimizer/Support/Utils.h"
23 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
24 #include "mlir/Dialect/OpenACC/OpenACC.h"
25 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MD5.h"
31 #include <optional>
32
33 static llvm::cl::opt<std::size_t>
34 nameLengthHashSize("length-to-hash-string-literal",
35 llvm::cl::desc("string literals that exceed this length"
36 " will use a hash value as their symbol "
37 "name"),
38 llvm::cl::init(32));
39
40 mlir::func::FuncOp
41 fir::FirOpBuilder::createFunction(mlir::Location loc, mlir::ModuleOp module,
42 llvm::StringRef name, mlir::FunctionType ty,
43 mlir::SymbolTable *symbolTable) {
44 return fir::createFuncOp(loc, module, name, ty, /*attrs*/ {}, symbolTable);
45 }
46
47 mlir::func::FuncOp
48 fir::FirOpBuilder::getNamedFunction(mlir::ModuleOp modOp,
49 const mlir::SymbolTable *symbolTable,
50 llvm::StringRef name) {
51 if (symbolTable)
52 if (auto func = symbolTable->lookup<mlir::func::FuncOp>(name)) {
53 #ifdef EXPENSIVE_CHECKS
54 assert(func == modOp.lookupSymbol<mlir::func::FuncOp>(name) &&
55 "symbolTable and module out of sync");
56 #endif
57 return func;
58 }
59 return modOp.lookupSymbol<mlir::func::FuncOp>(name);
60 }
61
62 mlir::func::FuncOp
63 fir::FirOpBuilder::getNamedFunction(mlir::ModuleOp modOp,
64 const mlir::SymbolTable *symbolTable,
65 mlir::SymbolRefAttr symbol) {
66 if (symbolTable)
67 if (auto func = symbolTable->lookup<mlir::func::FuncOp>(
68 symbol.getLeafReference())) {
69 #ifdef EXPENSIVE_CHECKS
70 assert(func == modOp.lookupSymbol<mlir::func::FuncOp>(symbol) &&
71 "symbolTable and module out of sync");
72 #endif
73 return func;
74 }
75 return modOp.lookupSymbol<mlir::func::FuncOp>(symbol);
76 }
77
78 fir::GlobalOp
79 fir::FirOpBuilder::getNamedGlobal(mlir::ModuleOp modOp,
80 const mlir::SymbolTable *symbolTable,
81 llvm::StringRef name) {
82 if (symbolTable)
83 if (auto global = symbolTable->lookup<fir::GlobalOp>(name)) {
84 #ifdef EXPENSIVE_CHECKS
85 assert(global == modOp.lookupSymbol<fir::GlobalOp>(name) &&
86 "symbolTable and module out of sync");
87 #endif
88 return global;
89 }
90 return modOp.lookupSymbol<fir::GlobalOp>(name);
91 }
92
93 mlir::Type fir::FirOpBuilder::getRefType(mlir::Type eleTy) {
94 assert(!mlir::isa<fir::ReferenceType>(eleTy) && "cannot be a reference type");
95 return fir::ReferenceType::get(eleTy);
96 }
97
98 mlir::Type fir::FirOpBuilder::getVarLenSeqTy(mlir::Type eleTy, unsigned rank) {
99 fir::SequenceType::Shape shape(rank, fir::SequenceType::getUnknownExtent());
100 return fir::SequenceType::get(shape, eleTy);
101 }
102
103 mlir::Type fir::FirOpBuilder::getRealType(int kind) {
104 switch (kindMap.getRealTypeID(kind)) {
105 case llvm::Type::TypeID::HalfTyID:
106 return mlir::FloatType::getF16(getContext());
107 case llvm::Type::TypeID::BFloatTyID:
108 return mlir::FloatType::getBF16(getContext());
109 case llvm::Type::TypeID::FloatTyID:
110 return mlir::FloatType::getF32(getContext());
111 case llvm::Type::TypeID::DoubleTyID:
112 return mlir::FloatType::getF64(getContext());
113 case llvm::Type::TypeID::X86_FP80TyID:
114 return mlir::FloatType::getF80(getContext());
115 case llvm::Type::TypeID::FP128TyID:
116 return mlir::FloatType::getF128(getContext());
117 default:
118 fir::emitFatalError(mlir::UnknownLoc::get(getContext()),
119 "unsupported type !fir.real<kind>");
120 }
121 }
122
123 mlir::Value fir::FirOpBuilder::createNullConstant(mlir::Location loc,
124 mlir::Type ptrType) {
125 auto ty = ptrType ? ptrType : getRefType(getNoneType());
126 return create<fir::ZeroOp>(loc, ty);
127 }
128
129 mlir::Value fir::FirOpBuilder::createIntegerConstant(mlir::Location loc,
130 mlir::Type ty,
131 std::int64_t cst) {
132 assert((cst >= 0 || mlir::isa<mlir::IndexType>(ty) ||
133 mlir::cast<mlir::IntegerType>(ty).getWidth() <= 64) &&
134 "must use APint");
135 return create<mlir::arith::ConstantOp>(loc, ty, getIntegerAttr(ty, cst));
136 }
137
138 mlir::Value fir::FirOpBuilder::createAllOnesInteger(mlir::Location loc,
139 mlir::Type ty) {
140 if (mlir::isa<mlir::IndexType>(ty))
141 return createIntegerConstant(loc, ty, -1);
142 llvm::APInt allOnes =
143 llvm::APInt::getAllOnes(mlir::cast<mlir::IntegerType>(ty).getWidth());
144 return create<mlir::arith::ConstantOp>(loc, ty, getIntegerAttr(ty, allOnes));
145 }
146
147 mlir::Value
148 fir::FirOpBuilder::createRealConstant(mlir::Location loc, mlir::Type fltTy,
149 llvm::APFloat::integerPart val) {
150 auto apf = [&]() -> llvm::APFloat {
151 if (auto ty = mlir::dyn_cast<fir::RealType>(fltTy))
152 return llvm::APFloat(kindMap.getFloatSemantics(ty.getFKind()), val);
153 if (fltTy.isF16())
154 return llvm::APFloat(llvm::APFloat::IEEEhalf(), val);
155 if (fltTy.isBF16())
156 return llvm::APFloat(llvm::APFloat::BFloat(), val);
157 if (fltTy.isF32())
158 return llvm::APFloat(llvm::APFloat::IEEEsingle(), val);
159 if (fltTy.isF64())
160 return llvm::APFloat(llvm::APFloat::IEEEdouble(), val);
161 if (fltTy.isF80())
162 return llvm::APFloat(llvm::APFloat::x87DoubleExtended(), val);
163 if (fltTy.isF128())
164 return llvm::APFloat(llvm::APFloat::IEEEquad(), val);
165 llvm_unreachable("unhandled MLIR floating-point type");
166 };
167 return createRealConstant(loc, fltTy, apf());
168 }
169
170 mlir::Value fir::FirOpBuilder::createRealConstant(mlir::Location loc,
171 mlir::Type fltTy,
172 const llvm::APFloat &value) {
173 if (mlir::isa<mlir::FloatType>(fltTy)) {
174 auto attr = getFloatAttr(fltTy, value);
175 return create<mlir::arith::ConstantOp>(loc, fltTy, attr);
176 }
177 llvm_unreachable("should use builtin floating-point type");
178 }
179
180 llvm::SmallVector<mlir::Value>
181 fir::factory::elideExtentsAlreadyInType(mlir::Type type,
182 mlir::ValueRange shape) {
183 auto arrTy = mlir::dyn_cast<fir::SequenceType>(type);
184 if (shape.empty() || !arrTy)
185 return {};
186 // elide the constant dimensions before construction
187 assert(shape.size() == arrTy.getDimension());
188 llvm::SmallVector<mlir::Value> dynamicShape;
189 auto typeShape = arrTy.getShape();
190 for (unsigned i = 0, end = arrTy.getDimension(); i < end; ++i)
191 if (typeShape[i] == fir::SequenceType::getUnknownExtent())
192 dynamicShape.push_back(shape[i]);
193 return dynamicShape;
194 }
195
196 llvm::SmallVector<mlir::Value>
197 fir::factory::elideLengthsAlreadyInType(mlir::Type type,
198 mlir::ValueRange lenParams) {
199 if (lenParams.empty())
200 return {};
201 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(type))
202 type = arrTy.getEleTy();
203 if (fir::hasDynamicSize(type))
204 return lenParams;
205 return {};
206 }
207
208 /// Allocate a local variable.
209 /// A local variable ought to have a name in the source code.
210 mlir::Value fir::FirOpBuilder::allocateLocal(
211 mlir::Location loc, mlir::Type ty, llvm::StringRef uniqName,
212 llvm::StringRef name, bool pinned, llvm::ArrayRef<mlir::Value> shape,
213 llvm::ArrayRef<mlir::Value> lenParams, bool asTarget) {
214 // Convert the shape extents to `index`, as needed.
215 llvm::SmallVector<mlir::Value> indices;
216 llvm::SmallVector<mlir::Value> elidedShape =
217 fir::factory::elideExtentsAlreadyInType(ty, shape);
218 llvm::SmallVector<mlir::Value> elidedLenParams =
219 fir::factory::elideLengthsAlreadyInType(ty, lenParams);
220 auto idxTy = getIndexType();
221 for (mlir::Value sh : elidedShape)
222 indices.push_back(createConvert(loc, idxTy, sh));
223 // Add a target attribute, if needed.
224 llvm::SmallVector<mlir::NamedAttribute> attrs;
225 if (asTarget)
226 attrs.emplace_back(
227 mlir::StringAttr::get(getContext(), fir::getTargetAttrName()),
228 getUnitAttr());
229 // Create the local variable.
230 if (name.empty()) {
231 if (uniqName.empty())
232 return create<fir::AllocaOp>(loc, ty, pinned, elidedLenParams, indices,
233 attrs);
234 return create<fir::AllocaOp>(loc, ty, uniqName, pinned, elidedLenParams,
235 indices, attrs);
236 }
237 return create<fir::AllocaOp>(loc, ty, uniqName, name, pinned, elidedLenParams,
238 indices, attrs);
239 }
240
241 mlir::Value fir::FirOpBuilder::allocateLocal(
242 mlir::Location loc, mlir::Type ty, llvm::StringRef uniqName,
243 llvm::StringRef name, llvm::ArrayRef<mlir::Value> shape,
244 llvm::ArrayRef<mlir::Value> lenParams, bool asTarget) {
245 return allocateLocal(loc, ty, uniqName, name, /*pinned=*/false, shape,
246 lenParams, asTarget);
247 }
248
249 /// Get the block for adding Allocas.
250 mlir::Block *fir::FirOpBuilder::getAllocaBlock() {
251 if (auto ompOutlineableIface =
252 getRegion()
253 .getParentOfType<mlir::omp::OutlineableOpenMPOpInterface>()) {
254 return ompOutlineableIface.getAllocaBlock();
255 }
256
257 if (auto recipeIface =
258 getRegion().getParentOfType<mlir::accomp::RecipeInterface>()) {
259 return recipeIface.getAllocaBlock(getRegion());
260 }
261
262 return getEntryBlock();
263 }
264
265 mlir::Value fir::FirOpBuilder::createTemporaryAlloc(
266 mlir::Location loc, mlir::Type type, llvm::StringRef name,
267 mlir::ValueRange lenParams, mlir::ValueRange shape,
268 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
269 assert(!mlir::isa<fir::ReferenceType>(type) && "cannot be a reference");
270 // If the alloca is inside an OpenMP Op which will be outlined then pin
271 // the alloca here.
272 const bool pinned =
273 getRegion().getParentOfType<mlir::omp::OutlineableOpenMPOpInterface>();
274 mlir::Value temp =
275 create<fir::AllocaOp>(loc, type, /*unique_name=*/llvm::StringRef{}, name,
276 pinned, lenParams, shape, attrs);
277 return temp;
278 }
279
280 /// Create a temporary variable on the stack. Anonymous temporaries have no
281 /// `name` value. Temporaries do not require a uniqued name.
282 mlir::Value
283 fir::FirOpBuilder::createTemporary(mlir::Location loc, mlir::Type type,
284 llvm::StringRef name, mlir::ValueRange shape,
285 mlir::ValueRange lenParams,
286 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
287 llvm::SmallVector<mlir::Value> dynamicShape =
288 fir::factory::elideExtentsAlreadyInType(type, shape);
289 llvm::SmallVector<mlir::Value> dynamicLength =
290 fir::factory::elideLengthsAlreadyInType(type, lenParams);
291 InsertPoint insPt;
292 const bool hoistAlloc = dynamicShape.empty() && dynamicLength.empty();
293 if (hoistAlloc) {
294 insPt = saveInsertionPoint();
295 setInsertionPointToStart(getAllocaBlock());
296 }
297
298 mlir::Value ae =
299 createTemporaryAlloc(loc, type, name, dynamicLength, dynamicShape, attrs);
300
301 if (hoistAlloc)
302 restoreInsertionPoint(insPt);
303 return ae;
304 }
305
306 mlir::Value fir::FirOpBuilder::createHeapTemporary(
307 mlir::Location loc, mlir::Type type, llvm::StringRef name,
308 mlir::ValueRange shape, mlir::ValueRange lenParams,
309 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
310 llvm::SmallVector<mlir::Value> dynamicShape =
311 fir::factory::elideExtentsAlreadyInType(type, shape);
312 llvm::SmallVector<mlir::Value> dynamicLength =
313 fir::factory::elideLengthsAlreadyInType(type, lenParams);
314
315 assert(!mlir::isa<fir::ReferenceType>(type) && "cannot be a reference");
316 return create<fir::AllocMemOp>(loc, type, /*unique_name=*/llvm::StringRef{},
317 name, dynamicLength, dynamicShape, attrs);
318 }
319
320 /// Create a global variable in the (read-only) data section. A global variable
321 /// must have a unique name to identify and reference it.
322 fir::GlobalOp fir::FirOpBuilder::createGlobal(
323 mlir::Location loc, mlir::Type type, llvm::StringRef name,
324 mlir::StringAttr linkage, mlir::Attribute value, bool isConst,
325 bool isTarget, cuf::DataAttributeAttr dataAttr) {
326 if (auto global = getNamedGlobal(name))
327 return global;
328 auto module = getModule();
329 auto insertPt = saveInsertionPoint();
330 setInsertionPoint(module.getBody(), module.getBody()->end());
331 llvm::SmallVector<mlir::NamedAttribute> attrs;
332 if (dataAttr) {
333 auto globalOpName = mlir::OperationName(fir::GlobalOp::getOperationName(),
334 module.getContext());
335 attrs.push_back(mlir::NamedAttribute(
336 fir::GlobalOp::getDataAttrAttrName(globalOpName), dataAttr));
337 }
338 auto glob = create<fir::GlobalOp>(loc, name, isConst, isTarget, type, value,
339 linkage, attrs);
340 restoreInsertionPoint(insertPt);
341 if (symbolTable)
342 symbolTable->insert(glob);
343 return glob;
344 }
345
346 fir::GlobalOp fir::FirOpBuilder::createGlobal(
347 mlir::Location loc, mlir::Type type, llvm::StringRef name, bool isConst,
348 bool isTarget, std::function<void(FirOpBuilder &)> bodyBuilder,
349 mlir::StringAttr linkage, cuf::DataAttributeAttr dataAttr) {
350 if (auto global = getNamedGlobal(name))
351 return global;
352 auto module = getModule();
353 auto insertPt = saveInsertionPoint();
354 setInsertionPoint(module.getBody(), module.getBody()->end());
355 auto glob = create<fir::GlobalOp>(loc, name, isConst, isTarget, type,
356 mlir::Attribute{}, linkage);
357 auto &region = glob.getRegion();
358 region.push_back(new mlir::Block);
359 auto &block = glob.getRegion().back();
360 setInsertionPointToStart(&block);
361 bodyBuilder(*this);
362 restoreInsertionPoint(insertPt);
363 if (symbolTable)
364 symbolTable->insert(glob);
365 return glob;
366 }
367
368 std::pair<fir::TypeInfoOp, mlir::OpBuilder::InsertPoint>
369 fir::FirOpBuilder::createTypeInfoOp(mlir::Location loc,
370 fir::RecordType recordType,
371 fir::RecordType parentType) {
372 mlir::ModuleOp module = getModule();
373 if (fir::TypeInfoOp typeInfo =
374 fir::lookupTypeInfoOp(recordType.getName(), module, symbolTable))
375 return {typeInfo, InsertPoint{}};
376 InsertPoint insertPoint = saveInsertionPoint();
377 setInsertionPoint(module.getBody(), module.getBody()->end());
378 auto typeInfo = create<fir::TypeInfoOp>(loc, recordType, parentType);
379 if (symbolTable)
380 symbolTable->insert(typeInfo);
381 return {typeInfo, insertPoint};
382 }
383
384 mlir::Value fir::FirOpBuilder::convertWithSemantics(
385 mlir::Location loc, mlir::Type toTy, mlir::Value val,
386 bool allowCharacterConversion, bool allowRebox) {
387 assert(toTy && "store location must be typed");
388 auto fromTy = val.getType();
389 if (fromTy == toTy)
390 return val;
391 fir::factory::Complex helper{*this, loc};
392 if ((fir::isa_real(fromTy) || fir::isa_integer(fromTy)) &&
393 fir::isa_complex(toTy)) {
394 // imaginary part is zero
395 auto eleTy = helper.getComplexPartType(toTy);
396 auto cast = createConvert(loc, eleTy, val);
397 llvm::APFloat zero{kindMap.getFloatSemantics(
398 mlir::cast<fir::ComplexType>(toTy).getFKind()),
399 0};
400 auto imag = createRealConstant(loc, eleTy, zero);
401 return helper.createComplex(toTy, cast, imag);
402 }
403 if (fir::isa_complex(fromTy) &&
404 (fir::isa_integer(toTy) || fir::isa_real(toTy))) {
405 // drop the imaginary part
406 auto rp = helper.extractComplexPart(val, /*isImagPart=*/false);
407 return createConvert(loc, toTy, rp);
408 }
409 if (allowCharacterConversion) {
410 if (mlir::isa<fir::BoxCharType>(fromTy)) {
411 // Extract the address of the character string and pass it
412 fir::factory::CharacterExprHelper charHelper{*this, loc};
413 std::pair<mlir::Value, mlir::Value> unboxchar =
414 charHelper.createUnboxChar(val);
415 return createConvert(loc, toTy, unboxchar.first);
416 }
417 if (auto boxType = mlir::dyn_cast<fir::BoxCharType>(toTy)) {
418 // Extract the address of the actual argument and create a boxed
419 // character value with an undefined length
420 // TODO: We should really calculate the total size of the actual
421 // argument in characters and use it as the length of the string
422 auto refType = getRefType(boxType.getEleTy());
423 mlir::Value charBase = createConvert(loc, refType, val);
424 mlir::Value unknownLen = create<fir::UndefOp>(loc, getIndexType());
425 fir::factory::CharacterExprHelper charHelper{*this, loc};
426 return charHelper.createEmboxChar(charBase, unknownLen);
427 }
428 }
429 if (fir::isa_ref_type(toTy) && fir::isa_box_type(fromTy)) {
430 // Call is expecting a raw data pointer, not a box. Get the data pointer out
431 // of the box and pass that.
432 assert((fir::unwrapRefType(toTy) ==
433 fir::unwrapRefType(fir::unwrapPassByRefType(fromTy)) &&
434 "element types expected to match"));
435 return create<fir::BoxAddrOp>(loc, toTy, val);
436 }
437 if (fir::isa_ref_type(fromTy) && mlir::isa<fir::BoxProcType>(toTy)) {
438 // Call is expecting a boxed procedure, not a reference to other data type.
439 // Convert the reference to a procedure and embox it.
440 mlir::Type procTy = mlir::cast<fir::BoxProcType>(toTy).getEleTy();
441 mlir::Value proc = createConvert(loc, procTy, val);
442 return create<fir::EmboxProcOp>(loc, toTy, proc);
443 }
444
445 // Legacy: remove when removing non HLFIR lowering path.
446 if (allowRebox)
447 if (((fir::isPolymorphicType(fromTy) &&
448 (fir::isAllocatableType(fromTy) || fir::isPointerType(fromTy)) &&
449 fir::isPolymorphicType(toTy)) ||
450 (fir::isPolymorphicType(fromTy) && mlir::isa<fir::BoxType>(toTy))) &&
451 !(fir::isUnlimitedPolymorphicType(fromTy) && fir::isAssumedType(toTy)))
452 return create<fir::ReboxOp>(loc, toTy, val, mlir::Value{},
453 /*slice=*/mlir::Value{});
454
455 return createConvert(loc, toTy, val);
456 }
457
458 mlir::Value fir::factory::createConvert(mlir::OpBuilder &builder,
459 mlir::Location loc, mlir::Type toTy,
460 mlir::Value val) {
461 if (val.getType() != toTy) {
462 assert(!fir::isa_derived(toTy));
463 return builder.create<fir::ConvertOp>(loc, toTy, val);
464 }
465 return val;
466 }
467
468 mlir::Value fir::FirOpBuilder::createConvert(mlir::Location loc,
469 mlir::Type toTy, mlir::Value val) {
470 return fir::factory::createConvert(*this, loc, toTy, val);
471 }
472
473 void fir::FirOpBuilder::createStoreWithConvert(mlir::Location loc,
474 mlir::Value val,
475 mlir::Value addr) {
476 mlir::Value cast =
477 createConvert(loc, fir::unwrapRefType(addr.getType()), val);
478 create<fir::StoreOp>(loc, cast, addr);
479 }
480
481 mlir::Value fir::FirOpBuilder::loadIfRef(mlir::Location loc, mlir::Value val) {
482 if (fir::isa_ref_type(val.getType()))
483 return create<fir::LoadOp>(loc, val);
484 return val;
485 }
486
487 fir::StringLitOp fir::FirOpBuilder::createStringLitOp(mlir::Location loc,
488 llvm::StringRef data) {
489 auto type = fir::CharacterType::get(getContext(), 1, data.size());
490 auto strAttr = mlir::StringAttr::get(getContext(), data);
491 auto valTag = mlir::StringAttr::get(getContext(), fir::StringLitOp::value());
492 mlir::NamedAttribute dataAttr(valTag, strAttr);
493 auto sizeTag = mlir::StringAttr::get(getContext(), fir::StringLitOp::size());
494 mlir::NamedAttribute sizeAttr(sizeTag, getI64IntegerAttr(data.size()));
495 llvm::SmallVector<mlir::NamedAttribute> attrs{dataAttr, sizeAttr};
496 return create<fir::StringLitOp>(loc, llvm::ArrayRef<mlir::Type>{type},
497 std::nullopt, attrs);
498 }
499
500 mlir::Value fir::FirOpBuilder::genShape(mlir::Location loc,
501 llvm::ArrayRef<mlir::Value> exts) {
502 return create<fir::ShapeOp>(loc, exts);
503 }
504
505 mlir::Value fir::FirOpBuilder::genShape(mlir::Location loc,
506 llvm::ArrayRef<mlir::Value> shift,
507 llvm::ArrayRef<mlir::Value> exts) {
508 auto shapeType = fir::ShapeShiftType::get(getContext(), exts.size());
509 llvm::SmallVector<mlir::Value> shapeArgs;
510 auto idxTy = getIndexType();
511 for (auto [lbnd, ext] : llvm::zip(shift, exts)) {
512 auto lb = createConvert(loc, idxTy, lbnd);
513 shapeArgs.push_back(lb);
514 shapeArgs.push_back(ext);
515 }
516 return create<fir::ShapeShiftOp>(loc, shapeType, shapeArgs);
517 }
518
519 mlir::Value fir::FirOpBuilder::genShape(mlir::Location loc,
520 const fir::AbstractArrayBox &arr) {
521 if (arr.lboundsAllOne())
522 return genShape(loc, arr.getExtents());
523 return genShape(loc, arr.getLBounds(), arr.getExtents());
524 }
525
526 mlir::Value fir::FirOpBuilder::genShift(mlir::Location loc,
527 llvm::ArrayRef<mlir::Value> shift) {
528 auto shiftType = fir::ShiftType::get(getContext(), shift.size());
529 return create<fir::ShiftOp>(loc, shiftType, shift);
530 }
531
532 mlir::Value fir::FirOpBuilder::createShape(mlir::Location loc,
533 const fir::ExtendedValue &exv) {
534 return exv.match(
535 [&](const fir::ArrayBoxValue &box) { return genShape(loc, box); },
536 [&](const fir::CharArrayBoxValue &box) { return genShape(loc, box); },
537 [&](const fir::BoxValue &box) -> mlir::Value {
538 if (!box.getLBounds().empty()) {
539 auto shiftType =
540 fir::ShiftType::get(getContext(), box.getLBounds().size());
541 return create<fir::ShiftOp>(loc, shiftType, box.getLBounds());
542 }
543 return {};
544 },
545 [&](const fir::MutableBoxValue &) -> mlir::Value {
546 // MutableBoxValue must be read into another category to work with them
547 // outside of allocation/assignment contexts.
548 fir::emitFatalError(loc, "createShape on MutableBoxValue");
549 },
550 [&](auto) -> mlir::Value { fir::emitFatalError(loc, "not an array"); });
551 }
552
553 mlir::Value fir::FirOpBuilder::createSlice(mlir::Location loc,
554 const fir::ExtendedValue &exv,
555 mlir::ValueRange triples,
556 mlir::ValueRange path) {
557 if (triples.empty()) {
558 // If there is no slicing by triple notation, then take the whole array.
559 auto fullShape = [&](const llvm::ArrayRef<mlir::Value> lbounds,
560 llvm::ArrayRef<mlir::Value> extents) -> mlir::Value {
561 llvm::SmallVector<mlir::Value> trips;
562 auto idxTy = getIndexType();
563 auto one = createIntegerConstant(loc, idxTy, 1);
564 if (lbounds.empty()) {
565 for (auto v : extents) {
566 trips.push_back(one);
567 trips.push_back(v);
568 trips.push_back(one);
569 }
570 return create<fir::SliceOp>(loc, trips, path);
571 }
572 for (auto [lbnd, extent] : llvm::zip(lbounds, extents)) {
573 auto lb = createConvert(loc, idxTy, lbnd);
574 auto ext = createConvert(loc, idxTy, extent);
575 auto shift = create<mlir::arith::SubIOp>(loc, lb, one);
576 auto ub = create<mlir::arith::AddIOp>(loc, ext, shift);
577 trips.push_back(lb);
578 trips.push_back(ub);
579 trips.push_back(one);
580 }
581 return create<fir::SliceOp>(loc, trips, path);
582 };
583 return exv.match(
584 [&](const fir::ArrayBoxValue &box) {
585 return fullShape(box.getLBounds(), box.getExtents());
586 },
587 [&](const fir::CharArrayBoxValue &box) {
588 return fullShape(box.getLBounds(), box.getExtents());
589 },
590 [&](const fir::BoxValue &box) {
591 auto extents = fir::factory::readExtents(*this, loc, box);
592 return fullShape(box.getLBounds(), extents);
593 },
594 [&](const fir::MutableBoxValue &) -> mlir::Value {
595 // MutableBoxValue must be read into another category to work with
596 // them outside of allocation/assignment contexts.
597 fir::emitFatalError(loc, "createSlice on MutableBoxValue");
598 },
599 [&](auto) -> mlir::Value { fir::emitFatalError(loc, "not an array"); });
600 }
601 return create<fir::SliceOp>(loc, triples, path);
602 }
603
604 mlir::Value fir::FirOpBuilder::createBox(mlir::Location loc,
605 const fir::ExtendedValue &exv,
606 bool isPolymorphic,
607 bool isAssumedType) {
608 mlir::Value itemAddr = fir::getBase(exv);
609 if (mlir::isa<fir::BaseBoxType>(itemAddr.getType()))
610 return itemAddr;
611 auto elementType = fir::dyn_cast_ptrEleTy(itemAddr.getType());
612 if (!elementType) {
613 mlir::emitError(loc, "internal: expected a memory reference type ")
614 << itemAddr.getType();
615 llvm_unreachable("not a memory reference type");
616 }
617 mlir::Type boxTy;
618 mlir::Value tdesc;
619 // Avoid to wrap a box/class with box/class.
620 if (mlir::isa<fir::BaseBoxType>(elementType)) {
621 boxTy = elementType;
622 } else {
623 boxTy = fir::BoxType::get(elementType);
624 if (isPolymorphic) {
625 elementType = fir::updateTypeForUnlimitedPolymorphic(elementType);
626 if (isAssumedType)
627 boxTy = fir::BoxType::get(elementType);
628 else
629 boxTy = fir::ClassType::get(elementType);
630 }
631 }
632
633 return exv.match(
634 [&](const fir::ArrayBoxValue &box) -> mlir::Value {
635 mlir::Value empty;
636 mlir::ValueRange emptyRange;
637 mlir::Value s = createShape(loc, exv);
638 return create<fir::EmboxOp>(loc, boxTy, itemAddr, s, /*slice=*/empty,
639 /*typeparams=*/emptyRange,
640 isPolymorphic ? box.getSourceBox() : tdesc);
641 },
642 [&](const fir::CharArrayBoxValue &box) -> mlir::Value {
643 mlir::Value s = createShape(loc, exv);
644 if (fir::factory::CharacterExprHelper::hasConstantLengthInType(exv))
645 return create<fir::EmboxOp>(loc, boxTy, itemAddr, s);
646
647 mlir::Value emptySlice;
648 llvm::SmallVector<mlir::Value> lenParams{box.getLen()};
649 return create<fir::EmboxOp>(loc, boxTy, itemAddr, s, emptySlice,
650 lenParams);
651 },
652 [&](const fir::CharBoxValue &box) -> mlir::Value {
653 if (fir::factory::CharacterExprHelper::hasConstantLengthInType(exv))
654 return create<fir::EmboxOp>(loc, boxTy, itemAddr);
655 mlir::Value emptyShape, emptySlice;
656 llvm::SmallVector<mlir::Value> lenParams{box.getLen()};
657 return create<fir::EmboxOp>(loc, boxTy, itemAddr, emptyShape,
658 emptySlice, lenParams);
659 },
660 [&](const fir::MutableBoxValue &x) -> mlir::Value {
661 return create<fir::LoadOp>(
662 loc, fir::factory::getMutableIRBox(*this, loc, x));
663 },
664 [&](const fir::PolymorphicValue &p) -> mlir::Value {
665 mlir::Value empty;
666 mlir::ValueRange emptyRange;
667 return create<fir::EmboxOp>(loc, boxTy, itemAddr, empty, empty,
668 emptyRange,
669 isPolymorphic ? p.getSourceBox() : tdesc);
670 },
671 [&](const auto &) -> mlir::Value {
672 mlir::Value empty;
673 mlir::ValueRange emptyRange;
674 return create<fir::EmboxOp>(loc, boxTy, itemAddr, empty, empty,
675 emptyRange, tdesc);
676 });
677 }
678
679 mlir::Value fir::FirOpBuilder::createBox(mlir::Location loc, mlir::Type boxType,
680 mlir::Value addr, mlir::Value shape,
681 mlir::Value slice,
682 llvm::ArrayRef<mlir::Value> lengths,
683 mlir::Value tdesc) {
684 mlir::Type valueOrSequenceType = fir::unwrapPassByRefType(boxType);
685 return create<fir::EmboxOp>(
686 loc, boxType, addr, shape, slice,
687 fir::factory::elideLengthsAlreadyInType(valueOrSequenceType, lengths),
688 tdesc);
689 }
690
691 void fir::FirOpBuilder::dumpFunc() { getFunction().dump(); }
692
693 static mlir::Value
694 genNullPointerComparison(fir::FirOpBuilder &builder, mlir::Location loc,
695 mlir::Value addr,
696 mlir::arith::CmpIPredicate condition) {
697 auto intPtrTy = builder.getIntPtrType();
698 auto ptrToInt = builder.createConvert(loc, intPtrTy, addr);
699 auto c0 = builder.createIntegerConstant(loc, intPtrTy, 0);
700 return builder.create<mlir::arith::CmpIOp>(loc, condition, ptrToInt, c0);
701 }
702
703 mlir::Value fir::FirOpBuilder::genIsNotNullAddr(mlir::Location loc,
704 mlir::Value addr) {
705 return genNullPointerComparison(*this, loc, addr,
706 mlir::arith::CmpIPredicate::ne);
707 }
708
709 mlir::Value fir::FirOpBuilder::genIsNullAddr(mlir::Location loc,
710 mlir::Value addr) {
711 return genNullPointerComparison(*this, loc, addr,
712 mlir::arith::CmpIPredicate::eq);
713 }
714
715 mlir::Value fir::FirOpBuilder::genExtentFromTriplet(mlir::Location loc,
716 mlir::Value lb,
717 mlir::Value ub,
718 mlir::Value step,
719 mlir::Type type) {
720 auto zero = createIntegerConstant(loc, type, 0);
721 lb = createConvert(loc, type, lb);
722 ub = createConvert(loc, type, ub);
723 step = createConvert(loc, type, step);
724 auto diff = create<mlir::arith::SubIOp>(loc, ub, lb);
725 auto add = create<mlir::arith::AddIOp>(loc, diff, step);
726 auto div = create<mlir::arith::DivSIOp>(loc, add, step);
727 auto cmp = create<mlir::arith::CmpIOp>(loc, mlir::arith::CmpIPredicate::sgt,
728 div, zero);
729 return create<mlir::arith::SelectOp>(loc, cmp, div, zero);
730 }
731
732 mlir::Value fir::FirOpBuilder::genAbsentOp(mlir::Location loc,
733 mlir::Type argTy) {
734 if (!fir::isCharacterProcedureTuple(argTy))
735 return create<fir::AbsentOp>(loc, argTy);
736
737 auto boxProc =
738 create<fir::AbsentOp>(loc, mlir::cast<mlir::TupleType>(argTy).getType(0));
739 mlir::Value charLen = create<fir::UndefOp>(loc, getCharacterLengthType());
740 return fir::factory::createCharacterProcedureTuple(*this, loc, argTy, boxProc,
741 charLen);
742 }
743
744 void fir::FirOpBuilder::setCommonAttributes(mlir::Operation *op) const {
745 auto fmi = mlir::dyn_cast<mlir::arith::ArithFastMathInterface>(*op);
746 if (!fmi)
747 return;
748 // TODO: use fmi.setFastMathFlagsAttr() after D137114 is merged.
749 // For now set the attribute by the name.
750 llvm::StringRef arithFMFAttrName = fmi.getFastMathAttrName();
751 if (fastMathFlags != mlir::arith::FastMathFlags::none)
752 op->setAttr(arithFMFAttrName, mlir::arith::FastMathFlagsAttr::get(
753 op->getContext(), fastMathFlags));
754 }
755
756 void fir::FirOpBuilder::setFastMathFlags(
757 Fortran::common::MathOptionsBase options) {
758 mlir::arith::FastMathFlags arithFMF{};
759 if (options.getFPContractEnabled()) {
760 arithFMF = arithFMF | mlir::arith::FastMathFlags::contract;
761 }
762 if (options.getNoHonorInfs()) {
763 arithFMF = arithFMF | mlir::arith::FastMathFlags::ninf;
764 }
765 if (options.getNoHonorNaNs()) {
766 arithFMF = arithFMF | mlir::arith::FastMathFlags::nnan;
767 }
768 if (options.getApproxFunc()) {
769 arithFMF = arithFMF | mlir::arith::FastMathFlags::afn;
770 }
771 if (options.getNoSignedZeros()) {
772 arithFMF = arithFMF | mlir::arith::FastMathFlags::nsz;
773 }
774 if (options.getAssociativeMath()) {
775 arithFMF = arithFMF | mlir::arith::FastMathFlags::reassoc;
776 }
777 if (options.getReciprocalMath()) {
778 arithFMF = arithFMF | mlir::arith::FastMathFlags::arcp;
779 }
780 setFastMathFlags(arithFMF);
781 }
782
783 //===--------------------------------------------------------------------===//
784 // ExtendedValue inquiry helper implementation
785 //===--------------------------------------------------------------------===//
786
787 mlir::Value fir::factory::readCharLen(fir::FirOpBuilder &builder,
788 mlir::Location loc,
789 const fir::ExtendedValue &box) {
790 return box.match(
791 [&](const fir::CharBoxValue &x) -> mlir::Value { return x.getLen(); },
792 [&](const fir::CharArrayBoxValue &x) -> mlir::Value {
793 return x.getLen();
794 },
795 [&](const fir::BoxValue &x) -> mlir::Value {
796 assert(x.isCharacter());
797 if (!x.getExplicitParameters().empty())
798 return x.getExplicitParameters()[0];
799 return fir::factory::CharacterExprHelper{builder, loc}
800 .readLengthFromBox(x.getAddr());
801 },
802 [&](const fir::MutableBoxValue &x) -> mlir::Value {
803 return readCharLen(builder, loc,
804 fir::factory::genMutableBoxRead(builder, loc, x));
805 },
806 [&](const auto &) -> mlir::Value {
807 fir::emitFatalError(
808 loc, "Character length inquiry on a non-character entity");
809 });
810 }
811
812 mlir::Value fir::factory::readExtent(fir::FirOpBuilder &builder,
813 mlir::Location loc,
814 const fir::ExtendedValue &box,
815 unsigned dim) {
816 assert(box.rank() > dim);
817 return box.match(
818 [&](const fir::ArrayBoxValue &x) -> mlir::Value {
819 return x.getExtents()[dim];
820 },
821 [&](const fir::CharArrayBoxValue &x) -> mlir::Value {
822 return x.getExtents()[dim];
823 },
824 [&](const fir::BoxValue &x) -> mlir::Value {
825 if (!x.getExplicitExtents().empty())
826 return x.getExplicitExtents()[dim];
827 auto idxTy = builder.getIndexType();
828 auto dimVal = builder.createIntegerConstant(loc, idxTy, dim);
829 return builder
830 .create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, x.getAddr(),
831 dimVal)
832 .getResult(1);
833 },
834 [&](const fir::MutableBoxValue &x) -> mlir::Value {
835 return readExtent(builder, loc,
836 fir::factory::genMutableBoxRead(builder, loc, x),
837 dim);
838 },
839 [&](const auto &) -> mlir::Value {
840 fir::emitFatalError(loc, "extent inquiry on scalar");
841 });
842 }
843
844 mlir::Value fir::factory::readLowerBound(fir::FirOpBuilder &builder,
845 mlir::Location loc,
846 const fir::ExtendedValue &box,
847 unsigned dim,
848 mlir::Value defaultValue) {
849 assert(box.rank() > dim);
850 auto lb = box.match(
851 [&](const fir::ArrayBoxValue &x) -> mlir::Value {
852 return x.getLBounds().empty() ? mlir::Value{} : x.getLBounds()[dim];
853 },
854 [&](const fir::CharArrayBoxValue &x) -> mlir::Value {
855 return x.getLBounds().empty() ? mlir::Value{} : x.getLBounds()[dim];
856 },
857 [&](const fir::BoxValue &x) -> mlir::Value {
858 return x.getLBounds().empty() ? mlir::Value{} : x.getLBounds()[dim];
859 },
860 [&](const fir::MutableBoxValue &x) -> mlir::Value {
861 return readLowerBound(builder, loc,
862 fir::factory::genMutableBoxRead(builder, loc, x),
863 dim, defaultValue);
864 },
865 [&](const auto &) -> mlir::Value {
866 fir::emitFatalError(loc, "lower bound inquiry on scalar");
867 });
868 if (lb)
869 return lb;
870 return defaultValue;
871 }
872
873 llvm::SmallVector<mlir::Value>
874 fir::factory::readExtents(fir::FirOpBuilder &builder, mlir::Location loc,
875 const fir::BoxValue &box) {
876 llvm::SmallVector<mlir::Value> result;
877 auto explicitExtents = box.getExplicitExtents();
878 if (!explicitExtents.empty()) {
879 result.append(explicitExtents.begin(), explicitExtents.end());
880 return result;
881 }
882 auto rank = box.rank();
883 auto idxTy = builder.getIndexType();
884 for (decltype(rank) dim = 0; dim < rank; ++dim) {
885 auto dimVal = builder.createIntegerConstant(loc, idxTy, dim);
886 auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy,
887 box.getAddr(), dimVal);
888 result.emplace_back(dimInfo.getResult(1));
889 }
890 return result;
891 }
892
893 llvm::SmallVector<mlir::Value>
894 fir::factory::getExtents(mlir::Location loc, fir::FirOpBuilder &builder,
895 const fir::ExtendedValue &box) {
896 return box.match(
897 [&](const fir::ArrayBoxValue &x) -> llvm::SmallVector<mlir::Value> {
898 return {x.getExtents().begin(), x.getExtents().end()};
899 },
900 [&](const fir::CharArrayBoxValue &x) -> llvm::SmallVector<mlir::Value> {
901 return {x.getExtents().begin(), x.getExtents().end()};
902 },
903 [&](const fir::BoxValue &x) -> llvm::SmallVector<mlir::Value> {
904 return fir::factory::readExtents(builder, loc, x);
905 },
906 [&](const fir::MutableBoxValue &x) -> llvm::SmallVector<mlir::Value> {
907 auto load = fir::factory::genMutableBoxRead(builder, loc, x);
908 return fir::factory::getExtents(loc, builder, load);
909 },
910 [&](const auto &) -> llvm::SmallVector<mlir::Value> { return {}; });
911 }
912
913 fir::ExtendedValue fir::factory::readBoxValue(fir::FirOpBuilder &builder,
914 mlir::Location loc,
915 const fir::BoxValue &box) {
916 assert(!box.hasAssumedRank() &&
917 "cannot read unlimited polymorphic or assumed rank fir.box");
918 auto addr =
919 builder.create<fir::BoxAddrOp>(loc, box.getMemTy(), box.getAddr());
920 if (box.isCharacter()) {
921 auto len = fir::factory::readCharLen(builder, loc, box);
922 if (box.rank() == 0)
923 return fir::CharBoxValue(addr, len);
924 return fir::CharArrayBoxValue(addr, len,
925 fir::factory::readExtents(builder, loc, box),
926 box.getLBounds());
927 }
928 if (box.isDerivedWithLenParameters())
929 TODO(loc, "read fir.box with length parameters");
930 mlir::Value sourceBox;
931 if (box.isPolymorphic())
932 sourceBox = box.getAddr();
933 if (box.isPolymorphic() && box.rank() == 0)
934 return fir::PolymorphicValue(addr, sourceBox);
935 if (box.rank() == 0)
936 return addr;
937 return fir::ArrayBoxValue(addr, fir::factory::readExtents(builder, loc, box),
938 box.getLBounds(), sourceBox);
939 }
940
941 llvm::SmallVector<mlir::Value>
942 fir::factory::getNonDefaultLowerBounds(fir::FirOpBuilder &builder,
943 mlir::Location loc,
944 const fir::ExtendedValue &exv) {
945 return exv.match(
946 [&](const fir::ArrayBoxValue &array) -> llvm::SmallVector<mlir::Value> {
947 return {array.getLBounds().begin(), array.getLBounds().end()};
948 },
949 [&](const fir::CharArrayBoxValue &array)
950 -> llvm::SmallVector<mlir::Value> {
951 return {array.getLBounds().begin(), array.getLBounds().end()};
952 },
953 [&](const fir::BoxValue &box) -> llvm::SmallVector<mlir::Value> {
954 return {box.getLBounds().begin(), box.getLBounds().end()};
955 },
956 [&](const fir::MutableBoxValue &box) -> llvm::SmallVector<mlir::Value> {
957 auto load = fir::factory::genMutableBoxRead(builder, loc, box);
958 return fir::factory::getNonDefaultLowerBounds(builder, loc, load);
959 },
960 [&](const auto &) -> llvm::SmallVector<mlir::Value> { return {}; });
961 }
962
963 llvm::SmallVector<mlir::Value>
964 fir::factory::getNonDeferredLenParams(const fir::ExtendedValue &exv) {
965 return exv.match(
966 [&](const fir::CharArrayBoxValue &character)
967 -> llvm::SmallVector<mlir::Value> { return {character.getLen()}; },
968 [&](const fir::CharBoxValue &character)
969 -> llvm::SmallVector<mlir::Value> { return {character.getLen()}; },
970 [&](const fir::MutableBoxValue &box) -> llvm::SmallVector<mlir::Value> {
971 return {box.nonDeferredLenParams().begin(),
972 box.nonDeferredLenParams().end()};
973 },
974 [&](const fir::BoxValue &box) -> llvm::SmallVector<mlir::Value> {
975 return {box.getExplicitParameters().begin(),
976 box.getExplicitParameters().end()};
977 },
978 [&](const auto &) -> llvm::SmallVector<mlir::Value> { return {}; });
979 }
980
981 // If valTy is a box type, then we need to extract the type parameters from
982 // the box value.
983 static llvm::SmallVector<mlir::Value> getFromBox(mlir::Location loc,
984 fir::FirOpBuilder &builder,
985 mlir::Type valTy,
986 mlir::Value boxVal) {
987 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(valTy)) {
988 auto eleTy = fir::unwrapAllRefAndSeqType(boxTy.getEleTy());
989 if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy)) {
990 if (recTy.getNumLenParams() > 0) {
991 // Walk each type parameter in the record and get the value.
992 TODO(loc, "generate code to get LEN type parameters");
993 }
994 } else if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
995 if (charTy.hasDynamicLen()) {
996 auto idxTy = builder.getIndexType();
997 auto eleSz = builder.create<fir::BoxEleSizeOp>(loc, idxTy, boxVal);
998 auto kindBytes =
999 builder.getKindMap().getCharacterBitsize(charTy.getFKind()) / 8;
1000 mlir::Value charSz =
1001 builder.createIntegerConstant(loc, idxTy, kindBytes);
1002 mlir::Value len =
1003 builder.create<mlir::arith::DivSIOp>(loc, eleSz, charSz);
1004 return {len};
1005 }
1006 }
1007 }
1008 return {};
1009 }
1010
1011 // fir::getTypeParams() will get the type parameters from the extended value.
1012 // When the extended value is a BoxValue or MutableBoxValue, it may be necessary
1013 // to generate code, so this factory function handles those cases.
1014 // TODO: fix the inverted type tests, etc.
1015 llvm::SmallVector<mlir::Value>
1016 fir::factory::getTypeParams(mlir::Location loc, fir::FirOpBuilder &builder,
1017 const fir::ExtendedValue &exv) {
1018 auto handleBoxed = [&](const auto &box) -> llvm::SmallVector<mlir::Value> {
1019 if (box.isCharacter())
1020 return {fir::factory::readCharLen(builder, loc, exv)};
1021 if (box.isDerivedWithLenParameters()) {
1022 // This should generate code to read the type parameters from the box.
1023 // This requires some consideration however as MutableBoxValues need to be
1024 // in a sane state to be provide the correct values.
1025 TODO(loc, "derived type with type parameters");
1026 }
1027 return {};
1028 };
1029 // Intentionally reuse the original code path to get type parameters for the
1030 // cases that were supported rather than introduce a new path.
1031 return exv.match(
1032 [&](const fir::BoxValue &box) { return handleBoxed(box); },
1033 [&](const fir::MutableBoxValue &box) { return handleBoxed(box); },
1034 [&](const auto &) { return fir::getTypeParams(exv); });
1035 }
1036
1037 llvm::SmallVector<mlir::Value>
1038 fir::factory::getTypeParams(mlir::Location loc, fir::FirOpBuilder &builder,
1039 fir::ArrayLoadOp load) {
1040 mlir::Type memTy = load.getMemref().getType();
1041 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(memTy))
1042 return getFromBox(loc, builder, boxTy, load.getMemref());
1043 return load.getTypeparams();
1044 }
1045
1046 std::string fir::factory::uniqueCGIdent(llvm::StringRef prefix,
1047 llvm::StringRef name) {
1048 // For "long" identifiers use a hash value
1049 if (name.size() > nameLengthHashSize) {
1050 llvm::MD5 hash;
1051 hash.update(name);
1052 llvm::MD5::MD5Result result;
1053 hash.final(result);
1054 llvm::SmallString<32> str;
1055 llvm::MD5::stringifyResult(result, str);
1056 std::string hashName = prefix.str();
1057 hashName.append("X").append(str.c_str());
1058 return fir::NameUniquer::doGenerated(hashName);
1059 }
1060 // "Short" identifiers use a reversible hex string
1061 std::string nm = prefix.str();
1062 return fir::NameUniquer::doGenerated(
1063 nm.append("X").append(llvm::toHex(name)));
1064 }
1065
1066 mlir::Value fir::factory::locationToFilename(fir::FirOpBuilder &builder,
1067 mlir::Location loc) {
1068 if (auto flc = mlir::dyn_cast<mlir::FileLineColLoc>(loc)) {
1069 // must be encoded as asciiz, C string
1070 auto fn = flc.getFilename().str() + '\0';
1071 return fir::getBase(createStringLiteral(builder, loc, fn));
1072 }
1073 return builder.createNullConstant(loc);
1074 }
1075
1076 mlir::Value fir::factory::locationToLineNo(fir::FirOpBuilder &builder,
1077 mlir::Location loc,
1078 mlir::Type type) {
1079 if (auto flc = mlir::dyn_cast<mlir::FileLineColLoc>(loc))
1080 return builder.createIntegerConstant(loc, type, flc.getLine());
1081 return builder.createIntegerConstant(loc, type, 0);
1082 }
1083
1084 fir::ExtendedValue fir::factory::createStringLiteral(fir::FirOpBuilder &builder,
1085 mlir::Location loc,
1086 llvm::StringRef str) {
1087 std::string globalName = fir::factory::uniqueCGIdent("cl", str);
1088 auto type = fir::CharacterType::get(builder.getContext(), 1, str.size());
1089 auto global = builder.getNamedGlobal(globalName);
1090 if (!global)
1091 global = builder.createGlobalConstant(
1092 loc, type, globalName,
1093 [&](fir::FirOpBuilder &builder) {
1094 auto stringLitOp = builder.createStringLitOp(loc, str);
1095 builder.create<fir::HasValueOp>(loc, stringLitOp);
1096 },
1097 builder.createLinkOnceLinkage());
1098 auto addr = builder.create<fir::AddrOfOp>(loc, global.resultType(),
1099 global.getSymbol());
1100 auto len = builder.createIntegerConstant(
1101 loc, builder.getCharacterLengthType(), str.size());
1102 return fir::CharBoxValue{addr, len};
1103 }
1104
1105 llvm::SmallVector<mlir::Value>
1106 fir::factory::createExtents(fir::FirOpBuilder &builder, mlir::Location loc,
1107 fir::SequenceType seqTy) {
1108 llvm::SmallVector<mlir::Value> extents;
1109 auto idxTy = builder.getIndexType();
1110 for (auto ext : seqTy.getShape())
1111 extents.emplace_back(
1112 ext == fir::SequenceType::getUnknownExtent()
1113 ? builder.create<fir::UndefOp>(loc, idxTy).getResult()
1114 : builder.createIntegerConstant(loc, idxTy, ext));
1115 return extents;
1116 }
1117
1118 // FIXME: This needs some work. To correctly determine the extended value of a
1119 // component, one needs the base object, its type, and its type parameters. (An
1120 // alternative would be to provide an already computed address of the final
1121 // component rather than the base object's address, the point being the result
1122 // will require the address of the final component to create the extended
1123 // value.) One further needs the full path of components being applied. One
1124 // needs to apply type-based expressions to type parameters along this said
1125 // path. (See applyPathToType for a type-only derivation.) Finally, one needs to
1126 // compose the extended value of the terminal component, including all of its
1127 // parameters: array lower bounds expressions, extents, type parameters, etc.
1128 // Any of these properties may be deferred until runtime in Fortran. This
1129 // operation may therefore generate a sizeable block of IR, including calls to
1130 // type-based helper functions, so caching the result of this operation in the
1131 // client would be advised as well.
1132 fir::ExtendedValue fir::factory::componentToExtendedValue(
1133 fir::FirOpBuilder &builder, mlir::Location loc, mlir::Value component) {
1134 auto fieldTy = component.getType();
1135 if (auto ty = fir::dyn_cast_ptrEleTy(fieldTy))
1136 fieldTy = ty;
1137 if (mlir::isa<fir::BaseBoxType>(fieldTy)) {
1138 llvm::SmallVector<mlir::Value> nonDeferredTypeParams;
1139 auto eleTy = fir::unwrapSequenceType(fir::dyn_cast_ptrOrBoxEleTy(fieldTy));
1140 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
1141 auto lenTy = builder.getCharacterLengthType();
1142 if (charTy.hasConstantLen())
1143 nonDeferredTypeParams.emplace_back(
1144 builder.createIntegerConstant(loc, lenTy, charTy.getLen()));
1145 // TODO: Starting, F2003, the dynamic character length might be dependent
1146 // on a PDT length parameter. There is no way to make a difference with
1147 // deferred length here yet.
1148 }
1149 if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy))
1150 if (recTy.getNumLenParams() > 0)
1151 TODO(loc, "allocatable and pointer components non deferred length "
1152 "parameters");
1153
1154 return fir::MutableBoxValue(component, nonDeferredTypeParams,
1155 /*mutableProperties=*/{});
1156 }
1157 llvm::SmallVector<mlir::Value> extents;
1158 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(fieldTy)) {
1159 fieldTy = seqTy.getEleTy();
1160 auto idxTy = builder.getIndexType();
1161 for (auto extent : seqTy.getShape()) {
1162 if (extent == fir::SequenceType::getUnknownExtent())
1163 TODO(loc, "array component shape depending on length parameters");
1164 extents.emplace_back(builder.createIntegerConstant(loc, idxTy, extent));
1165 }
1166 }
1167 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(fieldTy)) {
1168 auto cstLen = charTy.getLen();
1169 if (cstLen == fir::CharacterType::unknownLen())
1170 TODO(loc, "get character component length from length type parameters");
1171 auto len = builder.createIntegerConstant(
1172 loc, builder.getCharacterLengthType(), cstLen);
1173 if (!extents.empty())
1174 return fir::CharArrayBoxValue{component, len, extents};
1175 return fir::CharBoxValue{component, len};
1176 }
1177 if (auto recordTy = mlir::dyn_cast<fir::RecordType>(fieldTy))
1178 if (recordTy.getNumLenParams() != 0)
1179 TODO(loc,
1180 "lower component ref that is a derived type with length parameter");
1181 if (!extents.empty())
1182 return fir::ArrayBoxValue{component, extents};
1183 return component;
1184 }
1185
1186 fir::ExtendedValue fir::factory::arrayElementToExtendedValue(
1187 fir::FirOpBuilder &builder, mlir::Location loc,
1188 const fir::ExtendedValue &array, mlir::Value element) {
1189 return array.match(
1190 [&](const fir::CharBoxValue &cb) -> fir::ExtendedValue {
1191 return cb.clone(element);
1192 },
1193 [&](const fir::CharArrayBoxValue &bv) -> fir::ExtendedValue {
1194 return bv.cloneElement(element);
1195 },
1196 [&](const fir::BoxValue &box) -> fir::ExtendedValue {
1197 if (box.isCharacter()) {
1198 auto len = fir::factory::readCharLen(builder, loc, box);
1199 return fir::CharBoxValue{element, len};
1200 }
1201 if (box.isDerivedWithLenParameters())
1202 TODO(loc, "get length parameters from derived type BoxValue");
1203 if (box.isPolymorphic()) {
1204 return fir::PolymorphicValue(element, fir::getBase(box));
1205 }
1206 return element;
1207 },
1208 [&](const fir::ArrayBoxValue &box) -> fir::ExtendedValue {
1209 if (box.getSourceBox())
1210 return fir::PolymorphicValue(element, box.getSourceBox());
1211 return element;
1212 },
1213 [&](const auto &) -> fir::ExtendedValue { return element; });
1214 }
1215
1216 fir::ExtendedValue fir::factory::arraySectionElementToExtendedValue(
1217 fir::FirOpBuilder &builder, mlir::Location loc,
1218 const fir::ExtendedValue &array, mlir::Value element, mlir::Value slice) {
1219 if (!slice)
1220 return arrayElementToExtendedValue(builder, loc, array, element);
1221 auto sliceOp = mlir::dyn_cast_or_null<fir::SliceOp>(slice.getDefiningOp());
1222 assert(sliceOp && "slice must be a sliceOp");
1223 if (sliceOp.getFields().empty())
1224 return arrayElementToExtendedValue(builder, loc, array, element);
1225 // For F95, using componentToExtendedValue will work, but when PDTs are
1226 // lowered. It will be required to go down the slice to propagate the length
1227 // parameters.
1228 return fir::factory::componentToExtendedValue(builder, loc, element);
1229 }
1230
1231 void fir::factory::genScalarAssignment(fir::FirOpBuilder &builder,
1232 mlir::Location loc,
1233 const fir::ExtendedValue &lhs,
1234 const fir::ExtendedValue &rhs,
1235 bool needFinalization,
1236 bool isTemporaryLHS) {
1237 assert(lhs.rank() == 0 && rhs.rank() == 0 && "must be scalars");
1238 auto type = fir::unwrapSequenceType(
1239 fir::unwrapPassByRefType(fir::getBase(lhs).getType()));
1240 if (mlir::isa<fir::CharacterType>(type)) {
1241 const fir::CharBoxValue *toChar = lhs.getCharBox();
1242 const fir::CharBoxValue *fromChar = rhs.getCharBox();
1243 assert(toChar && fromChar);
1244 fir::factory::CharacterExprHelper helper{builder, loc};
1245 helper.createAssign(fir::ExtendedValue{*toChar},
1246 fir::ExtendedValue{*fromChar});
1247 } else if (mlir::isa<fir::RecordType>(type)) {
1248 fir::factory::genRecordAssignment(builder, loc, lhs, rhs, needFinalization,
1249 isTemporaryLHS);
1250 } else {
1251 assert(!fir::hasDynamicSize(type));
1252 auto rhsVal = fir::getBase(rhs);
1253 if (fir::isa_ref_type(rhsVal.getType()))
1254 rhsVal = builder.create<fir::LoadOp>(loc, rhsVal);
1255 mlir::Value lhsAddr = fir::getBase(lhs);
1256 rhsVal = builder.createConvert(loc, fir::unwrapRefType(lhsAddr.getType()),
1257 rhsVal);
1258 builder.create<fir::StoreOp>(loc, rhsVal, lhsAddr);
1259 }
1260 }
1261
1262 static void genComponentByComponentAssignment(fir::FirOpBuilder &builder,
1263 mlir::Location loc,
1264 const fir::ExtendedValue &lhs,
1265 const fir::ExtendedValue &rhs,
1266 bool isTemporaryLHS) {
1267 auto lbaseType = fir::unwrapPassByRefType(fir::getBase(lhs).getType());
1268 auto lhsType = mlir::dyn_cast<fir::RecordType>(lbaseType);
1269 assert(lhsType && "lhs must be a scalar record type");
1270 auto rbaseType = fir::unwrapPassByRefType(fir::getBase(rhs).getType());
1271 auto rhsType = mlir::dyn_cast<fir::RecordType>(rbaseType);
1272 assert(rhsType && "rhs must be a scalar record type");
1273 auto fieldIndexType = fir::FieldType::get(lhsType.getContext());
1274 for (auto [lhsPair, rhsPair] :
1275 llvm::zip(lhsType.getTypeList(), rhsType.getTypeList())) {
1276 auto &[lFieldName, lFieldTy] = lhsPair;
1277 auto &[rFieldName, rFieldTy] = rhsPair;
1278 assert(!fir::hasDynamicSize(lFieldTy) && !fir::hasDynamicSize(rFieldTy));
1279 mlir::Value rField = builder.create<fir::FieldIndexOp>(
1280 loc, fieldIndexType, rFieldName, rhsType, fir::getTypeParams(rhs));
1281 auto rFieldRefType = builder.getRefType(rFieldTy);
1282 mlir::Value fromCoor = builder.create<fir::CoordinateOp>(
1283 loc, rFieldRefType, fir::getBase(rhs), rField);
1284 mlir::Value field = builder.create<fir::FieldIndexOp>(
1285 loc, fieldIndexType, lFieldName, lhsType, fir::getTypeParams(lhs));
1286 auto fieldRefType = builder.getRefType(lFieldTy);
1287 mlir::Value toCoor = builder.create<fir::CoordinateOp>(
1288 loc, fieldRefType, fir::getBase(lhs), field);
1289 std::optional<fir::DoLoopOp> outerLoop;
1290 if (auto sequenceType = mlir::dyn_cast<fir::SequenceType>(lFieldTy)) {
1291 // Create loops to assign array components elements by elements.
1292 // Note that, since these are components, they either do not overlap,
1293 // or are the same and exactly overlap. They also have compile time
1294 // constant shapes.
1295 mlir::Type idxTy = builder.getIndexType();
1296 llvm::SmallVector<mlir::Value> indices;
1297 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
1298 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
1299 for (auto extent : llvm::reverse(sequenceType.getShape())) {
1300 // TODO: add zero size test !
1301 mlir::Value ub = builder.createIntegerConstant(loc, idxTy, extent - 1);
1302 auto loop = builder.create<fir::DoLoopOp>(loc, zero, ub, one);
1303 if (!outerLoop)
1304 outerLoop = loop;
1305 indices.push_back(loop.getInductionVar());
1306 builder.setInsertionPointToStart(loop.getBody());
1307 }
1308 // Set indices in column-major order.
1309 std::reverse(indices.begin(), indices.end());
1310 auto elementRefType = builder.getRefType(sequenceType.getEleTy());
1311 toCoor = builder.create<fir::CoordinateOp>(loc, elementRefType, toCoor,
1312 indices);
1313 fromCoor = builder.create<fir::CoordinateOp>(loc, elementRefType,
1314 fromCoor, indices);
1315 }
1316 if (auto fieldEleTy = fir::unwrapSequenceType(lFieldTy);
1317 mlir::isa<fir::BaseBoxType>(fieldEleTy)) {
1318 assert(mlir::isa<fir::PointerType>(
1319 mlir::cast<fir::BaseBoxType>(fieldEleTy).getEleTy()) &&
1320 "allocatable members require deep copy");
1321 auto fromPointerValue = builder.create<fir::LoadOp>(loc, fromCoor);
1322 auto castTo = builder.createConvert(loc, fieldEleTy, fromPointerValue);
1323 builder.create<fir::StoreOp>(loc, castTo, toCoor);
1324 } else {
1325 auto from =
1326 fir::factory::componentToExtendedValue(builder, loc, fromCoor);
1327 auto to = fir::factory::componentToExtendedValue(builder, loc, toCoor);
1328 // If LHS finalization is needed it is expected to be done
1329 // for the parent record, so that component-by-component
1330 // assignments may avoid finalization calls.
1331 fir::factory::genScalarAssignment(builder, loc, to, from,
1332 /*needFinalization=*/false,
1333 isTemporaryLHS);
1334 }
1335 if (outerLoop)
1336 builder.setInsertionPointAfter(*outerLoop);
1337 }
1338 }
1339
1340 /// Can the assignment of this record type be implement with a simple memory
1341 /// copy (it requires no deep copy or user defined assignment of components )?
1342 static bool recordTypeCanBeMemCopied(fir::RecordType recordType) {
1343 if (fir::hasDynamicSize(recordType))
1344 return false;
1345 for (auto [_, fieldType] : recordType.getTypeList()) {
1346 // Derived type component may have user assignment (so far, we cannot tell
1347 // in FIR, so assume it is always the case, TODO: get the actual info).
1348 if (mlir::isa<fir::RecordType>(fir::unwrapSequenceType(fieldType)))
1349 return false;
1350 // Allocatable components need deep copy.
1351 if (auto boxType = mlir::dyn_cast<fir::BaseBoxType>(fieldType))
1352 if (mlir::isa<fir::HeapType>(boxType.getEleTy()))
1353 return false;
1354 }
1355 // Constant size components without user defined assignment and pointers can
1356 // be memcopied.
1357 return true;
1358 }
1359
1360 static bool mayHaveFinalizer(fir::RecordType recordType,
1361 fir::FirOpBuilder &builder) {
1362 if (auto typeInfo = builder.getModule().lookupSymbol<fir::TypeInfoOp>(
1363 recordType.getName()))
1364 return !typeInfo.getNoFinal();
1365 // No info, be pessimistic.
1366 return true;
1367 }
1368
1369 void fir::factory::genRecordAssignment(fir::FirOpBuilder &builder,
1370 mlir::Location loc,
1371 const fir::ExtendedValue &lhs,
1372 const fir::ExtendedValue &rhs,
1373 bool needFinalization,
1374 bool isTemporaryLHS) {
1375 assert(lhs.rank() == 0 && rhs.rank() == 0 && "assume scalar assignment");
1376 auto baseTy = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(lhs).getType());
1377 assert(baseTy && "must be a memory type");
1378 // Box operands may be polymorphic, it is not entirely clear from 10.2.1.3
1379 // if the assignment is performed on the dynamic of declared type. Use the
1380 // runtime assuming it is performed on the dynamic type.
1381 bool hasBoxOperands =
1382 mlir::isa<fir::BaseBoxType>(fir::getBase(lhs).getType()) ||
1383 mlir::isa<fir::BaseBoxType>(fir::getBase(rhs).getType());
1384 auto recTy = mlir::dyn_cast<fir::RecordType>(baseTy);
1385 assert(recTy && "must be a record type");
1386 if ((needFinalization && mayHaveFinalizer(recTy, builder)) ||
1387 hasBoxOperands || !recordTypeCanBeMemCopied(recTy)) {
1388 auto to = fir::getBase(builder.createBox(loc, lhs));
1389 auto from = fir::getBase(builder.createBox(loc, rhs));
1390 // The runtime entry point may modify the LHS descriptor if it is
1391 // an allocatable. Allocatable assignment is handle elsewhere in lowering,
1392 // so just create a fir.ref<fir.box<>> from the fir.box to comply with the
1393 // runtime interface, but assume the fir.box is unchanged.
1394 // TODO: does this holds true with polymorphic entities ?
1395 auto toMutableBox = builder.createTemporary(loc, to.getType());
1396 builder.create<fir::StoreOp>(loc, to, toMutableBox);
1397 if (isTemporaryLHS)
1398 fir::runtime::genAssignTemporary(builder, loc, toMutableBox, from);
1399 else
1400 fir::runtime::genAssign(builder, loc, toMutableBox, from);
1401 return;
1402 }
1403
1404 // Otherwise, the derived type has compile time constant size and for which
1405 // the component by component assignment can be replaced by a memory copy.
1406 // Since we do not know the size of the derived type in lowering, do a
1407 // component by component assignment. Note that a single fir.load/fir.store
1408 // could be used on "small" record types, but as the type size grows, this
1409 // leads to issues in LLVM (long compile times, long IR files, and even
1410 // asserts at some point). Since there is no good size boundary, just always
1411 // use component by component assignment here.
1412 genComponentByComponentAssignment(builder, loc, lhs, rhs, isTemporaryLHS);
1413 }
1414
1415 mlir::TupleType
1416 fir::factory::getRaggedArrayHeaderType(fir::FirOpBuilder &builder) {
1417 mlir::IntegerType i64Ty = builder.getIntegerType(64);
1418 auto arrTy = fir::SequenceType::get(builder.getIntegerType(8), 1);
1419 auto buffTy = fir::HeapType::get(arrTy);
1420 auto extTy = fir::SequenceType::get(i64Ty, 1);
1421 auto shTy = fir::HeapType::get(extTy);
1422 return mlir::TupleType::get(builder.getContext(), {i64Ty, buffTy, shTy});
1423 }
1424
1425 mlir::Value fir::factory::genLenOfCharacter(
1426 fir::FirOpBuilder &builder, mlir::Location loc, fir::ArrayLoadOp arrLoad,
1427 llvm::ArrayRef<mlir::Value> path, llvm::ArrayRef<mlir::Value> substring) {
1428 llvm::SmallVector<mlir::Value> typeParams(arrLoad.getTypeparams());
1429 return genLenOfCharacter(builder, loc,
1430 mlir::cast<fir::SequenceType>(arrLoad.getType()),
1431 arrLoad.getMemref(), typeParams, path, substring);
1432 }
1433
1434 mlir::Value fir::factory::genLenOfCharacter(
1435 fir::FirOpBuilder &builder, mlir::Location loc, fir::SequenceType seqTy,
1436 mlir::Value memref, llvm::ArrayRef<mlir::Value> typeParams,
1437 llvm::ArrayRef<mlir::Value> path, llvm::ArrayRef<mlir::Value> substring) {
1438 auto idxTy = builder.getIndexType();
1439 auto zero = builder.createIntegerConstant(loc, idxTy, 0);
1440 auto saturatedDiff = [&](mlir::Value lower, mlir::Value upper) {
1441 auto diff = builder.create<mlir::arith::SubIOp>(loc, upper, lower);
1442 auto one = builder.createIntegerConstant(loc, idxTy, 1);
1443 auto size = builder.create<mlir::arith::AddIOp>(loc, diff, one);
1444 auto cmp = builder.create<mlir::arith::CmpIOp>(
1445 loc, mlir::arith::CmpIPredicate::sgt, size, zero);
1446 return builder.create<mlir::arith::SelectOp>(loc, cmp, size, zero);
1447 };
1448 if (substring.size() == 2) {
1449 auto upper = builder.createConvert(loc, idxTy, substring.back());
1450 auto lower = builder.createConvert(loc, idxTy, substring.front());
1451 return saturatedDiff(lower, upper);
1452 }
1453 auto lower = zero;
1454 if (substring.size() == 1)
1455 lower = builder.createConvert(loc, idxTy, substring.front());
1456 auto eleTy = fir::applyPathToType(seqTy, path);
1457 if (!fir::hasDynamicSize(eleTy)) {
1458 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
1459 // Use LEN from the type.
1460 return builder.createIntegerConstant(loc, idxTy, charTy.getLen());
1461 }
1462 // Do we need to support !fir.array<!fir.char<k,n>>?
1463 fir::emitFatalError(loc,
1464 "application of path did not result in a !fir.char");
1465 }
1466 if (fir::isa_box_type(memref.getType())) {
1467 if (mlir::isa<fir::BoxCharType>(memref.getType()))
1468 return builder.create<fir::BoxCharLenOp>(loc, idxTy, memref);
1469 if (mlir::isa<fir::BoxType>(memref.getType()))
1470 return CharacterExprHelper(builder, loc).readLengthFromBox(memref);
1471 fir::emitFatalError(loc, "memref has wrong type");
1472 }
1473 if (typeParams.empty()) {
1474 fir::emitFatalError(loc, "array_load must have typeparams");
1475 }
1476 if (fir::isa_char(seqTy.getEleTy())) {
1477 assert(typeParams.size() == 1 && "too many typeparams");
1478 return typeParams.front();
1479 }
1480 TODO(loc, "LEN of character must be computed at runtime");
1481 }
1482
1483 mlir::Value fir::factory::createZeroValue(fir::FirOpBuilder &builder,
1484 mlir::Location loc, mlir::Type type) {
1485 mlir::Type i1 = builder.getIntegerType(1);
1486 if (mlir::isa<fir::LogicalType>(type) || type == i1)
1487 return builder.createConvert(loc, type, builder.createBool(loc, false));
1488 if (fir::isa_integer(type))
1489 return builder.createIntegerConstant(loc, type, 0);
1490 if (fir::isa_real(type))
1491 return builder.createRealZeroConstant(loc, type);
1492 if (fir::isa_complex(type)) {
1493 fir::factory::Complex complexHelper(builder, loc);
1494 mlir::Type partType = complexHelper.getComplexPartType(type);
1495 mlir::Value zeroPart = builder.createRealZeroConstant(loc, partType);
1496 return complexHelper.createComplex(type, zeroPart, zeroPart);
1497 }
1498 fir::emitFatalError(loc, "internal: trying to generate zero value of non "
1499 "numeric or logical type");
1500 }
1501
1502 std::optional<std::int64_t>
1503 fir::factory::getExtentFromTriplet(mlir::Value lb, mlir::Value ub,
1504 mlir::Value stride) {
1505 std::function<std::optional<std::int64_t>(mlir::Value)> getConstantValue =
1506 [&](mlir::Value value) -> std::optional<std::int64_t> {
1507 if (auto valInt = fir::getIntIfConstant(value))
1508 return *valInt;
1509 auto *definingOp = value.getDefiningOp();
1510 if (mlir::isa_and_nonnull<fir::ConvertOp>(definingOp)) {
1511 auto valOp = mlir::dyn_cast<fir::ConvertOp>(definingOp);
1512 return getConstantValue(valOp.getValue());
1513 }
1514 return {};
1515 };
1516 if (auto lbInt = getConstantValue(lb)) {
1517 if (auto ubInt = getConstantValue(ub)) {
1518 if (auto strideInt = getConstantValue(stride)) {
1519 if (*strideInt != 0) {
1520 std::int64_t extent = 1 + (*ubInt - *lbInt) / *strideInt;
1521 if (extent > 0)
1522 return extent;
1523 }
1524 }
1525 }
1526 }
1527 return {};
1528 }
1529
1530 mlir::Value fir::factory::genMaxWithZero(fir::FirOpBuilder &builder,
1531 mlir::Location loc,
1532 mlir::Value value) {
1533 mlir::Value zero = builder.createIntegerConstant(loc, value.getType(), 0);
1534 if (mlir::Operation *definingOp = value.getDefiningOp())
1535 if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp))
1536 if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(cst.getValue()))
1537 return intAttr.getInt() > 0 ? value : zero;
1538 mlir::Value valueIsGreater = builder.create<mlir::arith::CmpIOp>(
1539 loc, mlir::arith::CmpIPredicate::sgt, value, zero);
1540 return builder.create<mlir::arith::SelectOp>(loc, valueIsGreater, value,
1541 zero);
1542 }
1543
1544 static std::pair<mlir::Value, mlir::Type>
1545 genCPtrOrCFunptrFieldIndex(fir::FirOpBuilder &builder, mlir::Location loc,
1546 mlir::Type cptrTy) {
1547 auto recTy = mlir::cast<fir::RecordType>(cptrTy);
1548 assert(recTy.getTypeList().size() == 1);
1549 auto addrFieldName = recTy.getTypeList()[0].first;
1550 mlir::Type addrFieldTy = recTy.getTypeList()[0].second;
1551 auto fieldIndexType = fir::FieldType::get(cptrTy.getContext());
1552 mlir::Value addrFieldIndex = builder.create<fir::FieldIndexOp>(
1553 loc, fieldIndexType, addrFieldName, recTy,
1554 /*typeParams=*/mlir::ValueRange{});
1555 return {addrFieldIndex, addrFieldTy};
1556 }
1557
1558 mlir::Value fir::factory::genCPtrOrCFunptrAddr(fir::FirOpBuilder &builder,
1559 mlir::Location loc,
1560 mlir::Value cPtr,
1561 mlir::Type ty) {
1562 auto [addrFieldIndex, addrFieldTy] =
1563 genCPtrOrCFunptrFieldIndex(builder, loc, ty);
1564 return builder.create<fir::CoordinateOp>(loc, builder.getRefType(addrFieldTy),
1565 cPtr, addrFieldIndex);
1566 }
1567
1568 mlir::Value fir::factory::genCPtrOrCFunptrValue(fir::FirOpBuilder &builder,
1569 mlir::Location loc,
1570 mlir::Value cPtr) {
1571 mlir::Type cPtrTy = fir::unwrapRefType(cPtr.getType());
1572 if (fir::isa_ref_type(cPtr.getType())) {
1573 mlir::Value cPtrAddr =
1574 fir::factory::genCPtrOrCFunptrAddr(builder, loc, cPtr, cPtrTy);
1575 return builder.create<fir::LoadOp>(loc, cPtrAddr);
1576 }
1577 auto [addrFieldIndex, addrFieldTy] =
1578 genCPtrOrCFunptrFieldIndex(builder, loc, cPtrTy);
1579 auto arrayAttr =
1580 builder.getArrayAttr({builder.getIntegerAttr(builder.getIndexType(), 0)});
1581 return builder.create<fir::ExtractValueOp>(loc, addrFieldTy, cPtr, arrayAttr);
1582 }
1583
1584 fir::BoxValue fir::factory::createBoxValue(fir::FirOpBuilder &builder,
1585 mlir::Location loc,
1586 const fir::ExtendedValue &exv) {
1587 if (auto *boxValue = exv.getBoxOf<fir::BoxValue>())
1588 return *boxValue;
1589 mlir::Value box = builder.createBox(loc, exv);
1590 llvm::SmallVector<mlir::Value> lbounds;
1591 llvm::SmallVector<mlir::Value> explicitTypeParams;
1592 exv.match(
1593 [&](const fir::ArrayBoxValue &box) {
1594 lbounds.append(box.getLBounds().begin(), box.getLBounds().end());
1595 },
1596 [&](const fir::CharArrayBoxValue &box) {
1597 lbounds.append(box.getLBounds().begin(), box.getLBounds().end());
1598 explicitTypeParams.emplace_back(box.getLen());
1599 },
1600 [&](const fir::CharBoxValue &box) {
1601 explicitTypeParams.emplace_back(box.getLen());
1602 },
1603 [&](const fir::MutableBoxValue &x) {
1604 if (x.rank() > 0) {
1605 // The resulting box lbounds must be coming from the mutable box.
1606 fir::ExtendedValue boxVal =
1607 fir::factory::genMutableBoxRead(builder, loc, x);
1608 // Make sure we do not recurse infinitely.
1609 if (boxVal.getBoxOf<fir::MutableBoxValue>())
1610 fir::emitFatalError(loc, "mutable box read cannot be mutable box");
1611 fir::BoxValue box =
1612 fir::factory::createBoxValue(builder, loc, boxVal);
1613 lbounds.append(box.getLBounds().begin(), box.getLBounds().end());
1614 }
1615 explicitTypeParams.append(x.nonDeferredLenParams().begin(),
1616 x.nonDeferredLenParams().end());
1617 },
1618 [](const auto &) {});
1619 return fir::BoxValue(box, lbounds, explicitTypeParams);
1620 }
1621
1622 mlir::Value fir::factory::createNullBoxProc(fir::FirOpBuilder &builder,
1623 mlir::Location loc,
1624 mlir::Type boxType) {
1625 auto boxTy{mlir::dyn_cast<fir::BoxProcType>(boxType)};
1626 if (!boxTy)
1627 fir::emitFatalError(loc, "Procedure pointer must be of BoxProcType");
1628 auto boxEleTy{fir::unwrapRefType(boxTy.getEleTy())};
1629 mlir::Value initVal{builder.create<fir::ZeroOp>(loc, boxEleTy)};
1630 return builder.create<fir::EmboxProcOp>(loc, boxTy, initVal);
1631 }
1632
1633 void fir::factory::setInternalLinkage(mlir::func::FuncOp func) {
1634 auto internalLinkage = mlir::LLVM::linkage::Linkage::Internal;
1635 auto linkage =
1636 mlir::LLVM::LinkageAttr::get(func->getContext(), internalLinkage);
1637 func->setAttr("llvm.linkage", linkage);
1638 }