Debian Codegraph @

flang/lib/Optimizer/CodeGen/CodeGen.cpp

raw
1 //===-- CodeGen.cpp -- bridge to lower to LLVM ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "flang/Optimizer/CodeGen/CodeGen.h"
14
15 #include "flang/Optimizer/CodeGen/CGOps.h"
16 #include "flang/Optimizer/CodeGen/CodeGenOpenMP.h"
17 #include "flang/Optimizer/CodeGen/FIROpPatterns.h"
18 #include "flang/Optimizer/CodeGen/TypeConverter.h"
19 #include "flang/Optimizer/Dialect/FIRAttr.h"
20 #include "flang/Optimizer/Dialect/FIROps.h"
21 #include "flang/Optimizer/Dialect/FIRType.h"
22 #include "flang/Optimizer/Support/DataLayout.h"
23 #include "flang/Optimizer/Support/InternalNames.h"
24 #include "flang/Optimizer/Support/TypeCode.h"
25 #include "flang/Optimizer/Support/Utils.h"
26 #include "flang/Semantics/runtime-type-info.h"
27 #include "mlir/Conversion/ArithCommon/AttrToLLVMConverter.h"
28 #include "mlir/Conversion/ArithToLLVM/ArithToLLVM.h"
29 #include "mlir/Conversion/ComplexToLLVM/ComplexToLLVM.h"
30 #include "mlir/Conversion/ComplexToStandard/ComplexToStandard.h"
31 #include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
32 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
33 #include "mlir/Conversion/LLVMCommon/Pattern.h"
34 #include "mlir/Conversion/MathToFuncs/MathToFuncs.h"
35 #include "mlir/Conversion/MathToLLVM/MathToLLVM.h"
36 #include "mlir/Conversion/MathToLibm/MathToLibm.h"
37 #include "mlir/Conversion/OpenMPToLLVM/ConvertOpenMPToLLVM.h"
38 #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h"
39 #include "mlir/Dialect/Arith/IR/Arith.h"
40 #include "mlir/Dialect/DLTI/DLTI.h"
41 #include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
42 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
43 #include "mlir/Dialect/LLVMIR/Transforms/AddComdats.h"
44 #include "mlir/Dialect/OpenACC/OpenACC.h"
45 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
46 #include "mlir/IR/BuiltinTypes.h"
47 #include "mlir/IR/Matchers.h"
48 #include "mlir/Pass/Pass.h"
49 #include "mlir/Pass/PassManager.h"
50 #include "mlir/Target/LLVMIR/Import.h"
51 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
52 #include "llvm/ADT/ArrayRef.h"
53 #include "llvm/ADT/TypeSwitch.h"
54
55 namespace fir {
56 #define GEN_PASS_DEF_FIRTOLLVMLOWERING
57 #include "flang/Optimizer/CodeGen/CGPasses.h.inc"
58 } // namespace fir
59
60 #define DEBUG_TYPE "flang-codegen"
61
62 // TODO: This should really be recovered from the specified target.
63 static constexpr unsigned defaultAlign = 8;
64
65 /// `fir.box` attribute values as defined for CFI_attribute_t in
66 /// flang/ISO_Fortran_binding.h.
67 static constexpr unsigned kAttrPointer = CFI_attribute_pointer;
68 static constexpr unsigned kAttrAllocatable = CFI_attribute_allocatable;
69
70 static inline mlir::Type getLlvmPtrType(mlir::MLIRContext *context,
71 unsigned addressSpace = 0) {
72 return mlir::LLVM::LLVMPointerType::get(context, addressSpace);
73 }
74
75 static inline mlir::Type getI8Type(mlir::MLIRContext *context) {
76 return mlir::IntegerType::get(context, 8);
77 }
78
79 static mlir::LLVM::ConstantOp
80 genConstantIndex(mlir::Location loc, mlir::Type ity,
81 mlir::ConversionPatternRewriter &rewriter,
82 std::int64_t offset) {
83 auto cattr = rewriter.getI64IntegerAttr(offset);
84 return rewriter.create<mlir::LLVM::ConstantOp>(loc, ity, cattr);
85 }
86
87 static mlir::Block *createBlock(mlir::ConversionPatternRewriter &rewriter,
88 mlir::Block *insertBefore) {
89 assert(insertBefore && "expected valid insertion block");
90 return rewriter.createBlock(insertBefore->getParent(),
91 mlir::Region::iterator(insertBefore));
92 }
93
94 /// Extract constant from a value that must be the result of one of the
95 /// ConstantOp operations.
96 static int64_t getConstantIntValue(mlir::Value val) {
97 if (auto constVal = fir::getIntIfConstant(val))
98 return *constVal;
99 fir::emitFatalError(val.getLoc(), "must be a constant");
100 }
101
102 static unsigned getTypeDescFieldId(mlir::Type ty) {
103 auto isArray = mlir::isa<fir::SequenceType>(fir::dyn_cast_ptrOrBoxEleTy(ty));
104 return isArray ? kOptTypePtrPosInBox : kDimsPosInBox;
105 }
106 static unsigned getLenParamFieldId(mlir::Type ty) {
107 return getTypeDescFieldId(ty) + 1;
108 }
109
110 namespace {
111 /// Lower `fir.address_of` operation to `llvm.address_of` operation.
112 struct AddrOfOpConversion : public fir::FIROpConversion<fir::AddrOfOp> {
113 using FIROpConversion::FIROpConversion;
114
115 llvm::LogicalResult
116 matchAndRewrite(fir::AddrOfOp addr, OpAdaptor adaptor,
117 mlir::ConversionPatternRewriter &rewriter) const override {
118 auto ty = convertType(addr.getType());
119 rewriter.replaceOpWithNewOp<mlir::LLVM::AddressOfOp>(
120 addr, ty, addr.getSymbol().getRootReference().getValue());
121 return mlir::success();
122 }
123 };
124 } // namespace
125
126 /// Lookup the function to compute the memory size of this parametric derived
127 /// type. The size of the object may depend on the LEN type parameters of the
128 /// derived type.
129 static mlir::LLVM::LLVMFuncOp
130 getDependentTypeMemSizeFn(fir::RecordType recTy, fir::AllocaOp op,
131 mlir::ConversionPatternRewriter &rewriter) {
132 auto module = op->getParentOfType<mlir::ModuleOp>();
133 std::string name = recTy.getName().str() + "P.mem.size";
134 if (auto memSizeFunc = module.lookupSymbol<mlir::LLVM::LLVMFuncOp>(name))
135 return memSizeFunc;
136 TODO(op.getLoc(), "did not find allocation function");
137 }
138
139 // Compute the alloc scale size (constant factors encoded in the array type).
140 // We do this for arrays without a constant interior or arrays of character with
141 // dynamic length arrays, since those are the only ones that get decayed to a
142 // pointer to the element type.
143 template <typename OP>
144 static mlir::Value
145 genAllocationScaleSize(OP op, mlir::Type ity,
146 mlir::ConversionPatternRewriter &rewriter) {
147 mlir::Location loc = op.getLoc();
148 mlir::Type dataTy = op.getInType();
149 auto seqTy = mlir::dyn_cast<fir::SequenceType>(dataTy);
150 fir::SequenceType::Extent constSize = 1;
151 if (seqTy) {
152 int constRows = seqTy.getConstantRows();
153 const fir::SequenceType::ShapeRef &shape = seqTy.getShape();
154 if (constRows != static_cast<int>(shape.size())) {
155 for (auto extent : shape) {
156 if (constRows-- > 0)
157 continue;
158 if (extent != fir::SequenceType::getUnknownExtent())
159 constSize *= extent;
160 }
161 }
162 }
163
164 if (constSize != 1) {
165 mlir::Value constVal{
166 genConstantIndex(loc, ity, rewriter, constSize).getResult()};
167 return constVal;
168 }
169 return nullptr;
170 }
171
172 namespace {
173 struct DeclareOpConversion : public fir::FIROpConversion<fir::cg::XDeclareOp> {
174 public:
175 using FIROpConversion::FIROpConversion;
176 llvm::LogicalResult
177 matchAndRewrite(fir::cg::XDeclareOp declareOp, OpAdaptor adaptor,
178 mlir::ConversionPatternRewriter &rewriter) const override {
179 auto memRef = adaptor.getOperands()[0];
180 if (auto fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(declareOp.getLoc())) {
181 if (auto varAttr =
182 mlir::dyn_cast_or_null<mlir::LLVM::DILocalVariableAttr>(
183 fusedLoc.getMetadata())) {
184 rewriter.create<mlir::LLVM::DbgDeclareOp>(memRef.getLoc(), memRef,
185 varAttr, nullptr);
186 }
187 }
188 rewriter.replaceOp(declareOp, memRef);
189 return mlir::success();
190 }
191 };
192 } // namespace
193
194 namespace {
195 /// convert to LLVM IR dialect `alloca`
196 struct AllocaOpConversion : public fir::FIROpConversion<fir::AllocaOp> {
197 using FIROpConversion::FIROpConversion;
198
199 llvm::LogicalResult
200 matchAndRewrite(fir::AllocaOp alloc, OpAdaptor adaptor,
201 mlir::ConversionPatternRewriter &rewriter) const override {
202 mlir::ValueRange operands = adaptor.getOperands();
203 auto loc = alloc.getLoc();
204 mlir::Type ity = lowerTy().indexType();
205 unsigned i = 0;
206 mlir::Value size = genConstantIndex(loc, ity, rewriter, 1).getResult();
207 mlir::Type firObjType = fir::unwrapRefType(alloc.getType());
208 mlir::Type llvmObjectType = convertObjectType(firObjType);
209 if (alloc.hasLenParams()) {
210 unsigned end = alloc.numLenParams();
211 llvm::SmallVector<mlir::Value> lenParams;
212 for (; i < end; ++i)
213 lenParams.push_back(operands[i]);
214 mlir::Type scalarType = fir::unwrapSequenceType(alloc.getInType());
215 if (auto chrTy = mlir::dyn_cast<fir::CharacterType>(scalarType)) {
216 fir::CharacterType rawCharTy = fir::CharacterType::getUnknownLen(
217 chrTy.getContext(), chrTy.getFKind());
218 llvmObjectType = convertType(rawCharTy);
219 assert(end == 1);
220 size = integerCast(loc, rewriter, ity, lenParams[0], /*fold=*/true);
221 } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(scalarType)) {
222 mlir::LLVM::LLVMFuncOp memSizeFn =
223 getDependentTypeMemSizeFn(recTy, alloc, rewriter);
224 if (!memSizeFn)
225 emitError(loc, "did not find allocation function");
226 mlir::NamedAttribute attr = rewriter.getNamedAttr(
227 "callee", mlir::SymbolRefAttr::get(memSizeFn));
228 auto call = rewriter.create<mlir::LLVM::CallOp>(
229 loc, ity, lenParams, llvm::ArrayRef<mlir::NamedAttribute>{attr});
230 size = call.getResult();
231 llvmObjectType = ::getI8Type(alloc.getContext());
232 } else {
233 return emitError(loc, "unexpected type ")
234 << scalarType << " with type parameters";
235 }
236 }
237 if (auto scaleSize = genAllocationScaleSize(alloc, ity, rewriter))
238 size =
239 rewriter.createOrFold<mlir::LLVM::MulOp>(loc, ity, size, scaleSize);
240 if (alloc.hasShapeOperands()) {
241 unsigned end = operands.size();
242 for (; i < end; ++i)
243 size = rewriter.createOrFold<mlir::LLVM::MulOp>(
244 loc, ity, size,
245 integerCast(loc, rewriter, ity, operands[i], /*fold=*/true));
246 }
247
248 unsigned allocaAs = getAllocaAddressSpace(rewriter);
249 unsigned programAs = getProgramAddressSpace(rewriter);
250
251 if (mlir::isa<mlir::LLVM::ConstantOp>(size.getDefiningOp())) {
252 // Set the Block in which the llvm alloca should be inserted.
253 mlir::Operation *parentOp = rewriter.getInsertionBlock()->getParentOp();
254 mlir::Region *parentRegion = rewriter.getInsertionBlock()->getParent();
255 mlir::Block *insertBlock =
256 getBlockForAllocaInsert(parentOp, parentRegion);
257 size.getDefiningOp()->moveBefore(&insertBlock->front());
258 rewriter.setInsertionPointAfter(size.getDefiningOp());
259 }
260
261 // NOTE: we used to pass alloc->getAttrs() in the builder for non opaque
262 // pointers! Only propagate pinned and bindc_name to help debugging, but
263 // this should have no functional purpose (and passing the operand segment
264 // attribute like before is certainly bad).
265 auto llvmAlloc = rewriter.create<mlir::LLVM::AllocaOp>(
266 loc, ::getLlvmPtrType(alloc.getContext(), allocaAs), llvmObjectType,
267 size);
268 if (alloc.getPinned())
269 llvmAlloc->setDiscardableAttr(alloc.getPinnedAttrName(),
270 alloc.getPinnedAttr());
271 if (alloc.getBindcName())
272 llvmAlloc->setDiscardableAttr(alloc.getBindcNameAttrName(),
273 alloc.getBindcNameAttr());
274 if (allocaAs == programAs) {
275 rewriter.replaceOp(alloc, llvmAlloc);
276 } else {
277 // if our allocation address space, is not the same as the program address
278 // space, then we must emit a cast to the program address space before
279 // use. An example case would be on AMDGPU, where the allocation address
280 // space is the numeric value 5 (private), and the program address space
281 // is 0 (generic).
282 rewriter.replaceOpWithNewOp<mlir::LLVM::AddrSpaceCastOp>(
283 alloc, ::getLlvmPtrType(alloc.getContext(), programAs), llvmAlloc);
284 }
285 return mlir::success();
286 }
287 };
288 } // namespace
289
290 namespace {
291 /// Lower `fir.box_addr` to the sequence of operations to extract the first
292 /// element of the box.
293 struct BoxAddrOpConversion : public fir::FIROpConversion<fir::BoxAddrOp> {
294 using FIROpConversion::FIROpConversion;
295
296 llvm::LogicalResult
297 matchAndRewrite(fir::BoxAddrOp boxaddr, OpAdaptor adaptor,
298 mlir::ConversionPatternRewriter &rewriter) const override {
299 mlir::Value a = adaptor.getOperands()[0];
300 auto loc = boxaddr.getLoc();
301 if (auto argty =
302 mlir::dyn_cast<fir::BaseBoxType>(boxaddr.getVal().getType())) {
303 TypePair boxTyPair = getBoxTypePair(argty);
304 rewriter.replaceOp(boxaddr,
305 getBaseAddrFromBox(loc, boxTyPair, a, rewriter));
306 } else {
307 rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractValueOp>(boxaddr, a, 0);
308 }
309 return mlir::success();
310 }
311 };
312
313 /// Convert `!fir.boxchar_len` to `!llvm.extractvalue` for the 2nd part of the
314 /// boxchar.
315 struct BoxCharLenOpConversion : public fir::FIROpConversion<fir::BoxCharLenOp> {
316 using FIROpConversion::FIROpConversion;
317
318 llvm::LogicalResult
319 matchAndRewrite(fir::BoxCharLenOp boxCharLen, OpAdaptor adaptor,
320 mlir::ConversionPatternRewriter &rewriter) const override {
321 mlir::Value boxChar = adaptor.getOperands()[0];
322 mlir::Location loc = boxChar.getLoc();
323 mlir::Type returnValTy = boxCharLen.getResult().getType();
324
325 constexpr int boxcharLenIdx = 1;
326 auto len = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, boxChar,
327 boxcharLenIdx);
328 mlir::Value lenAfterCast = integerCast(loc, rewriter, returnValTy, len);
329 rewriter.replaceOp(boxCharLen, lenAfterCast);
330
331 return mlir::success();
332 }
333 };
334
335 /// Lower `fir.box_dims` to a sequence of operations to extract the requested
336 /// dimension information from the boxed value.
337 /// Result in a triple set of GEPs and loads.
338 struct BoxDimsOpConversion : public fir::FIROpConversion<fir::BoxDimsOp> {
339 using FIROpConversion::FIROpConversion;
340
341 llvm::LogicalResult
342 matchAndRewrite(fir::BoxDimsOp boxdims, OpAdaptor adaptor,
343 mlir::ConversionPatternRewriter &rewriter) const override {
344 llvm::SmallVector<mlir::Type, 3> resultTypes = {
345 convertType(boxdims.getResult(0).getType()),
346 convertType(boxdims.getResult(1).getType()),
347 convertType(boxdims.getResult(2).getType()),
348 };
349 TypePair boxTyPair = getBoxTypePair(boxdims.getVal().getType());
350 auto results = getDimsFromBox(boxdims.getLoc(), resultTypes, boxTyPair,
351 adaptor.getOperands()[0],
352 adaptor.getOperands()[1], rewriter);
353 rewriter.replaceOp(boxdims, results);
354 return mlir::success();
355 }
356 };
357
358 /// Lower `fir.box_elesize` to a sequence of operations ro extract the size of
359 /// an element in the boxed value.
360 struct BoxEleSizeOpConversion : public fir::FIROpConversion<fir::BoxEleSizeOp> {
361 using FIROpConversion::FIROpConversion;
362
363 llvm::LogicalResult
364 matchAndRewrite(fir::BoxEleSizeOp boxelesz, OpAdaptor adaptor,
365 mlir::ConversionPatternRewriter &rewriter) const override {
366 mlir::Value box = adaptor.getOperands()[0];
367 auto loc = boxelesz.getLoc();
368 auto ty = convertType(boxelesz.getType());
369 TypePair boxTyPair = getBoxTypePair(boxelesz.getVal().getType());
370 auto elemSize = getElementSizeFromBox(loc, ty, boxTyPair, box, rewriter);
371 rewriter.replaceOp(boxelesz, elemSize);
372 return mlir::success();
373 }
374 };
375
376 /// Lower `fir.box_isalloc` to a sequence of operations to determine if the
377 /// boxed value was from an ALLOCATABLE entity.
378 struct BoxIsAllocOpConversion : public fir::FIROpConversion<fir::BoxIsAllocOp> {
379 using FIROpConversion::FIROpConversion;
380
381 llvm::LogicalResult
382 matchAndRewrite(fir::BoxIsAllocOp boxisalloc, OpAdaptor adaptor,
383 mlir::ConversionPatternRewriter &rewriter) const override {
384 mlir::Value box = adaptor.getOperands()[0];
385 auto loc = boxisalloc.getLoc();
386 TypePair boxTyPair = getBoxTypePair(boxisalloc.getVal().getType());
387 mlir::Value check =
388 genBoxAttributeCheck(loc, boxTyPair, box, rewriter, kAttrAllocatable);
389 rewriter.replaceOp(boxisalloc, check);
390 return mlir::success();
391 }
392 };
393
394 /// Lower `fir.box_isarray` to a sequence of operations to determine if the
395 /// boxed is an array.
396 struct BoxIsArrayOpConversion : public fir::FIROpConversion<fir::BoxIsArrayOp> {
397 using FIROpConversion::FIROpConversion;
398
399 llvm::LogicalResult
400 matchAndRewrite(fir::BoxIsArrayOp boxisarray, OpAdaptor adaptor,
401 mlir::ConversionPatternRewriter &rewriter) const override {
402 mlir::Value a = adaptor.getOperands()[0];
403 auto loc = boxisarray.getLoc();
404 TypePair boxTyPair = getBoxTypePair(boxisarray.getVal().getType());
405 mlir::Value rank = getRankFromBox(loc, boxTyPair, a, rewriter);
406 mlir::Value c0 = genConstantIndex(loc, rank.getType(), rewriter, 0);
407 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
408 boxisarray, mlir::LLVM::ICmpPredicate::ne, rank, c0);
409 return mlir::success();
410 }
411 };
412
413 /// Lower `fir.box_isptr` to a sequence of operations to determined if the
414 /// boxed value was from a POINTER entity.
415 struct BoxIsPtrOpConversion : public fir::FIROpConversion<fir::BoxIsPtrOp> {
416 using FIROpConversion::FIROpConversion;
417
418 llvm::LogicalResult
419 matchAndRewrite(fir::BoxIsPtrOp boxisptr, OpAdaptor adaptor,
420 mlir::ConversionPatternRewriter &rewriter) const override {
421 mlir::Value box = adaptor.getOperands()[0];
422 auto loc = boxisptr.getLoc();
423 TypePair boxTyPair = getBoxTypePair(boxisptr.getVal().getType());
424 mlir::Value check =
425 genBoxAttributeCheck(loc, boxTyPair, box, rewriter, kAttrPointer);
426 rewriter.replaceOp(boxisptr, check);
427 return mlir::success();
428 }
429 };
430
431 /// Lower `fir.box_rank` to the sequence of operation to extract the rank from
432 /// the box.
433 struct BoxRankOpConversion : public fir::FIROpConversion<fir::BoxRankOp> {
434 using FIROpConversion::FIROpConversion;
435
436 llvm::LogicalResult
437 matchAndRewrite(fir::BoxRankOp boxrank, OpAdaptor adaptor,
438 mlir::ConversionPatternRewriter &rewriter) const override {
439 mlir::Value a = adaptor.getOperands()[0];
440 auto loc = boxrank.getLoc();
441 mlir::Type ty = convertType(boxrank.getType());
442 TypePair boxTyPair =
443 getBoxTypePair(fir::unwrapRefType(boxrank.getBox().getType()));
444 mlir::Value rank = getRankFromBox(loc, boxTyPair, a, rewriter);
445 mlir::Value result = integerCast(loc, rewriter, ty, rank);
446 rewriter.replaceOp(boxrank, result);
447 return mlir::success();
448 }
449 };
450
451 /// Lower `fir.boxproc_host` operation. Extracts the host pointer from the
452 /// boxproc.
453 /// TODO: Part of supporting Fortran 2003 procedure pointers.
454 struct BoxProcHostOpConversion
455 : public fir::FIROpConversion<fir::BoxProcHostOp> {
456 using FIROpConversion::FIROpConversion;
457
458 llvm::LogicalResult
459 matchAndRewrite(fir::BoxProcHostOp boxprochost, OpAdaptor adaptor,
460 mlir::ConversionPatternRewriter &rewriter) const override {
461 TODO(boxprochost.getLoc(), "fir.boxproc_host codegen");
462 return mlir::failure();
463 }
464 };
465
466 /// Lower `fir.box_tdesc` to the sequence of operations to extract the type
467 /// descriptor from the box.
468 struct BoxTypeDescOpConversion
469 : public fir::FIROpConversion<fir::BoxTypeDescOp> {
470 using FIROpConversion::FIROpConversion;
471
472 llvm::LogicalResult
473 matchAndRewrite(fir::BoxTypeDescOp boxtypedesc, OpAdaptor adaptor,
474 mlir::ConversionPatternRewriter &rewriter) const override {
475 mlir::Value box = adaptor.getOperands()[0];
476 TypePair boxTyPair = getBoxTypePair(boxtypedesc.getBox().getType());
477 auto typeDescAddr =
478 loadTypeDescAddress(boxtypedesc.getLoc(), boxTyPair, box, rewriter);
479 rewriter.replaceOp(boxtypedesc, typeDescAddr);
480 return mlir::success();
481 }
482 };
483
484 /// Lower `fir.box_typecode` to a sequence of operations to extract the type
485 /// code in the boxed value.
486 struct BoxTypeCodeOpConversion
487 : public fir::FIROpConversion<fir::BoxTypeCodeOp> {
488 using FIROpConversion::FIROpConversion;
489
490 llvm::LogicalResult
491 matchAndRewrite(fir::BoxTypeCodeOp op, OpAdaptor adaptor,
492 mlir::ConversionPatternRewriter &rewriter) const override {
493 mlir::Value box = adaptor.getOperands()[0];
494 auto loc = box.getLoc();
495 auto ty = convertType(op.getType());
496 TypePair boxTyPair = getBoxTypePair(op.getBox().getType());
497 auto typeCode =
498 getValueFromBox(loc, boxTyPair, box, ty, rewriter, kTypePosInBox);
499 rewriter.replaceOp(op, typeCode);
500 return mlir::success();
501 }
502 };
503
504 /// Lower `fir.string_lit` to LLVM IR dialect operation.
505 struct StringLitOpConversion : public fir::FIROpConversion<fir::StringLitOp> {
506 using FIROpConversion::FIROpConversion;
507
508 llvm::LogicalResult
509 matchAndRewrite(fir::StringLitOp constop, OpAdaptor adaptor,
510 mlir::ConversionPatternRewriter &rewriter) const override {
511 auto ty = convertType(constop.getType());
512 auto attr = constop.getValue();
513 if (mlir::isa<mlir::StringAttr>(attr)) {
514 rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(constop, ty, attr);
515 return mlir::success();
516 }
517
518 auto charTy = mlir::cast<fir::CharacterType>(constop.getType());
519 unsigned bits = lowerTy().characterBitsize(charTy);
520 mlir::Type intTy = rewriter.getIntegerType(bits);
521 mlir::Location loc = constop.getLoc();
522 mlir::Value cst = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
523 if (auto arr = mlir::dyn_cast<mlir::DenseElementsAttr>(attr)) {
524 cst = rewriter.create<mlir::LLVM::ConstantOp>(loc, ty, arr);
525 } else if (auto arr = mlir::dyn_cast<mlir::ArrayAttr>(attr)) {
526 for (auto a : llvm::enumerate(arr.getValue())) {
527 // convert each character to a precise bitsize
528 auto elemAttr = mlir::IntegerAttr::get(
529 intTy,
530 mlir::cast<mlir::IntegerAttr>(a.value()).getValue().zextOrTrunc(
531 bits));
532 auto elemCst =
533 rewriter.create<mlir::LLVM::ConstantOp>(loc, intTy, elemAttr);
534 cst = rewriter.create<mlir::LLVM::InsertValueOp>(loc, cst, elemCst,
535 a.index());
536 }
537 } else {
538 return mlir::failure();
539 }
540 rewriter.replaceOp(constop, cst);
541 return mlir::success();
542 }
543 };
544
545 /// `fir.call` -> `llvm.call`
546 struct CallOpConversion : public fir::FIROpConversion<fir::CallOp> {
547 using FIROpConversion::FIROpConversion;
548
549 llvm::LogicalResult
550 matchAndRewrite(fir::CallOp call, OpAdaptor adaptor,
551 mlir::ConversionPatternRewriter &rewriter) const override {
552 llvm::SmallVector<mlir::Type> resultTys;
553 for (auto r : call.getResults())
554 resultTys.push_back(convertType(r.getType()));
555 // Convert arith::FastMathFlagsAttr to LLVM::FastMathFlagsAttr.
556 mlir::arith::AttrConvertFastMathToLLVM<fir::CallOp, mlir::LLVM::CallOp>
557 attrConvert(call);
558 rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
559 call, resultTys, adaptor.getOperands(), attrConvert.getAttrs());
560 return mlir::success();
561 }
562 };
563 } // namespace
564
565 static mlir::Type getComplexEleTy(mlir::Type complex) {
566 if (auto cc = mlir::dyn_cast<mlir::ComplexType>(complex))
567 return cc.getElementType();
568 return mlir::cast<fir::ComplexType>(complex).getElementType();
569 }
570
571 namespace {
572 /// Compare complex values
573 ///
574 /// Per 10.1, the only comparisons available are .EQ. (oeq) and .NE. (une).
575 ///
576 /// For completeness, all other comparison are done on the real component only.
577 struct CmpcOpConversion : public fir::FIROpConversion<fir::CmpcOp> {
578 using FIROpConversion::FIROpConversion;
579
580 llvm::LogicalResult
581 matchAndRewrite(fir::CmpcOp cmp, OpAdaptor adaptor,
582 mlir::ConversionPatternRewriter &rewriter) const override {
583 mlir::ValueRange operands = adaptor.getOperands();
584 mlir::Type resTy = convertType(cmp.getType());
585 mlir::Location loc = cmp.getLoc();
586 mlir::LLVM::FastmathFlags fmf =
587 mlir::arith::convertArithFastMathFlagsToLLVM(cmp.getFastmath());
588 mlir::LLVM::FCmpPredicate pred =
589 static_cast<mlir::LLVM::FCmpPredicate>(cmp.getPredicate());
590 auto rcp = rewriter.create<mlir::LLVM::FCmpOp>(
591 loc, resTy, pred,
592 rewriter.create<mlir::LLVM::ExtractValueOp>(loc, operands[0], 0),
593 rewriter.create<mlir::LLVM::ExtractValueOp>(loc, operands[1], 0), fmf);
594 auto icp = rewriter.create<mlir::LLVM::FCmpOp>(
595 loc, resTy, pred,
596 rewriter.create<mlir::LLVM::ExtractValueOp>(loc, operands[0], 1),
597 rewriter.create<mlir::LLVM::ExtractValueOp>(loc, operands[1], 1), fmf);
598 llvm::SmallVector<mlir::Value, 2> cp = {rcp, icp};
599 switch (cmp.getPredicate()) {
600 case mlir::arith::CmpFPredicate::OEQ: // .EQ.
601 rewriter.replaceOpWithNewOp<mlir::LLVM::AndOp>(cmp, resTy, cp);
602 break;
603 case mlir::arith::CmpFPredicate::UNE: // .NE.
604 rewriter.replaceOpWithNewOp<mlir::LLVM::OrOp>(cmp, resTy, cp);
605 break;
606 default:
607 rewriter.replaceOp(cmp, rcp.getResult());
608 break;
609 }
610 return mlir::success();
611 }
612 };
613
614 /// Lower complex constants
615 struct ConstcOpConversion : public fir::FIROpConversion<fir::ConstcOp> {
616 using FIROpConversion::FIROpConversion;
617
618 llvm::LogicalResult
619 matchAndRewrite(fir::ConstcOp conc, OpAdaptor,
620 mlir::ConversionPatternRewriter &rewriter) const override {
621 mlir::Location loc = conc.getLoc();
622 mlir::Type ty = convertType(conc.getType());
623 mlir::Type ety = convertType(getComplexEleTy(conc.getType()));
624 auto realPart = rewriter.create<mlir::LLVM::ConstantOp>(
625 loc, ety, getValue(conc.getReal()));
626 auto imPart = rewriter.create<mlir::LLVM::ConstantOp>(
627 loc, ety, getValue(conc.getImaginary()));
628 auto undef = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
629 auto setReal =
630 rewriter.create<mlir::LLVM::InsertValueOp>(loc, undef, realPart, 0);
631 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(conc, setReal,
632 imPart, 1);
633 return mlir::success();
634 }
635
636 inline llvm::APFloat getValue(mlir::Attribute attr) const {
637 return mlir::cast<fir::RealAttr>(attr).getValue();
638 }
639 };
640
641 /// convert value of from-type to value of to-type
642 struct ConvertOpConversion : public fir::FIROpConversion<fir::ConvertOp> {
643 using FIROpConversion::FIROpConversion;
644
645 static bool isFloatingPointTy(mlir::Type ty) {
646 return mlir::isa<mlir::FloatType>(ty);
647 }
648
649 llvm::LogicalResult
650 matchAndRewrite(fir::ConvertOp convert, OpAdaptor adaptor,
651 mlir::ConversionPatternRewriter &rewriter) const override {
652 auto fromFirTy = convert.getValue().getType();
653 auto toFirTy = convert.getRes().getType();
654 auto fromTy = convertType(fromFirTy);
655 auto toTy = convertType(toFirTy);
656 mlir::Value op0 = adaptor.getOperands()[0];
657
658 if (fromFirTy == toFirTy) {
659 rewriter.replaceOp(convert, op0);
660 return mlir::success();
661 }
662
663 auto loc = convert.getLoc();
664 auto i1Type = mlir::IntegerType::get(convert.getContext(), 1);
665
666 if (mlir::isa<fir::LogicalType>(fromFirTy) ||
667 mlir::isa<fir::LogicalType>(toFirTy)) {
668 // By specification fir::LogicalType value may be any number,
669 // where non-zero value represents .true. and zero value represents
670 // .false.
671 //
672 // integer<->logical conversion requires value normalization.
673 // Conversion from wide logical to narrow logical must set the result
674 // to non-zero iff the input is non-zero - the easiest way to implement
675 // it is to compare the input agains zero and set the result to
676 // the canonical 0/1.
677 // Conversion from narrow logical to wide logical may be implemented
678 // as a zero or sign extension of the input, but it may use value
679 // normalization as well.
680 if (!mlir::isa<mlir::IntegerType>(fromTy) ||
681 !mlir::isa<mlir::IntegerType>(toTy))
682 return mlir::emitError(loc)
683 << "unsupported types for logical conversion: " << fromTy
684 << " -> " << toTy;
685
686 // Do folding for constant inputs.
687 if (auto constVal = fir::getIntIfConstant(op0)) {
688 mlir::Value normVal =
689 genConstantIndex(loc, toTy, rewriter, *constVal ? 1 : 0);
690 rewriter.replaceOp(convert, normVal);
691 return mlir::success();
692 }
693
694 // If the input is i1, then we can just zero extend it, and
695 // the result will be normalized.
696 if (fromTy == i1Type) {
697 rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(convert, toTy, op0);
698 return mlir::success();
699 }
700
701 // Compare the input with zero.
702 mlir::Value zero = genConstantIndex(loc, fromTy, rewriter, 0);
703 auto isTrue = rewriter.create<mlir::LLVM::ICmpOp>(
704 loc, mlir::LLVM::ICmpPredicate::ne, op0, zero);
705
706 // Zero extend the i1 isTrue result to the required type (unless it is i1
707 // itself).
708 if (toTy != i1Type)
709 rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(convert, toTy, isTrue);
710 else
711 rewriter.replaceOp(convert, isTrue.getResult());
712
713 return mlir::success();
714 }
715
716 if (fromTy == toTy) {
717 rewriter.replaceOp(convert, op0);
718 return mlir::success();
719 }
720 auto convertFpToFp = [&](mlir::Value val, unsigned fromBits,
721 unsigned toBits, mlir::Type toTy) -> mlir::Value {
722 if (fromBits == toBits) {
723 // TODO: Converting between two floating-point representations with the
724 // same bitwidth is not allowed for now.
725 mlir::emitError(loc,
726 "cannot implicitly convert between two floating-point "
727 "representations of the same bitwidth");
728 return {};
729 }
730 if (fromBits > toBits)
731 return rewriter.create<mlir::LLVM::FPTruncOp>(loc, toTy, val);
732 return rewriter.create<mlir::LLVM::FPExtOp>(loc, toTy, val);
733 };
734 // Complex to complex conversion.
735 if (fir::isa_complex(fromFirTy) && fir::isa_complex(toFirTy)) {
736 // Special case: handle the conversion of a complex such that both the
737 // real and imaginary parts are converted together.
738 auto ty = convertType(getComplexEleTy(convert.getValue().getType()));
739 auto rp = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, op0, 0);
740 auto ip = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, op0, 1);
741 auto nt = convertType(getComplexEleTy(convert.getRes().getType()));
742 auto fromBits = mlir::LLVM::getPrimitiveTypeSizeInBits(ty);
743 auto toBits = mlir::LLVM::getPrimitiveTypeSizeInBits(nt);
744 auto rc = convertFpToFp(rp, fromBits, toBits, nt);
745 auto ic = convertFpToFp(ip, fromBits, toBits, nt);
746 auto un = rewriter.create<mlir::LLVM::UndefOp>(loc, toTy);
747 auto i1 = rewriter.create<mlir::LLVM::InsertValueOp>(loc, un, rc, 0);
748 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(convert, i1, ic,
749 1);
750 return mlir::success();
751 }
752
753 // Floating point to floating point conversion.
754 if (isFloatingPointTy(fromTy)) {
755 if (isFloatingPointTy(toTy)) {
756 auto fromBits = mlir::LLVM::getPrimitiveTypeSizeInBits(fromTy);
757 auto toBits = mlir::LLVM::getPrimitiveTypeSizeInBits(toTy);
758 auto v = convertFpToFp(op0, fromBits, toBits, toTy);
759 rewriter.replaceOp(convert, v);
760 return mlir::success();
761 }
762 if (mlir::isa<mlir::IntegerType>(toTy)) {
763 rewriter.replaceOpWithNewOp<mlir::LLVM::FPToSIOp>(convert, toTy, op0);
764 return mlir::success();
765 }
766 } else if (mlir::isa<mlir::IntegerType>(fromTy)) {
767 // Integer to integer conversion.
768 if (mlir::isa<mlir::IntegerType>(toTy)) {
769 auto fromBits = mlir::LLVM::getPrimitiveTypeSizeInBits(fromTy);
770 auto toBits = mlir::LLVM::getPrimitiveTypeSizeInBits(toTy);
771 assert(fromBits != toBits);
772 if (fromBits > toBits) {
773 rewriter.replaceOpWithNewOp<mlir::LLVM::TruncOp>(convert, toTy, op0);
774 return mlir::success();
775 }
776 if (fromFirTy == i1Type) {
777 rewriter.replaceOpWithNewOp<mlir::LLVM::ZExtOp>(convert, toTy, op0);
778 return mlir::success();
779 }
780 rewriter.replaceOpWithNewOp<mlir::LLVM::SExtOp>(convert, toTy, op0);
781 return mlir::success();
782 }
783 // Integer to floating point conversion.
784 if (isFloatingPointTy(toTy)) {
785 rewriter.replaceOpWithNewOp<mlir::LLVM::SIToFPOp>(convert, toTy, op0);
786 return mlir::success();
787 }
788 // Integer to pointer conversion.
789 if (mlir::isa<mlir::LLVM::LLVMPointerType>(toTy)) {
790 rewriter.replaceOpWithNewOp<mlir::LLVM::IntToPtrOp>(convert, toTy, op0);
791 return mlir::success();
792 }
793 } else if (mlir::isa<mlir::LLVM::LLVMPointerType>(fromTy)) {
794 // Pointer to integer conversion.
795 if (mlir::isa<mlir::IntegerType>(toTy)) {
796 rewriter.replaceOpWithNewOp<mlir::LLVM::PtrToIntOp>(convert, toTy, op0);
797 return mlir::success();
798 }
799 // Pointer to pointer conversion.
800 if (mlir::isa<mlir::LLVM::LLVMPointerType>(toTy)) {
801 rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(convert, toTy, op0);
802 return mlir::success();
803 }
804 }
805 return emitError(loc) << "cannot convert " << fromTy << " to " << toTy;
806 }
807 };
808
809 /// `fir.type_info` operation has no specific CodeGen. The operation is
810 /// only used to carry information during FIR to FIR passes. It may be used
811 /// in the future to generate the runtime type info data structures instead
812 /// of generating them in lowering.
813 struct TypeInfoOpConversion : public fir::FIROpConversion<fir::TypeInfoOp> {
814 using FIROpConversion::FIROpConversion;
815
816 llvm::LogicalResult
817 matchAndRewrite(fir::TypeInfoOp op, OpAdaptor,
818 mlir::ConversionPatternRewriter &rewriter) const override {
819 rewriter.eraseOp(op);
820 return mlir::success();
821 }
822 };
823
824 /// `fir.dt_entry` operation has no specific CodeGen. The operation is only used
825 /// to carry information during FIR to FIR passes.
826 struct DTEntryOpConversion : public fir::FIROpConversion<fir::DTEntryOp> {
827 using FIROpConversion::FIROpConversion;
828
829 llvm::LogicalResult
830 matchAndRewrite(fir::DTEntryOp op, OpAdaptor,
831 mlir::ConversionPatternRewriter &rewriter) const override {
832 rewriter.eraseOp(op);
833 return mlir::success();
834 }
835 };
836
837 /// Lower `fir.global_len` operation.
838 struct GlobalLenOpConversion : public fir::FIROpConversion<fir::GlobalLenOp> {
839 using FIROpConversion::FIROpConversion;
840
841 llvm::LogicalResult
842 matchAndRewrite(fir::GlobalLenOp globalLen, OpAdaptor adaptor,
843 mlir::ConversionPatternRewriter &rewriter) const override {
844 TODO(globalLen.getLoc(), "fir.global_len codegen");
845 return mlir::failure();
846 }
847 };
848
849 /// Lower fir.len_param_index
850 struct LenParamIndexOpConversion
851 : public fir::FIROpConversion<fir::LenParamIndexOp> {
852 using FIROpConversion::FIROpConversion;
853
854 // FIXME: this should be specialized by the runtime target
855 llvm::LogicalResult
856 matchAndRewrite(fir::LenParamIndexOp lenp, OpAdaptor,
857 mlir::ConversionPatternRewriter &rewriter) const override {
858 TODO(lenp.getLoc(), "fir.len_param_index codegen");
859 }
860 };
861
862 /// Convert `!fir.emboxchar<!fir.char<KIND, ?>, #n>` into a sequence of
863 /// instructions that generate `!llvm.struct<(ptr<ik>, i64)>`. The 1st element
864 /// in this struct is a pointer. Its type is determined from `KIND`. The 2nd
865 /// element is the length of the character buffer (`#n`).
866 struct EmboxCharOpConversion : public fir::FIROpConversion<fir::EmboxCharOp> {
867 using FIROpConversion::FIROpConversion;
868
869 llvm::LogicalResult
870 matchAndRewrite(fir::EmboxCharOp emboxChar, OpAdaptor adaptor,
871 mlir::ConversionPatternRewriter &rewriter) const override {
872 mlir::ValueRange operands = adaptor.getOperands();
873
874 mlir::Value charBuffer = operands[0];
875 mlir::Value charBufferLen = operands[1];
876
877 mlir::Location loc = emboxChar.getLoc();
878 mlir::Type llvmStructTy = convertType(emboxChar.getType());
879 auto llvmStruct = rewriter.create<mlir::LLVM::UndefOp>(loc, llvmStructTy);
880
881 mlir::Type lenTy =
882 mlir::cast<mlir::LLVM::LLVMStructType>(llvmStructTy).getBody()[1];
883 mlir::Value lenAfterCast = integerCast(loc, rewriter, lenTy, charBufferLen);
884
885 mlir::Type addrTy =
886 mlir::cast<mlir::LLVM::LLVMStructType>(llvmStructTy).getBody()[0];
887 if (addrTy != charBuffer.getType())
888 charBuffer =
889 rewriter.create<mlir::LLVM::BitcastOp>(loc, addrTy, charBuffer);
890
891 auto insertBufferOp = rewriter.create<mlir::LLVM::InsertValueOp>(
892 loc, llvmStruct, charBuffer, 0);
893 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
894 emboxChar, insertBufferOp, lenAfterCast, 1);
895
896 return mlir::success();
897 }
898 };
899 } // namespace
900
901 /// Return the LLVMFuncOp corresponding to the standard malloc call.
902 static mlir::SymbolRefAttr
903 getMalloc(fir::AllocMemOp op, mlir::ConversionPatternRewriter &rewriter) {
904 static constexpr char mallocName[] = "malloc";
905 auto module = op->getParentOfType<mlir::ModuleOp>();
906 if (auto mallocFunc = module.lookupSymbol<mlir::LLVM::LLVMFuncOp>(mallocName))
907 return mlir::SymbolRefAttr::get(mallocFunc);
908 if (auto userMalloc = module.lookupSymbol<mlir::func::FuncOp>(mallocName))
909 return mlir::SymbolRefAttr::get(userMalloc);
910 mlir::OpBuilder moduleBuilder(
911 op->getParentOfType<mlir::ModuleOp>().getBodyRegion());
912 auto indexType = mlir::IntegerType::get(op.getContext(), 64);
913 auto mallocDecl = moduleBuilder.create<mlir::LLVM::LLVMFuncOp>(
914 op.getLoc(), mallocName,
915 mlir::LLVM::LLVMFunctionType::get(getLlvmPtrType(op.getContext()),
916 indexType,
917 /*isVarArg=*/false));
918 return mlir::SymbolRefAttr::get(mallocDecl);
919 }
920
921 /// Helper function for generating the LLVM IR that computes the distance
922 /// in bytes between adjacent elements pointed to by a pointer
923 /// of type \p ptrTy. The result is returned as a value of \p idxTy integer
924 /// type.
925 static mlir::Value
926 computeElementDistance(mlir::Location loc, mlir::Type llvmObjectType,
927 mlir::Type idxTy,
928 mlir::ConversionPatternRewriter &rewriter) {
929 // Note that we cannot use something like
930 // mlir::LLVM::getPrimitiveTypeSizeInBits() for the element type here. For
931 // example, it returns 10 bytes for mlir::Float80Type for targets where it
932 // occupies 16 bytes. Proper solution is probably to use
933 // mlir::DataLayout::getTypeABIAlignment(), but DataLayout is not being set
934 // yet (see llvm-project#57230). For the time being use the '(intptr_t)((type
935 // *)0 + 1)' trick for all types. The generated instructions are optimized
936 // into constant by the first pass of InstCombine, so it should not be a
937 // performance issue.
938 auto llvmPtrTy = ::getLlvmPtrType(llvmObjectType.getContext());
939 auto nullPtr = rewriter.create<mlir::LLVM::ZeroOp>(loc, llvmPtrTy);
940 auto gep = rewriter.create<mlir::LLVM::GEPOp>(
941 loc, llvmPtrTy, llvmObjectType, nullPtr,
942 llvm::ArrayRef<mlir::LLVM::GEPArg>{1});
943 return rewriter.create<mlir::LLVM::PtrToIntOp>(loc, idxTy, gep);
944 }
945
946 /// Return value of the stride in bytes between adjacent elements
947 /// of LLVM type \p llTy. The result is returned as a value of
948 /// \p idxTy integer type.
949 static mlir::Value
950 genTypeStrideInBytes(mlir::Location loc, mlir::Type idxTy,
951 mlir::ConversionPatternRewriter &rewriter,
952 mlir::Type llTy) {
953 // Create a pointer type and use computeElementDistance().
954 return computeElementDistance(loc, llTy, idxTy, rewriter);
955 }
956
957 namespace {
958 /// Lower a `fir.allocmem` instruction into `llvm.call @malloc`
959 struct AllocMemOpConversion : public fir::FIROpConversion<fir::AllocMemOp> {
960 using FIROpConversion::FIROpConversion;
961
962 llvm::LogicalResult
963 matchAndRewrite(fir::AllocMemOp heap, OpAdaptor adaptor,
964 mlir::ConversionPatternRewriter &rewriter) const override {
965 mlir::Type heapTy = heap.getType();
966 mlir::Location loc = heap.getLoc();
967 auto ity = lowerTy().indexType();
968 mlir::Type dataTy = fir::unwrapRefType(heapTy);
969 mlir::Type llvmObjectTy = convertObjectType(dataTy);
970 if (fir::isRecordWithTypeParameters(fir::unwrapSequenceType(dataTy)))
971 TODO(loc, "fir.allocmem codegen of derived type with length parameters");
972 mlir::Value size = genTypeSizeInBytes(loc, ity, rewriter, llvmObjectTy);
973 if (auto scaleSize = genAllocationScaleSize(heap, ity, rewriter))
974 size = rewriter.create<mlir::LLVM::MulOp>(loc, ity, size, scaleSize);
975 for (mlir::Value opnd : adaptor.getOperands())
976 size = rewriter.create<mlir::LLVM::MulOp>(
977 loc, ity, size, integerCast(loc, rewriter, ity, opnd));
978 heap->setAttr("callee", getMalloc(heap, rewriter));
979 rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
980 heap, ::getLlvmPtrType(heap.getContext()), size, heap->getAttrs());
981 return mlir::success();
982 }
983
984 /// Compute the allocation size in bytes of the element type of
985 /// \p llTy pointer type. The result is returned as a value of \p idxTy
986 /// integer type.
987 mlir::Value genTypeSizeInBytes(mlir::Location loc, mlir::Type idxTy,
988 mlir::ConversionPatternRewriter &rewriter,
989 mlir::Type llTy) const {
990 return computeElementDistance(loc, llTy, idxTy, rewriter);
991 }
992 };
993 } // namespace
994
995 /// Return the LLVMFuncOp corresponding to the standard free call.
996 static mlir::SymbolRefAttr getFree(fir::FreeMemOp op,
997 mlir::ConversionPatternRewriter &rewriter) {
998 static constexpr char freeName[] = "free";
999 auto module = op->getParentOfType<mlir::ModuleOp>();
1000 // Check if free already defined in the module.
1001 if (auto freeFunc = module.lookupSymbol<mlir::LLVM::LLVMFuncOp>(freeName))
1002 return mlir::SymbolRefAttr::get(freeFunc);
1003 if (auto freeDefinedByUser =
1004 module.lookupSymbol<mlir::func::FuncOp>(freeName))
1005 return mlir::SymbolRefAttr::get(freeDefinedByUser);
1006 // Create llvm declaration for free.
1007 mlir::OpBuilder moduleBuilder(module.getBodyRegion());
1008 auto voidType = mlir::LLVM::LLVMVoidType::get(op.getContext());
1009 auto freeDecl = moduleBuilder.create<mlir::LLVM::LLVMFuncOp>(
1010 rewriter.getUnknownLoc(), freeName,
1011 mlir::LLVM::LLVMFunctionType::get(voidType,
1012 getLlvmPtrType(op.getContext()),
1013 /*isVarArg=*/false));
1014 return mlir::SymbolRefAttr::get(freeDecl);
1015 }
1016
1017 static unsigned getDimension(mlir::LLVM::LLVMArrayType ty) {
1018 unsigned result = 1;
1019 for (auto eleTy =
1020 mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(ty.getElementType());
1021 eleTy; eleTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(
1022 eleTy.getElementType()))
1023 ++result;
1024 return result;
1025 }
1026
1027 namespace {
1028 /// Lower a `fir.freemem` instruction into `llvm.call @free`
1029 struct FreeMemOpConversion : public fir::FIROpConversion<fir::FreeMemOp> {
1030 using FIROpConversion::FIROpConversion;
1031
1032 llvm::LogicalResult
1033 matchAndRewrite(fir::FreeMemOp freemem, OpAdaptor adaptor,
1034 mlir::ConversionPatternRewriter &rewriter) const override {
1035 mlir::Location loc = freemem.getLoc();
1036 freemem->setAttr("callee", getFree(freemem, rewriter));
1037 rewriter.create<mlir::LLVM::CallOp>(loc, mlir::TypeRange{},
1038 mlir::ValueRange{adaptor.getHeapref()},
1039 freemem->getAttrs());
1040 rewriter.eraseOp(freemem);
1041 return mlir::success();
1042 }
1043 };
1044 } // namespace
1045
1046 // Convert subcomponent array indices from column-major to row-major ordering.
1047 static llvm::SmallVector<mlir::Value>
1048 convertSubcomponentIndices(mlir::Location loc, mlir::Type eleTy,
1049 mlir::ValueRange indices,
1050 mlir::Type *retTy = nullptr) {
1051 llvm::SmallVector<mlir::Value> result;
1052 llvm::SmallVector<mlir::Value> arrayIndices;
1053
1054 auto appendArrayIndices = [&] {
1055 if (arrayIndices.empty())
1056 return;
1057 std::reverse(arrayIndices.begin(), arrayIndices.end());
1058 result.append(arrayIndices.begin(), arrayIndices.end());
1059 arrayIndices.clear();
1060 };
1061
1062 for (mlir::Value index : indices) {
1063 // Component indices can be field index to select a component, or array
1064 // index, to select an element in an array component.
1065 if (auto structTy = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(eleTy)) {
1066 std::int64_t cstIndex = getConstantIntValue(index);
1067 assert(cstIndex < (int64_t)structTy.getBody().size() &&
1068 "out-of-bounds struct field index");
1069 eleTy = structTy.getBody()[cstIndex];
1070 appendArrayIndices();
1071 result.push_back(index);
1072 } else if (auto arrayTy =
1073 mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(eleTy)) {
1074 eleTy = arrayTy.getElementType();
1075 arrayIndices.push_back(index);
1076 } else
1077 fir::emitFatalError(loc, "Unexpected subcomponent type");
1078 }
1079 appendArrayIndices();
1080 if (retTy)
1081 *retTy = eleTy;
1082 return result;
1083 }
1084
1085 /// Common base class for embox to descriptor conversion.
1086 template <typename OP>
1087 struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
1088 using fir::FIROpConversion<OP>::FIROpConversion;
1089 using TypePair = typename fir::FIROpConversion<OP>::TypePair;
1090
1091 static int getCFIAttr(fir::BaseBoxType boxTy) {
1092 auto eleTy = boxTy.getEleTy();
1093 if (mlir::isa<fir::PointerType>(eleTy))
1094 return CFI_attribute_pointer;
1095 if (mlir::isa<fir::HeapType>(eleTy))
1096 return CFI_attribute_allocatable;
1097 return CFI_attribute_other;
1098 }
1099
1100 mlir::Value getCharacterByteSize(mlir::Location loc,
1101 mlir::ConversionPatternRewriter &rewriter,
1102 fir::CharacterType charTy,
1103 mlir::ValueRange lenParams) const {
1104 auto i64Ty = mlir::IntegerType::get(rewriter.getContext(), 64);
1105 mlir::Value size =
1106 genTypeStrideInBytes(loc, i64Ty, rewriter, this->convertType(charTy));
1107 if (charTy.hasConstantLen())
1108 return size; // Length accounted for in the genTypeStrideInBytes GEP.
1109 // Otherwise, multiply the single character size by the length.
1110 assert(!lenParams.empty());
1111 auto len64 = fir::FIROpConversion<OP>::integerCast(loc, rewriter, i64Ty,
1112 lenParams.back());
1113 return rewriter.create<mlir::LLVM::MulOp>(loc, i64Ty, size, len64);
1114 }
1115
1116 // Get the element size and CFI type code of the boxed value.
1117 std::tuple<mlir::Value, mlir::Value> getSizeAndTypeCode(
1118 mlir::Location loc, mlir::ConversionPatternRewriter &rewriter,
1119 mlir::Type boxEleTy, mlir::ValueRange lenParams = {}) const {
1120 auto i64Ty = mlir::IntegerType::get(rewriter.getContext(), 64);
1121 if (auto eleTy = fir::dyn_cast_ptrEleTy(boxEleTy))
1122 boxEleTy = eleTy;
1123 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(boxEleTy))
1124 return getSizeAndTypeCode(loc, rewriter, seqTy.getEleTy(), lenParams);
1125 if (mlir::isa<mlir::NoneType>(
1126 boxEleTy)) // unlimited polymorphic or assumed type
1127 return {rewriter.create<mlir::LLVM::ConstantOp>(loc, i64Ty, 0),
1128 this->genConstantOffset(loc, rewriter, CFI_type_other)};
1129 mlir::Value typeCodeVal = this->genConstantOffset(
1130 loc, rewriter,
1131 fir::getTypeCode(boxEleTy, this->lowerTy().getKindMap()));
1132 if (fir::isa_integer(boxEleTy) ||
1133 mlir::dyn_cast<fir::LogicalType>(boxEleTy) || fir::isa_real(boxEleTy) ||
1134 fir::isa_complex(boxEleTy))
1135 return {genTypeStrideInBytes(loc, i64Ty, rewriter,
1136 this->convertType(boxEleTy)),
1137 typeCodeVal};
1138 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(boxEleTy))
1139 return {getCharacterByteSize(loc, rewriter, charTy, lenParams),
1140 typeCodeVal};
1141 if (fir::isa_ref_type(boxEleTy)) {
1142 auto ptrTy = ::getLlvmPtrType(rewriter.getContext());
1143 return {genTypeStrideInBytes(loc, i64Ty, rewriter, ptrTy), typeCodeVal};
1144 }
1145 if (mlir::isa<fir::RecordType>(boxEleTy))
1146 return {genTypeStrideInBytes(loc, i64Ty, rewriter,
1147 this->convertType(boxEleTy)),
1148 typeCodeVal};
1149 fir::emitFatalError(loc, "unhandled type in fir.box code generation");
1150 }
1151
1152 /// Basic pattern to write a field in the descriptor
1153 mlir::Value insertField(mlir::ConversionPatternRewriter &rewriter,
1154 mlir::Location loc, mlir::Value dest,
1155 llvm::ArrayRef<std::int64_t> fldIndexes,
1156 mlir::Value value, bool bitcast = false) const {
1157 auto boxTy = dest.getType();
1158 auto fldTy = this->getBoxEleTy(boxTy, fldIndexes);
1159 if (!bitcast)
1160 value = this->integerCast(loc, rewriter, fldTy, value);
1161 // bitcast are no-ops with LLVM opaque pointers.
1162 return rewriter.create<mlir::LLVM::InsertValueOp>(loc, dest, value,
1163 fldIndexes);
1164 }
1165
1166 inline mlir::Value
1167 insertBaseAddress(mlir::ConversionPatternRewriter &rewriter,
1168 mlir::Location loc, mlir::Value dest,
1169 mlir::Value base) const {
1170 return insertField(rewriter, loc, dest, {kAddrPosInBox}, base,
1171 /*bitCast=*/true);
1172 }
1173
1174 inline mlir::Value insertLowerBound(mlir::ConversionPatternRewriter &rewriter,
1175 mlir::Location loc, mlir::Value dest,
1176 unsigned dim, mlir::Value lb) const {
1177 return insertField(rewriter, loc, dest,
1178 {kDimsPosInBox, dim, kDimLowerBoundPos}, lb);
1179 }
1180
1181 inline mlir::Value insertExtent(mlir::ConversionPatternRewriter &rewriter,
1182 mlir::Location loc, mlir::Value dest,
1183 unsigned dim, mlir::Value extent) const {
1184 return insertField(rewriter, loc, dest, {kDimsPosInBox, dim, kDimExtentPos},
1185 extent);
1186 }
1187
1188 inline mlir::Value insertStride(mlir::ConversionPatternRewriter &rewriter,
1189 mlir::Location loc, mlir::Value dest,
1190 unsigned dim, mlir::Value stride) const {
1191 return insertField(rewriter, loc, dest, {kDimsPosInBox, dim, kDimStridePos},
1192 stride);
1193 }
1194
1195 /// Get the address of the type descriptor global variable that was created by
1196 /// lowering for derived type \p recType.
1197 mlir::Value getTypeDescriptor(mlir::ModuleOp mod,
1198 mlir::ConversionPatternRewriter &rewriter,
1199 mlir::Location loc,
1200 fir::RecordType recType) const {
1201 std::string name =
1202 fir::NameUniquer::getTypeDescriptorName(recType.getName());
1203 mlir::Type llvmPtrTy = ::getLlvmPtrType(mod.getContext());
1204 if (auto global = mod.template lookupSymbol<fir::GlobalOp>(name)) {
1205 return rewriter.create<mlir::LLVM::AddressOfOp>(loc, llvmPtrTy,
1206 global.getSymName());
1207 }
1208 if (auto global = mod.template lookupSymbol<mlir::LLVM::GlobalOp>(name)) {
1209 // The global may have already been translated to LLVM.
1210 return rewriter.create<mlir::LLVM::AddressOfOp>(loc, llvmPtrTy,
1211 global.getSymName());
1212 }
1213 // Type info derived types do not have type descriptors since they are the
1214 // types defining type descriptors.
1215 if (!this->options.ignoreMissingTypeDescriptors &&
1216 !fir::NameUniquer::belongsToModule(
1217 name, Fortran::semantics::typeInfoBuiltinModule))
1218 fir::emitFatalError(
1219 loc, "runtime derived type info descriptor was not generated");
1220 return rewriter.create<mlir::LLVM::ZeroOp>(loc, llvmPtrTy);
1221 }
1222
1223 mlir::Value populateDescriptor(mlir::Location loc, mlir::ModuleOp mod,
1224 fir::BaseBoxType boxTy, mlir::Type inputType,
1225 mlir::ConversionPatternRewriter &rewriter,
1226 unsigned rank, mlir::Value eleSize,
1227 mlir::Value cfiTy,
1228 mlir::Value typeDesc) const {
1229 auto llvmBoxTy = this->lowerTy().convertBoxTypeAsStruct(boxTy, rank);
1230 bool isUnlimitedPolymorphic = fir::isUnlimitedPolymorphicType(boxTy);
1231 bool useInputType = fir::isPolymorphicType(boxTy) || isUnlimitedPolymorphic;
1232 mlir::Value descriptor =
1233 rewriter.create<mlir::LLVM::UndefOp>(loc, llvmBoxTy);
1234 descriptor =
1235 insertField(rewriter, loc, descriptor, {kElemLenPosInBox}, eleSize);
1236 descriptor = insertField(rewriter, loc, descriptor, {kVersionPosInBox},
1237 this->genI32Constant(loc, rewriter, CFI_VERSION));
1238 descriptor = insertField(rewriter, loc, descriptor, {kRankPosInBox},
1239 this->genI32Constant(loc, rewriter, rank));
1240 descriptor = insertField(rewriter, loc, descriptor, {kTypePosInBox}, cfiTy);
1241 descriptor =
1242 insertField(rewriter, loc, descriptor, {kAttributePosInBox},
1243 this->genI32Constant(loc, rewriter, getCFIAttr(boxTy)));
1244 const bool hasAddendum = fir::boxHasAddendum(boxTy);
1245 descriptor =
1246 insertField(rewriter, loc, descriptor, {kF18AddendumPosInBox},
1247 this->genI32Constant(loc, rewriter, hasAddendum ? 1 : 0));
1248
1249 if (hasAddendum) {
1250 unsigned typeDescFieldId = getTypeDescFieldId(boxTy);
1251 if (!typeDesc) {
1252 if (useInputType) {
1253 mlir::Type innerType = fir::unwrapInnerType(inputType);
1254 if (innerType && mlir::isa<fir::RecordType>(innerType)) {
1255 auto recTy = mlir::dyn_cast<fir::RecordType>(innerType);
1256 typeDesc = getTypeDescriptor(mod, rewriter, loc, recTy);
1257 } else {
1258 // Unlimited polymorphic type descriptor with no record type. Set
1259 // type descriptor address to a clean state.
1260 typeDesc = rewriter.create<mlir::LLVM::ZeroOp>(
1261 loc, ::getLlvmPtrType(mod.getContext()));
1262 }
1263 } else {
1264 typeDesc = getTypeDescriptor(mod, rewriter, loc,
1265 fir::unwrapIfDerived(boxTy));
1266 }
1267 }
1268 if (typeDesc)
1269 descriptor =
1270 insertField(rewriter, loc, descriptor, {typeDescFieldId}, typeDesc,
1271 /*bitCast=*/true);
1272 // Always initialize the length parameter field to zero to avoid issues
1273 // with uninitialized values in Fortran code trying to compare physical
1274 // representation of derived types with pointer/allocatable components.
1275 // This has been seen in hashing algorithms using TRANSFER.
1276 mlir::Value zero =
1277 genConstantIndex(loc, rewriter.getI64Type(), rewriter, 0);
1278 descriptor = insertField(rewriter, loc, descriptor,
1279 {getLenParamFieldId(boxTy), 0}, zero);
1280 }
1281 return descriptor;
1282 }
1283
1284 // Template used for fir::EmboxOp and fir::cg::XEmboxOp
1285 template <typename BOX>
1286 std::tuple<fir::BaseBoxType, mlir::Value, mlir::Value>
1287 consDescriptorPrefix(BOX box, mlir::Type inputType,
1288 mlir::ConversionPatternRewriter &rewriter, unsigned rank,
1289 [[maybe_unused]] mlir::ValueRange substrParams,
1290 mlir::ValueRange lenParams, mlir::Value sourceBox = {},
1291 mlir::Type sourceBoxType = {}) const {
1292 auto loc = box.getLoc();
1293 auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType());
1294 bool useInputType = fir::isPolymorphicType(boxTy) &&
1295 !fir::isUnlimitedPolymorphicType(inputType);
1296 llvm::SmallVector<mlir::Value> typeparams = lenParams;
1297 if constexpr (!std::is_same_v<BOX, fir::EmboxOp>) {
1298 if (!box.getSubstr().empty() && fir::hasDynamicSize(boxTy.getEleTy()))
1299 typeparams.push_back(substrParams[1]);
1300 }
1301
1302 // Write each of the fields with the appropriate values.
1303 // When emboxing an element to a polymorphic descriptor, use the
1304 // input type since the destination descriptor type has not the exact
1305 // information.
1306 auto [eleSize, cfiTy] = getSizeAndTypeCode(
1307 loc, rewriter, useInputType ? inputType : boxTy.getEleTy(), typeparams);
1308
1309 mlir::Value typeDesc;
1310 // When emboxing to a polymorphic box, get the type descriptor, type code
1311 // and element size from the source box if any.
1312 if (fir::isPolymorphicType(boxTy) && sourceBox) {
1313 TypePair sourceBoxTyPair = this->getBoxTypePair(sourceBoxType);
1314 typeDesc =
1315 this->loadTypeDescAddress(loc, sourceBoxTyPair, sourceBox, rewriter);
1316 mlir::Type idxTy = this->lowerTy().indexType();
1317 eleSize = this->getElementSizeFromBox(loc, idxTy, sourceBoxTyPair,
1318 sourceBox, rewriter);
1319 cfiTy = this->getValueFromBox(loc, sourceBoxTyPair, sourceBox,
1320 cfiTy.getType(), rewriter, kTypePosInBox);
1321 }
1322 auto mod = box->template getParentOfType<mlir::ModuleOp>();
1323 mlir::Value descriptor = populateDescriptor(
1324 loc, mod, boxTy, inputType, rewriter, rank, eleSize, cfiTy, typeDesc);
1325
1326 return {boxTy, descriptor, eleSize};
1327 }
1328
1329 std::tuple<fir::BaseBoxType, mlir::Value, mlir::Value>
1330 consDescriptorPrefix(fir::cg::XReboxOp box, mlir::Value loweredBox,
1331 mlir::ConversionPatternRewriter &rewriter, unsigned rank,
1332 mlir::ValueRange substrParams,
1333 mlir::ValueRange lenParams,
1334 mlir::Value typeDesc = {}) const {
1335 auto loc = box.getLoc();
1336 auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType());
1337 auto inputBoxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getBox().getType());
1338 auto inputBoxTyPair = this->getBoxTypePair(inputBoxTy);
1339 llvm::SmallVector<mlir::Value> typeparams = lenParams;
1340 if (!box.getSubstr().empty() && fir::hasDynamicSize(boxTy.getEleTy()))
1341 typeparams.push_back(substrParams[1]);
1342
1343 auto [eleSize, cfiTy] =
1344 getSizeAndTypeCode(loc, rewriter, boxTy.getEleTy(), typeparams);
1345
1346 // Reboxing to a polymorphic entity. eleSize and type code need to
1347 // be retrieved from the initial box and propagated to the new box.
1348 // If the initial box has an addendum, the type desc must be propagated as
1349 // well.
1350 if (fir::isPolymorphicType(boxTy)) {
1351 mlir::Type idxTy = this->lowerTy().indexType();
1352 eleSize = this->getElementSizeFromBox(loc, idxTy, inputBoxTyPair,
1353 loweredBox, rewriter);
1354 cfiTy = this->getValueFromBox(loc, inputBoxTyPair, loweredBox,
1355 cfiTy.getType(), rewriter, kTypePosInBox);
1356 // TODO: For initial box that are unlimited polymorphic entities, this
1357 // code must be made conditional because unlimited polymorphic entities
1358 // with intrinsic type spec does not have addendum.
1359 if (fir::boxHasAddendum(inputBoxTy))
1360 typeDesc = this->loadTypeDescAddress(loc, inputBoxTyPair, loweredBox,
1361 rewriter);
1362 }
1363
1364 auto mod = box->template getParentOfType<mlir::ModuleOp>();
1365 mlir::Value descriptor =
1366 populateDescriptor(loc, mod, boxTy, box.getBox().getType(), rewriter,
1367 rank, eleSize, cfiTy, typeDesc);
1368
1369 return {boxTy, descriptor, eleSize};
1370 }
1371
1372 // Compute the base address of a fir.box given the indices from the slice.
1373 // The indices from the "outer" dimensions (every dimension after the first
1374 // one (included) that is not a compile time constant) must have been
1375 // multiplied with the related extents and added together into \p outerOffset.
1376 mlir::Value
1377 genBoxOffsetGep(mlir::ConversionPatternRewriter &rewriter, mlir::Location loc,
1378 mlir::Value base, mlir::Type llvmBaseObjectType,
1379 mlir::Value outerOffset, mlir::ValueRange cstInteriorIndices,
1380 mlir::ValueRange componentIndices,
1381 std::optional<mlir::Value> substringOffset) const {
1382 llvm::SmallVector<mlir::LLVM::GEPArg> gepArgs{outerOffset};
1383 mlir::Type resultTy = llvmBaseObjectType;
1384 // Fortran is column major, llvm GEP is row major: reverse the indices here.
1385 for (mlir::Value interiorIndex : llvm::reverse(cstInteriorIndices)) {
1386 auto arrayTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(resultTy);
1387 if (!arrayTy)
1388 fir::emitFatalError(
1389 loc,
1390 "corrupted GEP generated being generated in fir.embox/fir.rebox");
1391 resultTy = arrayTy.getElementType();
1392 gepArgs.push_back(interiorIndex);
1393 }
1394 llvm::SmallVector<mlir::Value> gepIndices =
1395 convertSubcomponentIndices(loc, resultTy, componentIndices, &resultTy);
1396 gepArgs.append(gepIndices.begin(), gepIndices.end());
1397 if (substringOffset) {
1398 if (auto arrayTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(resultTy)) {
1399 gepArgs.push_back(*substringOffset);
1400 resultTy = arrayTy.getElementType();
1401 } else {
1402 // If the CHARACTER length is dynamic, the whole base type should have
1403 // degenerated to an llvm.ptr<i[width]>, and there should not be any
1404 // cstInteriorIndices/componentIndices. The substring offset can be
1405 // added to the outterOffset since it applies on the same LLVM type.
1406 if (gepArgs.size() != 1)
1407 fir::emitFatalError(loc,
1408 "corrupted substring GEP in fir.embox/fir.rebox");
1409 mlir::Type outterOffsetTy = gepArgs[0].get<mlir::Value>().getType();
1410 mlir::Value cast =
1411 this->integerCast(loc, rewriter, outterOffsetTy, *substringOffset);
1412
1413 gepArgs[0] = rewriter.create<mlir::LLVM::AddOp>(
1414 loc, outterOffsetTy, gepArgs[0].get<mlir::Value>(), cast);
1415 }
1416 }
1417 mlir::Type llvmPtrTy = ::getLlvmPtrType(resultTy.getContext());
1418 return rewriter.create<mlir::LLVM::GEPOp>(
1419 loc, llvmPtrTy, llvmBaseObjectType, base, gepArgs);
1420 }
1421
1422 template <typename BOX>
1423 void
1424 getSubcomponentIndices(BOX xbox, mlir::Value memref,
1425 mlir::ValueRange operands,
1426 mlir::SmallVectorImpl<mlir::Value> &indices) const {
1427 // For each field in the path add the offset to base via the args list.
1428 // In the most general case, some offsets must be computed since
1429 // they are not be known until runtime.
1430 if (fir::hasDynamicSize(fir::unwrapSequenceType(
1431 fir::unwrapPassByRefType(memref.getType()))))
1432 TODO(xbox.getLoc(),
1433 "fir.embox codegen dynamic size component in derived type");
1434 indices.append(operands.begin() + xbox.subcomponentOffset(),
1435 operands.begin() + xbox.subcomponentOffset() +
1436 xbox.getSubcomponent().size());
1437 }
1438
1439 static bool isInGlobalOp(mlir::ConversionPatternRewriter &rewriter) {
1440 auto *thisBlock = rewriter.getInsertionBlock();
1441 return thisBlock &&
1442 mlir::isa<mlir::LLVM::GlobalOp>(thisBlock->getParentOp());
1443 }
1444
1445 /// If the embox is not in a globalOp body, allocate storage for the box;
1446 /// store the value inside and return the generated alloca. Return the input
1447 /// value otherwise.
1448 mlir::Value
1449 placeInMemoryIfNotGlobalInit(mlir::ConversionPatternRewriter &rewriter,
1450 mlir::Location loc, mlir::Type boxTy,
1451 mlir::Value boxValue) const {
1452 if (isInGlobalOp(rewriter))
1453 return boxValue;
1454 mlir::Type llvmBoxTy = boxValue.getType();
1455 auto alloca = this->genAllocaAndAddrCastWithType(loc, llvmBoxTy,
1456 defaultAlign, rewriter);
1457 auto storeOp = rewriter.create<mlir::LLVM::StoreOp>(loc, boxValue, alloca);
1458 this->attachTBAATag(storeOp, boxTy, boxTy, nullptr);
1459 return alloca;
1460 }
1461 };
1462
1463 /// Compute the extent of a triplet slice (lb:ub:step).
1464 static mlir::Value
1465 computeTripletExtent(mlir::ConversionPatternRewriter &rewriter,
1466 mlir::Location loc, mlir::Value lb, mlir::Value ub,
1467 mlir::Value step, mlir::Value zero, mlir::Type type) {
1468 mlir::Value extent = rewriter.create<mlir::LLVM::SubOp>(loc, type, ub, lb);
1469 extent = rewriter.create<mlir::LLVM::AddOp>(loc, type, extent, step);
1470 extent = rewriter.create<mlir::LLVM::SDivOp>(loc, type, extent, step);
1471 // If the resulting extent is negative (`ub-lb` and `step` have different
1472 // signs), zero must be returned instead.
1473 auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
1474 loc, mlir::LLVM::ICmpPredicate::sgt, extent, zero);
1475 return rewriter.create<mlir::LLVM::SelectOp>(loc, cmp, extent, zero);
1476 }
1477
1478 /// Create a generic box on a memory reference. This conversions lowers the
1479 /// abstract box to the appropriate, initialized descriptor.
1480 struct EmboxOpConversion : public EmboxCommonConversion<fir::EmboxOp> {
1481 using EmboxCommonConversion::EmboxCommonConversion;
1482
1483 llvm::LogicalResult
1484 matchAndRewrite(fir::EmboxOp embox, OpAdaptor adaptor,
1485 mlir::ConversionPatternRewriter &rewriter) const override {
1486 mlir::ValueRange operands = adaptor.getOperands();
1487 mlir::Value sourceBox;
1488 mlir::Type sourceBoxType;
1489 if (embox.getSourceBox()) {
1490 sourceBox = operands[embox.getSourceBoxOffset()];
1491 sourceBoxType = embox.getSourceBox().getType();
1492 }
1493 assert(!embox.getShape() && "There should be no dims on this embox op");
1494 auto [boxTy, dest, eleSize] = consDescriptorPrefix(
1495 embox, fir::unwrapRefType(embox.getMemref().getType()), rewriter,
1496 /*rank=*/0, /*substrParams=*/mlir::ValueRange{},
1497 adaptor.getTypeparams(), sourceBox, sourceBoxType);
1498 dest = insertBaseAddress(rewriter, embox.getLoc(), dest, operands[0]);
1499 if (fir::isDerivedTypeWithLenParams(boxTy)) {
1500 TODO(embox.getLoc(),
1501 "fir.embox codegen of derived with length parameters");
1502 return mlir::failure();
1503 }
1504 auto result =
1505 placeInMemoryIfNotGlobalInit(rewriter, embox.getLoc(), boxTy, dest);
1506 rewriter.replaceOp(embox, result);
1507 return mlir::success();
1508 }
1509 };
1510
1511 /// Create a generic box on a memory reference.
1512 struct XEmboxOpConversion : public EmboxCommonConversion<fir::cg::XEmboxOp> {
1513 using EmboxCommonConversion::EmboxCommonConversion;
1514
1515 llvm::LogicalResult
1516 matchAndRewrite(fir::cg::XEmboxOp xbox, OpAdaptor adaptor,
1517 mlir::ConversionPatternRewriter &rewriter) const override {
1518 mlir::ValueRange operands = adaptor.getOperands();
1519 mlir::Value sourceBox;
1520 mlir::Type sourceBoxType;
1521 if (xbox.getSourceBox()) {
1522 sourceBox = operands[xbox.getSourceBoxOffset()];
1523 sourceBoxType = xbox.getSourceBox().getType();
1524 }
1525 auto [boxTy, dest, resultEleSize] = consDescriptorPrefix(
1526 xbox, fir::unwrapRefType(xbox.getMemref().getType()), rewriter,
1527 xbox.getOutRank(), adaptor.getSubstr(), adaptor.getLenParams(),
1528 sourceBox, sourceBoxType);
1529 // Generate the triples in the dims field of the descriptor
1530 auto i64Ty = mlir::IntegerType::get(xbox.getContext(), 64);
1531 assert(!xbox.getShape().empty() && "must have a shape");
1532 unsigned shapeOffset = xbox.shapeOffset();
1533 bool hasShift = !xbox.getShift().empty();
1534 unsigned shiftOffset = xbox.shiftOffset();
1535 bool hasSlice = !xbox.getSlice().empty();
1536 unsigned sliceOffset = xbox.sliceOffset();
1537 mlir::Location loc = xbox.getLoc();
1538 mlir::Value zero = genConstantIndex(loc, i64Ty, rewriter, 0);
1539 mlir::Value one = genConstantIndex(loc, i64Ty, rewriter, 1);
1540 mlir::Value prevPtrOff = one;
1541 mlir::Type eleTy = boxTy.getEleTy();
1542 const unsigned rank = xbox.getRank();
1543 llvm::SmallVector<mlir::Value> cstInteriorIndices;
1544 unsigned constRows = 0;
1545 mlir::Value ptrOffset = zero;
1546 mlir::Type memEleTy = fir::dyn_cast_ptrEleTy(xbox.getMemref().getType());
1547 assert(mlir::isa<fir::SequenceType>(memEleTy));
1548 auto seqTy = mlir::cast<fir::SequenceType>(memEleTy);
1549 mlir::Type seqEleTy = seqTy.getEleTy();
1550 // Adjust the element scaling factor if the element is a dependent type.
1551 if (fir::hasDynamicSize(seqEleTy)) {
1552 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(seqEleTy)) {
1553 // The GEP pointer type decays to llvm.ptr<i[width]>.
1554 // The scaling factor is the runtime value of the length.
1555 assert(!adaptor.getLenParams().empty());
1556 prevPtrOff = FIROpConversion::integerCast(
1557 loc, rewriter, i64Ty, adaptor.getLenParams().back());
1558 } else if (mlir::isa<fir::RecordType>(seqEleTy)) {
1559 // prevPtrOff = ;
1560 TODO(loc, "generate call to calculate size of PDT");
1561 } else {
1562 fir::emitFatalError(loc, "unexpected dynamic type");
1563 }
1564 } else {
1565 constRows = seqTy.getConstantRows();
1566 }
1567
1568 const auto hasSubcomp = !xbox.getSubcomponent().empty();
1569 const bool hasSubstr = !xbox.getSubstr().empty();
1570 // Initial element stride that will be use to compute the step in
1571 // each dimension. Initially, this is the size of the input element.
1572 // Note that when there are no components/substring, the resultEleSize
1573 // that was previously computed matches the input element size.
1574 mlir::Value prevDimByteStride = resultEleSize;
1575 if (hasSubcomp) {
1576 // We have a subcomponent. The step value needs to be the number of
1577 // bytes per element (which is a derived type).
1578 prevDimByteStride =
1579 genTypeStrideInBytes(loc, i64Ty, rewriter, convertType(seqEleTy));
1580 } else if (hasSubstr) {
1581 // We have a substring. The step value needs to be the number of bytes
1582 // per CHARACTER element.
1583 auto charTy = mlir::cast<fir::CharacterType>(seqEleTy);
1584 if (fir::hasDynamicSize(charTy)) {
1585 prevDimByteStride =
1586 getCharacterByteSize(loc, rewriter, charTy, adaptor.getLenParams());
1587 } else {
1588 prevDimByteStride = genConstantIndex(
1589 loc, i64Ty, rewriter,
1590 charTy.getLen() * lowerTy().characterBitsize(charTy) / 8);
1591 }
1592 }
1593
1594 // Process the array subspace arguments (shape, shift, etc.), if any,
1595 // translating everything to values in the descriptor wherever the entity
1596 // has a dynamic array dimension.
1597 for (unsigned di = 0, descIdx = 0; di < rank; ++di) {
1598 mlir::Value extent = operands[shapeOffset];
1599 mlir::Value outerExtent = extent;
1600 bool skipNext = false;
1601 if (hasSlice) {
1602 mlir::Value off = operands[sliceOffset];
1603 mlir::Value adj = one;
1604 if (hasShift)
1605 adj = operands[shiftOffset];
1606 auto ao = rewriter.create<mlir::LLVM::SubOp>(loc, i64Ty, off, adj);
1607 if (constRows > 0) {
1608 cstInteriorIndices.push_back(ao);
1609 } else {
1610 auto dimOff =
1611 rewriter.create<mlir::LLVM::MulOp>(loc, i64Ty, ao, prevPtrOff);
1612 ptrOffset =
1613 rewriter.create<mlir::LLVM::AddOp>(loc, i64Ty, dimOff, ptrOffset);
1614 }
1615 if (mlir::isa_and_nonnull<fir::UndefOp>(
1616 xbox.getSlice()[3 * di + 1].getDefiningOp())) {
1617 // This dimension contains a scalar expression in the array slice op.
1618 // The dimension is loop invariant, will be dropped, and will not
1619 // appear in the descriptor.
1620 skipNext = true;
1621 }
1622 }
1623 if (!skipNext) {
1624 // store extent
1625 if (hasSlice)
1626 extent = computeTripletExtent(rewriter, loc, operands[sliceOffset],
1627 operands[sliceOffset + 1],
1628 operands[sliceOffset + 2], zero, i64Ty);
1629 // Lower bound is normalized to 0 for BIND(C) interoperability.
1630 mlir::Value lb = zero;
1631 const bool isaPointerOrAllocatable =
1632 mlir::isa<fir::PointerType, fir::HeapType>(eleTy);
1633 // Lower bound is defaults to 1 for POINTER, ALLOCATABLE, and
1634 // denormalized descriptors.
1635 if (isaPointerOrAllocatable || !normalizedLowerBound(xbox))
1636 lb = one;
1637 // If there is a shifted origin, and no fir.slice, and this is not
1638 // a normalized descriptor then use the value from the shift op as
1639 // the lower bound.
1640 if (hasShift && !(hasSlice || hasSubcomp || hasSubstr) &&
1641 (isaPointerOrAllocatable || !normalizedLowerBound(xbox))) {
1642 lb = operands[shiftOffset];
1643 auto extentIsEmpty = rewriter.create<mlir::LLVM::ICmpOp>(
1644 loc, mlir::LLVM::ICmpPredicate::eq, extent, zero);
1645 lb = rewriter.create<mlir::LLVM::SelectOp>(loc, extentIsEmpty, one,
1646 lb);
1647 }
1648 dest = insertLowerBound(rewriter, loc, dest, descIdx, lb);
1649
1650 dest = insertExtent(rewriter, loc, dest, descIdx, extent);
1651
1652 // store step (scaled by shaped extent)
1653 mlir::Value step = prevDimByteStride;
1654 if (hasSlice)
1655 step = rewriter.create<mlir::LLVM::MulOp>(loc, i64Ty, step,
1656 operands[sliceOffset + 2]);
1657 dest = insertStride(rewriter, loc, dest, descIdx, step);
1658 ++descIdx;
1659 }
1660
1661 // compute the stride and offset for the next natural dimension
1662 prevDimByteStride = rewriter.create<mlir::LLVM::MulOp>(
1663 loc, i64Ty, prevDimByteStride, outerExtent);
1664 if (constRows == 0)
1665 prevPtrOff = rewriter.create<mlir::LLVM::MulOp>(loc, i64Ty, prevPtrOff,
1666 outerExtent);
1667 else
1668 --constRows;
1669
1670 // increment iterators
1671 ++shapeOffset;
1672 if (hasShift)
1673 ++shiftOffset;
1674 if (hasSlice)
1675 sliceOffset += 3;
1676 }
1677 mlir::Value base = adaptor.getMemref();
1678 if (hasSlice || hasSubcomp || hasSubstr) {
1679 // Shift the base address.
1680 llvm::SmallVector<mlir::Value> fieldIndices;
1681 std::optional<mlir::Value> substringOffset;
1682 if (hasSubcomp)
1683 getSubcomponentIndices(xbox, xbox.getMemref(), operands, fieldIndices);
1684 if (hasSubstr)
1685 substringOffset = operands[xbox.substrOffset()];
1686 mlir::Type llvmBaseType =
1687 convertType(fir::unwrapRefType(xbox.getMemref().getType()));
1688 base = genBoxOffsetGep(rewriter, loc, base, llvmBaseType, ptrOffset,
1689 cstInteriorIndices, fieldIndices, substringOffset);
1690 }
1691 dest = insertBaseAddress(rewriter, loc, dest, base);
1692 if (fir::isDerivedTypeWithLenParams(boxTy))
1693 TODO(loc, "fir.embox codegen of derived with length parameters");
1694
1695 mlir::Value result =
1696 placeInMemoryIfNotGlobalInit(rewriter, loc, boxTy, dest);
1697 rewriter.replaceOp(xbox, result);
1698 return mlir::success();
1699 }
1700
1701 /// Return true if `xbox` has a normalized lower bounds attribute. A box value
1702 /// that is neither a POINTER nor an ALLOCATABLE should be normalized to a
1703 /// zero origin lower bound for interoperability with BIND(C).
1704 inline static bool normalizedLowerBound(fir::cg::XEmboxOp xbox) {
1705 return xbox->hasAttr(fir::getNormalizedLowerBoundAttrName());
1706 }
1707 };
1708
1709 /// Create a new box given a box reference.
1710 struct XReboxOpConversion : public EmboxCommonConversion<fir::cg::XReboxOp> {
1711 using EmboxCommonConversion::EmboxCommonConversion;
1712
1713 llvm::LogicalResult
1714 matchAndRewrite(fir::cg::XReboxOp rebox, OpAdaptor adaptor,
1715 mlir::ConversionPatternRewriter &rewriter) const override {
1716 mlir::Location loc = rebox.getLoc();
1717 mlir::Type idxTy = lowerTy().indexType();
1718 mlir::Value loweredBox = adaptor.getOperands()[0];
1719 mlir::ValueRange operands = adaptor.getOperands();
1720
1721 // Inside a fir.global, the input box was produced as an llvm.struct<>
1722 // because objects cannot be handled in memory inside a fir.global body that
1723 // must be constant foldable. However, the type translation are not
1724 // contextual, so the fir.box<T> type of the operation that produced the
1725 // fir.box was translated to an llvm.ptr<llvm.struct<>> and the MLIR pass
1726 // manager inserted a builtin.unrealized_conversion_cast that was inserted
1727 // and needs to be removed here.
1728 if (isInGlobalOp(rewriter))
1729 if (auto unrealizedCast =
1730 loweredBox.getDefiningOp<mlir::UnrealizedConversionCastOp>())
1731 loweredBox = unrealizedCast.getInputs()[0];
1732
1733 TypePair inputBoxTyPair = getBoxTypePair(rebox.getBox().getType());
1734
1735 // Create new descriptor and fill its non-shape related data.
1736 llvm::SmallVector<mlir::Value, 2> lenParams;
1737 mlir::Type inputEleTy = getInputEleTy(rebox);
1738 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(inputEleTy)) {
1739 if (charTy.hasConstantLen()) {
1740 mlir::Value len =
1741 genConstantIndex(loc, idxTy, rewriter, charTy.getLen());
1742 lenParams.emplace_back(len);
1743 } else {
1744 mlir::Value len = getElementSizeFromBox(loc, idxTy, inputBoxTyPair,
1745 loweredBox, rewriter);
1746 if (charTy.getFKind() != 1) {
1747 assert(!isInGlobalOp(rewriter) &&
1748 "character target in global op must have constant length");
1749 mlir::Value width =
1750 genConstantIndex(loc, idxTy, rewriter, charTy.getFKind());
1751 len = rewriter.create<mlir::LLVM::SDivOp>(loc, idxTy, len, width);
1752 }
1753 lenParams.emplace_back(len);
1754 }
1755 } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(inputEleTy)) {
1756 if (recTy.getNumLenParams() != 0)
1757 TODO(loc, "reboxing descriptor of derived type with length parameters");
1758 }
1759
1760 // Rebox on polymorphic entities needs to carry over the dynamic type.
1761 mlir::Value typeDescAddr;
1762 if (mlir::isa<fir::ClassType>(inputBoxTyPair.fir) &&
1763 mlir::isa<fir::ClassType>(rebox.getType()))
1764 typeDescAddr =
1765 loadTypeDescAddress(loc, inputBoxTyPair, loweredBox, rewriter);
1766
1767 auto [boxTy, dest, eleSize] =
1768 consDescriptorPrefix(rebox, loweredBox, rewriter, rebox.getOutRank(),
1769 adaptor.getSubstr(), lenParams, typeDescAddr);
1770
1771 // Read input extents, strides, and base address
1772 llvm::SmallVector<mlir::Value> inputExtents;
1773 llvm::SmallVector<mlir::Value> inputStrides;
1774 const unsigned inputRank = rebox.getRank();
1775 for (unsigned dim = 0; dim < inputRank; ++dim) {
1776 llvm::SmallVector<mlir::Value, 3> dimInfo =
1777 getDimsFromBox(loc, {idxTy, idxTy, idxTy}, inputBoxTyPair, loweredBox,
1778 dim, rewriter);
1779 inputExtents.emplace_back(dimInfo[1]);
1780 inputStrides.emplace_back(dimInfo[2]);
1781 }
1782
1783 mlir::Value baseAddr =
1784 getBaseAddrFromBox(loc, inputBoxTyPair, loweredBox, rewriter);
1785
1786 if (!rebox.getSlice().empty() || !rebox.getSubcomponent().empty())
1787 return sliceBox(rebox, boxTy, dest, baseAddr, inputExtents, inputStrides,
1788 operands, rewriter);
1789 return reshapeBox(rebox, boxTy, dest, baseAddr, inputExtents, inputStrides,
1790 operands, rewriter);
1791 }
1792
1793 private:
1794 /// Write resulting shape and base address in descriptor, and replace rebox
1795 /// op.
1796 llvm::LogicalResult
1797 finalizeRebox(fir::cg::XReboxOp rebox, mlir::Type destBoxTy, mlir::Value dest,
1798 mlir::Value base, mlir::ValueRange lbounds,
1799 mlir::ValueRange extents, mlir::ValueRange strides,
1800 mlir::ConversionPatternRewriter &rewriter) const {
1801 mlir::Location loc = rebox.getLoc();
1802 mlir::Value zero =
1803 genConstantIndex(loc, lowerTy().indexType(), rewriter, 0);
1804 mlir::Value one = genConstantIndex(loc, lowerTy().indexType(), rewriter, 1);
1805 for (auto iter : llvm::enumerate(llvm::zip(extents, strides))) {
1806 mlir::Value extent = std::get<0>(iter.value());
1807 unsigned dim = iter.index();
1808 mlir::Value lb = one;
1809 if (!lbounds.empty()) {
1810 lb = lbounds[dim];
1811 auto extentIsEmpty = rewriter.create<mlir::LLVM::ICmpOp>(
1812 loc, mlir::LLVM::ICmpPredicate::eq, extent, zero);
1813 lb = rewriter.create<mlir::LLVM::SelectOp>(loc, extentIsEmpty, one, lb);
1814 };
1815 dest = insertLowerBound(rewriter, loc, dest, dim, lb);
1816 dest = insertExtent(rewriter, loc, dest, dim, extent);
1817 dest = insertStride(rewriter, loc, dest, dim, std::get<1>(iter.value()));
1818 }
1819 dest = insertBaseAddress(rewriter, loc, dest, base);
1820 mlir::Value result =
1821 placeInMemoryIfNotGlobalInit(rewriter, rebox.getLoc(), destBoxTy, dest);
1822 rewriter.replaceOp(rebox, result);
1823 return mlir::success();
1824 }
1825
1826 // Apply slice given the base address, extents and strides of the input box.
1827 llvm::LogicalResult
1828 sliceBox(fir::cg::XReboxOp rebox, mlir::Type destBoxTy, mlir::Value dest,
1829 mlir::Value base, mlir::ValueRange inputExtents,
1830 mlir::ValueRange inputStrides, mlir::ValueRange operands,
1831 mlir::ConversionPatternRewriter &rewriter) const {
1832 mlir::Location loc = rebox.getLoc();
1833 mlir::Type byteTy = ::getI8Type(rebox.getContext());
1834 mlir::Type idxTy = lowerTy().indexType();
1835 mlir::Value zero = genConstantIndex(loc, idxTy, rewriter, 0);
1836 // Apply subcomponent and substring shift on base address.
1837 if (!rebox.getSubcomponent().empty() || !rebox.getSubstr().empty()) {
1838 // Cast to inputEleTy* so that a GEP can be used.
1839 mlir::Type inputEleTy = getInputEleTy(rebox);
1840 mlir::Type llvmBaseObjectType = convertType(inputEleTy);
1841 llvm::SmallVector<mlir::Value> fieldIndices;
1842 std::optional<mlir::Value> substringOffset;
1843 if (!rebox.getSubcomponent().empty())
1844 getSubcomponentIndices(rebox, rebox.getBox(), operands, fieldIndices);
1845 if (!rebox.getSubstr().empty())
1846 substringOffset = operands[rebox.substrOffset()];
1847 base = genBoxOffsetGep(rewriter, loc, base, llvmBaseObjectType, zero,
1848 /*cstInteriorIndices=*/std::nullopt, fieldIndices,
1849 substringOffset);
1850 }
1851
1852 if (rebox.getSlice().empty())
1853 // The array section is of the form array[%component][substring], keep
1854 // the input array extents and strides.
1855 return finalizeRebox(rebox, destBoxTy, dest, base,
1856 /*lbounds*/ std::nullopt, inputExtents, inputStrides,
1857 rewriter);
1858
1859 // The slice is of the form array(i:j:k)[%component]. Compute new extents
1860 // and strides.
1861 llvm::SmallVector<mlir::Value> slicedExtents;
1862 llvm::SmallVector<mlir::Value> slicedStrides;
1863 mlir::Value one = genConstantIndex(loc, idxTy, rewriter, 1);
1864 const bool sliceHasOrigins = !rebox.getShift().empty();
1865 unsigned sliceOps = rebox.sliceOffset();
1866 unsigned shiftOps = rebox.shiftOffset();
1867 auto strideOps = inputStrides.begin();
1868 const unsigned inputRank = inputStrides.size();
1869 for (unsigned i = 0; i < inputRank;
1870 ++i, ++strideOps, ++shiftOps, sliceOps += 3) {
1871 mlir::Value sliceLb =
1872 integerCast(loc, rewriter, idxTy, operands[sliceOps]);
1873 mlir::Value inputStride = *strideOps; // already idxTy
1874 // Apply origin shift: base += (lb-shift)*input_stride
1875 mlir::Value sliceOrigin =
1876 sliceHasOrigins
1877 ? integerCast(loc, rewriter, idxTy, operands[shiftOps])
1878 : one;
1879 mlir::Value diff =
1880 rewriter.create<mlir::LLVM::SubOp>(loc, idxTy, sliceLb, sliceOrigin);
1881 mlir::Value offset =
1882 rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, diff, inputStride);
1883 // Strides from the fir.box are in bytes.
1884 base = genGEP(loc, byteTy, rewriter, base, offset);
1885 // Apply upper bound and step if this is a triplet. Otherwise, the
1886 // dimension is dropped and no extents/strides are computed.
1887 mlir::Value upper = operands[sliceOps + 1];
1888 const bool isTripletSlice =
1889 !mlir::isa_and_nonnull<mlir::LLVM::UndefOp>(upper.getDefiningOp());
1890 if (isTripletSlice) {
1891 mlir::Value step =
1892 integerCast(loc, rewriter, idxTy, operands[sliceOps + 2]);
1893 // extent = ub-lb+step/step
1894 mlir::Value sliceUb = integerCast(loc, rewriter, idxTy, upper);
1895 mlir::Value extent = computeTripletExtent(rewriter, loc, sliceLb,
1896 sliceUb, step, zero, idxTy);
1897 slicedExtents.emplace_back(extent);
1898 // stride = step*input_stride
1899 mlir::Value stride =
1900 rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, step, inputStride);
1901 slicedStrides.emplace_back(stride);
1902 }
1903 }
1904 return finalizeRebox(rebox, destBoxTy, dest, base, /*lbounds*/ std::nullopt,
1905 slicedExtents, slicedStrides, rewriter);
1906 }
1907
1908 /// Apply a new shape to the data described by a box given the base address,
1909 /// extents and strides of the box.
1910 llvm::LogicalResult
1911 reshapeBox(fir::cg::XReboxOp rebox, mlir::Type destBoxTy, mlir::Value dest,
1912 mlir::Value base, mlir::ValueRange inputExtents,
1913 mlir::ValueRange inputStrides, mlir::ValueRange operands,
1914 mlir::ConversionPatternRewriter &rewriter) const {
1915 mlir::ValueRange reboxShifts{operands.begin() + rebox.shiftOffset(),
1916 operands.begin() + rebox.shiftOffset() +
1917 rebox.getShift().size()};
1918 if (rebox.getShape().empty()) {
1919 // Only setting new lower bounds.
1920 return finalizeRebox(rebox, destBoxTy, dest, base, reboxShifts,
1921 inputExtents, inputStrides, rewriter);
1922 }
1923
1924 mlir::Location loc = rebox.getLoc();
1925
1926 llvm::SmallVector<mlir::Value> newStrides;
1927 llvm::SmallVector<mlir::Value> newExtents;
1928 mlir::Type idxTy = lowerTy().indexType();
1929 // First stride from input box is kept. The rest is assumed contiguous
1930 // (it is not possible to reshape otherwise). If the input is scalar,
1931 // which may be OK if all new extents are ones, the stride does not
1932 // matter, use one.
1933 mlir::Value stride = inputStrides.empty()
1934 ? genConstantIndex(loc, idxTy, rewriter, 1)
1935 : inputStrides[0];
1936 for (unsigned i = 0; i < rebox.getShape().size(); ++i) {
1937 mlir::Value rawExtent = operands[rebox.shapeOffset() + i];
1938 mlir::Value extent = integerCast(loc, rewriter, idxTy, rawExtent);
1939 newExtents.emplace_back(extent);
1940 newStrides.emplace_back(stride);
1941 // nextStride = extent * stride;
1942 stride = rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, extent, stride);
1943 }
1944 return finalizeRebox(rebox, destBoxTy, dest, base, reboxShifts, newExtents,
1945 newStrides, rewriter);
1946 }
1947
1948 /// Return scalar element type of the input box.
1949 static mlir::Type getInputEleTy(fir::cg::XReboxOp rebox) {
1950 auto ty = fir::dyn_cast_ptrOrBoxEleTy(rebox.getBox().getType());
1951 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
1952 return seqTy.getEleTy();
1953 return ty;
1954 }
1955 };
1956
1957 /// Lower `fir.emboxproc` operation. Creates a procedure box.
1958 /// TODO: Part of supporting Fortran 2003 procedure pointers.
1959 struct EmboxProcOpConversion : public fir::FIROpConversion<fir::EmboxProcOp> {
1960 using FIROpConversion::FIROpConversion;
1961
1962 llvm::LogicalResult
1963 matchAndRewrite(fir::EmboxProcOp emboxproc, OpAdaptor adaptor,
1964 mlir::ConversionPatternRewriter &rewriter) const override {
1965 TODO(emboxproc.getLoc(), "fir.emboxproc codegen");
1966 return mlir::failure();
1967 }
1968 };
1969
1970 // Code shared between insert_value and extract_value Ops.
1971 struct ValueOpCommon {
1972 // Translate the arguments pertaining to any multidimensional array to
1973 // row-major order for LLVM-IR.
1974 static void toRowMajor(llvm::SmallVectorImpl<int64_t> &indices,
1975 mlir::Type ty) {
1976 assert(ty && "type is null");
1977 const auto end = indices.size();
1978 for (std::remove_const_t<decltype(end)> i = 0; i < end; ++i) {
1979 if (auto seq = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(ty)) {
1980 const auto dim = getDimension(seq);
1981 if (dim > 1) {
1982 auto ub = std::min(i + dim, end);
1983 std::reverse(indices.begin() + i, indices.begin() + ub);
1984 i += dim - 1;
1985 }
1986 ty = getArrayElementType(seq);
1987 } else if (auto st = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(ty)) {
1988 ty = st.getBody()[indices[i]];
1989 } else {
1990 llvm_unreachable("index into invalid type");
1991 }
1992 }
1993 }
1994
1995 static llvm::SmallVector<int64_t>
1996 collectIndices(mlir::ConversionPatternRewriter &rewriter,
1997 mlir::ArrayAttr arrAttr) {
1998 llvm::SmallVector<int64_t> indices;
1999 for (auto i = arrAttr.begin(), e = arrAttr.end(); i != e; ++i) {
2000 if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(*i)) {
2001 indices.push_back(intAttr.getInt());
2002 } else {
2003 auto fieldName = mlir::cast<mlir::StringAttr>(*i).getValue();
2004 ++i;
2005 auto ty = mlir::cast<mlir::TypeAttr>(*i).getValue();
2006 auto index = mlir::cast<fir::RecordType>(ty).getFieldIndex(fieldName);
2007 indices.push_back(index);
2008 }
2009 }
2010 return indices;
2011 }
2012
2013 private:
2014 static mlir::Type getArrayElementType(mlir::LLVM::LLVMArrayType ty) {
2015 auto eleTy = ty.getElementType();
2016 while (auto arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(eleTy))
2017 eleTy = arrTy.getElementType();
2018 return eleTy;
2019 }
2020 };
2021
2022 namespace {
2023 /// Extract a subobject value from an ssa-value of aggregate type
2024 struct ExtractValueOpConversion
2025 : public fir::FIROpAndTypeConversion<fir::ExtractValueOp>,
2026 public ValueOpCommon {
2027 using FIROpAndTypeConversion::FIROpAndTypeConversion;
2028
2029 llvm::LogicalResult
2030 doRewrite(fir::ExtractValueOp extractVal, mlir::Type ty, OpAdaptor adaptor,
2031 mlir::ConversionPatternRewriter &rewriter) const override {
2032 mlir::ValueRange operands = adaptor.getOperands();
2033 auto indices = collectIndices(rewriter, extractVal.getCoor());
2034 toRowMajor(indices, operands[0].getType());
2035 rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractValueOp>(
2036 extractVal, operands[0], indices);
2037 return mlir::success();
2038 }
2039 };
2040
2041 /// InsertValue is the generalized instruction for the composition of new
2042 /// aggregate type values.
2043 struct InsertValueOpConversion
2044 : public mlir::OpConversionPattern<fir::InsertValueOp>,
2045 public ValueOpCommon {
2046 using OpConversionPattern::OpConversionPattern;
2047
2048 llvm::LogicalResult
2049 matchAndRewrite(fir::InsertValueOp insertVal, OpAdaptor adaptor,
2050 mlir::ConversionPatternRewriter &rewriter) const override {
2051 mlir::ValueRange operands = adaptor.getOperands();
2052 auto indices = collectIndices(rewriter, insertVal.getCoor());
2053 toRowMajor(indices, operands[0].getType());
2054 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
2055 insertVal, operands[0], operands[1], indices);
2056 return mlir::success();
2057 }
2058 };
2059
2060 /// InsertOnRange inserts a value into a sequence over a range of offsets.
2061 struct InsertOnRangeOpConversion
2062 : public fir::FIROpAndTypeConversion<fir::InsertOnRangeOp> {
2063 using FIROpAndTypeConversion::FIROpAndTypeConversion;
2064
2065 // Increments an array of subscripts in a row major fasion.
2066 void incrementSubscripts(llvm::ArrayRef<int64_t> dims,
2067 llvm::SmallVectorImpl<int64_t> &subscripts) const {
2068 for (size_t i = dims.size(); i > 0; --i) {
2069 if (++subscripts[i - 1] < dims[i - 1]) {
2070 return;
2071 }
2072 subscripts[i - 1] = 0;
2073 }
2074 }
2075
2076 llvm::LogicalResult
2077 doRewrite(fir::InsertOnRangeOp range, mlir::Type ty, OpAdaptor adaptor,
2078 mlir::ConversionPatternRewriter &rewriter) const override {
2079
2080 llvm::SmallVector<std::int64_t> dims;
2081 auto type = adaptor.getOperands()[0].getType();
2082
2083 // Iteratively extract the array dimensions from the type.
2084 while (auto t = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(type)) {
2085 dims.push_back(t.getNumElements());
2086 type = t.getElementType();
2087 }
2088
2089 llvm::SmallVector<std::int64_t> lBounds;
2090 llvm::SmallVector<std::int64_t> uBounds;
2091
2092 // Unzip the upper and lower bound and convert to a row major format.
2093 mlir::DenseIntElementsAttr coor = range.getCoor();
2094 auto reversedCoor = llvm::reverse(coor.getValues<int64_t>());
2095 for (auto i = reversedCoor.begin(), e = reversedCoor.end(); i != e; ++i) {
2096 uBounds.push_back(*i++);
2097 lBounds.push_back(*i);
2098 }
2099
2100 auto &subscripts = lBounds;
2101 auto loc = range.getLoc();
2102 mlir::Value lastOp = adaptor.getOperands()[0];
2103 mlir::Value insertVal = adaptor.getOperands()[1];
2104
2105 while (subscripts != uBounds) {
2106 lastOp = rewriter.create<mlir::LLVM::InsertValueOp>(
2107 loc, lastOp, insertVal, subscripts);
2108
2109 incrementSubscripts(dims, subscripts);
2110 }
2111
2112 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
2113 range, lastOp, insertVal, subscripts);
2114
2115 return mlir::success();
2116 }
2117 };
2118 } // namespace
2119
2120 namespace {
2121 /// XArrayCoor is the address arithmetic on a dynamically shaped, sliced,
2122 /// shifted etc. array.
2123 /// (See the static restriction on coordinate_of.) array_coor determines the
2124 /// coordinate (location) of a specific element.
2125 struct XArrayCoorOpConversion
2126 : public fir::FIROpAndTypeConversion<fir::cg::XArrayCoorOp> {
2127 using FIROpAndTypeConversion::FIROpAndTypeConversion;
2128
2129 llvm::LogicalResult
2130 doRewrite(fir::cg::XArrayCoorOp coor, mlir::Type llvmPtrTy, OpAdaptor adaptor,
2131 mlir::ConversionPatternRewriter &rewriter) const override {
2132 auto loc = coor.getLoc();
2133 mlir::ValueRange operands = adaptor.getOperands();
2134 unsigned rank = coor.getRank();
2135 assert(coor.getIndices().size() == rank);
2136 assert(coor.getShape().empty() || coor.getShape().size() == rank);
2137 assert(coor.getShift().empty() || coor.getShift().size() == rank);
2138 assert(coor.getSlice().empty() || coor.getSlice().size() == 3 * rank);
2139 mlir::Type idxTy = lowerTy().indexType();
2140 unsigned indexOffset = coor.indicesOffset();
2141 unsigned shapeOffset = coor.shapeOffset();
2142 unsigned shiftOffset = coor.shiftOffset();
2143 unsigned sliceOffset = coor.sliceOffset();
2144 auto sliceOps = coor.getSlice().begin();
2145 mlir::Value one = genConstantIndex(loc, idxTy, rewriter, 1);
2146 mlir::Value prevExt = one;
2147 mlir::Value offset = genConstantIndex(loc, idxTy, rewriter, 0);
2148 const bool isShifted = !coor.getShift().empty();
2149 const bool isSliced = !coor.getSlice().empty();
2150 const bool baseIsBoxed =
2151 mlir::isa<fir::BaseBoxType>(coor.getMemref().getType());
2152 TypePair baseBoxTyPair =
2153 baseIsBoxed ? getBoxTypePair(coor.getMemref().getType()) : TypePair{};
2154 mlir::LLVM::IntegerOverflowFlags nsw =
2155 mlir::LLVM::IntegerOverflowFlags::nsw;
2156
2157 // For each dimension of the array, generate the offset calculation.
2158 for (unsigned i = 0; i < rank; ++i, ++indexOffset, ++shapeOffset,
2159 ++shiftOffset, sliceOffset += 3, sliceOps += 3) {
2160 mlir::Value index =
2161 integerCast(loc, rewriter, idxTy, operands[indexOffset]);
2162 mlir::Value lb =
2163 isShifted ? integerCast(loc, rewriter, idxTy, operands[shiftOffset])
2164 : one;
2165 mlir::Value step = one;
2166 bool normalSlice = isSliced;
2167 // Compute zero based index in dimension i of the element, applying
2168 // potential triplets and lower bounds.
2169 if (isSliced) {
2170 mlir::Value originalUb = *(sliceOps + 1);
2171 normalSlice =
2172 !mlir::isa_and_nonnull<fir::UndefOp>(originalUb.getDefiningOp());
2173 if (normalSlice)
2174 step = integerCast(loc, rewriter, idxTy, operands[sliceOffset + 2]);
2175 }
2176 auto idx = rewriter.create<mlir::LLVM::SubOp>(loc, idxTy, index, lb, nsw);
2177 mlir::Value diff =
2178 rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, idx, step, nsw);
2179 if (normalSlice) {
2180 mlir::Value sliceLb =
2181 integerCast(loc, rewriter, idxTy, operands[sliceOffset]);
2182 auto adj =
2183 rewriter.create<mlir::LLVM::SubOp>(loc, idxTy, sliceLb, lb, nsw);
2184 diff = rewriter.create<mlir::LLVM::AddOp>(loc, idxTy, diff, adj, nsw);
2185 }
2186 // Update the offset given the stride and the zero based index `diff`
2187 // that was just computed.
2188 if (baseIsBoxed) {
2189 // Use stride in bytes from the descriptor.
2190 mlir::Value stride =
2191 getStrideFromBox(loc, baseBoxTyPair, operands[0], i, rewriter);
2192 auto sc =
2193 rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, diff, stride, nsw);
2194 offset =
2195 rewriter.create<mlir::LLVM::AddOp>(loc, idxTy, sc, offset, nsw);
2196 } else {
2197 // Use stride computed at last iteration.
2198 auto sc =
2199 rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, diff, prevExt, nsw);
2200 offset =
2201 rewriter.create<mlir::LLVM::AddOp>(loc, idxTy, sc, offset, nsw);
2202 // Compute next stride assuming contiguity of the base array
2203 // (in element number).
2204 auto nextExt = integerCast(loc, rewriter, idxTy, operands[shapeOffset]);
2205 prevExt = rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, prevExt,
2206 nextExt, nsw);
2207 }
2208 }
2209
2210 // Add computed offset to the base address.
2211 if (baseIsBoxed) {
2212 // Working with byte offsets. The base address is read from the fir.box.
2213 // and used in i8* GEP to do the pointer arithmetic.
2214 mlir::Type byteTy = ::getI8Type(coor.getContext());
2215 mlir::Value base =
2216 getBaseAddrFromBox(loc, baseBoxTyPair, operands[0], rewriter);
2217 llvm::SmallVector<mlir::LLVM::GEPArg> args{offset};
2218 auto addr = rewriter.create<mlir::LLVM::GEPOp>(loc, llvmPtrTy, byteTy,
2219 base, args);
2220 if (coor.getSubcomponent().empty()) {
2221 rewriter.replaceOp(coor, addr);
2222 return mlir::success();
2223 }
2224 // Cast the element address from void* to the derived type so that the
2225 // derived type members can be addresses via a GEP using the index of
2226 // components.
2227 mlir::Type elementType =
2228 getLlvmObjectTypeFromBoxType(coor.getMemref().getType());
2229 while (auto arrayTy =
2230 mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(elementType))
2231 elementType = arrayTy.getElementType();
2232 args.clear();
2233 args.push_back(0);
2234 if (!coor.getLenParams().empty()) {
2235 // If type parameters are present, then we don't want to use a GEPOp
2236 // as below, as the LLVM struct type cannot be statically defined.
2237 TODO(loc, "derived type with type parameters");
2238 }
2239 llvm::SmallVector<mlir::Value> indices = convertSubcomponentIndices(
2240 loc, elementType,
2241 operands.slice(coor.subcomponentOffset(),
2242 coor.getSubcomponent().size()));
2243 args.append(indices.begin(), indices.end());
2244 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(coor, llvmPtrTy,
2245 elementType, addr, args);
2246 return mlir::success();
2247 }
2248
2249 // The array was not boxed, so it must be contiguous. offset is therefore an
2250 // element offset and the base type is kept in the GEP unless the element
2251 // type size is itself dynamic.
2252 mlir::Type objectTy = fir::unwrapRefType(coor.getMemref().getType());
2253 mlir::Type eleType = fir::unwrapSequenceType(objectTy);
2254 mlir::Type gepObjectType = convertType(eleType);
2255 llvm::SmallVector<mlir::LLVM::GEPArg> args;
2256 if (coor.getSubcomponent().empty()) {
2257 // No subcomponent.
2258 if (!coor.getLenParams().empty()) {
2259 // Type parameters. Adjust element size explicitly.
2260 auto eleTy = fir::dyn_cast_ptrEleTy(coor.getType());
2261 assert(eleTy && "result must be a reference-like type");
2262 if (fir::characterWithDynamicLen(eleTy)) {
2263 assert(coor.getLenParams().size() == 1);
2264 auto length = integerCast(loc, rewriter, idxTy,
2265 operands[coor.lenParamsOffset()]);
2266 offset = rewriter.create<mlir::LLVM::MulOp>(loc, idxTy, offset,
2267 length, nsw);
2268 } else {
2269 TODO(loc, "compute size of derived type with type parameters");
2270 }
2271 }
2272 args.push_back(offset);
2273 } else {
2274 // There are subcomponents.
2275 args.push_back(offset);
2276 llvm::SmallVector<mlir::Value> indices = convertSubcomponentIndices(
2277 loc, gepObjectType,
2278 operands.slice(coor.subcomponentOffset(),
2279 coor.getSubcomponent().size()));
2280 args.append(indices.begin(), indices.end());
2281 }
2282 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
2283 coor, llvmPtrTy, gepObjectType, adaptor.getMemref(), args);
2284 return mlir::success();
2285 }
2286 };
2287 } // namespace
2288
2289 /// Convert to (memory) reference to a reference to a subobject.
2290 /// The coordinate_of op is a Swiss army knife operation that can be used on
2291 /// (memory) references to records, arrays, complex, etc. as well as boxes.
2292 /// With unboxed arrays, there is the restriction that the array have a static
2293 /// shape in all but the last column.
2294 struct CoordinateOpConversion
2295 : public fir::FIROpAndTypeConversion<fir::CoordinateOp> {
2296 using FIROpAndTypeConversion::FIROpAndTypeConversion;
2297
2298 llvm::LogicalResult
2299 doRewrite(fir::CoordinateOp coor, mlir::Type ty, OpAdaptor adaptor,
2300 mlir::ConversionPatternRewriter &rewriter) const override {
2301 mlir::ValueRange operands = adaptor.getOperands();
2302
2303 mlir::Location loc = coor.getLoc();
2304 mlir::Value base = operands[0];
2305 mlir::Type baseObjectTy = coor.getBaseType();
2306 mlir::Type objectTy = fir::dyn_cast_ptrOrBoxEleTy(baseObjectTy);
2307 assert(objectTy && "fir.coordinate_of expects a reference type");
2308 mlir::Type llvmObjectTy = convertType(objectTy);
2309
2310 // Complex type - basically, extract the real or imaginary part
2311 // FIXME: double check why this is done before the fir.box case below.
2312 if (fir::isa_complex(objectTy)) {
2313 mlir::Value gep =
2314 genGEP(loc, llvmObjectTy, rewriter, base, 0, operands[1]);
2315 rewriter.replaceOp(coor, gep);
2316 return mlir::success();
2317 }
2318
2319 // Boxed type - get the base pointer from the box
2320 if (mlir::dyn_cast<fir::BaseBoxType>(baseObjectTy))
2321 return doRewriteBox(coor, operands, loc, rewriter);
2322
2323 // Reference, pointer or a heap type
2324 if (mlir::isa<fir::ReferenceType, fir::PointerType, fir::HeapType>(
2325 baseObjectTy))
2326 return doRewriteRefOrPtr(coor, llvmObjectTy, operands, loc, rewriter);
2327
2328 return rewriter.notifyMatchFailure(
2329 coor, "fir.coordinate_of base operand has unsupported type");
2330 }
2331
2332 static unsigned getFieldNumber(fir::RecordType ty, mlir::Value op) {
2333 return fir::hasDynamicSize(ty)
2334 ? op.getDefiningOp()
2335 ->getAttrOfType<mlir::IntegerAttr>("field")
2336 .getInt()
2337 : getConstantIntValue(op);
2338 }
2339
2340 static bool hasSubDimensions(mlir::Type type) {
2341 return mlir::isa<fir::SequenceType, fir::RecordType, mlir::TupleType>(type);
2342 }
2343
2344 /// Check whether this form of `!fir.coordinate_of` is supported. These
2345 /// additional checks are required, because we are not yet able to convert
2346 /// all valid forms of `!fir.coordinate_of`.
2347 /// TODO: Either implement the unsupported cases or extend the verifier
2348 /// in FIROps.cpp instead.
2349 static bool supportedCoordinate(mlir::Type type, mlir::ValueRange coors) {
2350 const std::size_t numOfCoors = coors.size();
2351 std::size_t i = 0;
2352 bool subEle = false;
2353 bool ptrEle = false;
2354 for (; i < numOfCoors; ++i) {
2355 mlir::Value nxtOpnd = coors[i];
2356 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(type)) {
2357 subEle = true;
2358 i += arrTy.getDimension() - 1;
2359 type = arrTy.getEleTy();
2360 } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(type)) {
2361 subEle = true;
2362 type = recTy.getType(getFieldNumber(recTy, nxtOpnd));
2363 } else if (auto tupTy = mlir::dyn_cast<mlir::TupleType>(type)) {
2364 subEle = true;
2365 type = tupTy.getType(getConstantIntValue(nxtOpnd));
2366 } else {
2367 ptrEle = true;
2368 }
2369 }
2370 if (ptrEle)
2371 return (!subEle) && (numOfCoors == 1);
2372 return subEle && (i >= numOfCoors);
2373 }
2374
2375 /// Walk the abstract memory layout and determine if the path traverses any
2376 /// array types with unknown shape. Return true iff all the array types have a
2377 /// constant shape along the path.
2378 static bool arraysHaveKnownShape(mlir::Type type, mlir::ValueRange coors) {
2379 for (std::size_t i = 0, sz = coors.size(); i < sz; ++i) {
2380 mlir::Value nxtOpnd = coors[i];
2381 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(type)) {
2382 if (fir::sequenceWithNonConstantShape(arrTy))
2383 return false;
2384 i += arrTy.getDimension() - 1;
2385 type = arrTy.getEleTy();
2386 } else if (auto strTy = mlir::dyn_cast<fir::RecordType>(type)) {
2387 type = strTy.getType(getFieldNumber(strTy, nxtOpnd));
2388 } else if (auto strTy = mlir::dyn_cast<mlir::TupleType>(type)) {
2389 type = strTy.getType(getConstantIntValue(nxtOpnd));
2390 } else {
2391 return true;
2392 }
2393 }
2394 return true;
2395 }
2396
2397 private:
2398 llvm::LogicalResult
2399 doRewriteBox(fir::CoordinateOp coor, mlir::ValueRange operands,
2400 mlir::Location loc,
2401 mlir::ConversionPatternRewriter &rewriter) const {
2402 mlir::Type boxObjTy = coor.getBaseType();
2403 assert(mlir::dyn_cast<fir::BaseBoxType>(boxObjTy) &&
2404 "This is not a `fir.box`");
2405 TypePair boxTyPair = getBoxTypePair(boxObjTy);
2406
2407 mlir::Value boxBaseAddr = operands[0];
2408
2409 // 1. SPECIAL CASE (uses `fir.len_param_index`):
2410 // %box = ... : !fir.box<!fir.type<derived{len1:i32}>>
2411 // %lenp = fir.len_param_index len1, !fir.type<derived{len1:i32}>
2412 // %addr = coordinate_of %box, %lenp
2413 if (coor.getNumOperands() == 2) {
2414 mlir::Operation *coordinateDef =
2415 (*coor.getCoor().begin()).getDefiningOp();
2416 if (mlir::isa_and_nonnull<fir::LenParamIndexOp>(coordinateDef))
2417 TODO(loc,
2418 "fir.coordinate_of - fir.len_param_index is not supported yet");
2419 }
2420
2421 // 2. GENERAL CASE:
2422 // 2.1. (`fir.array`)
2423 // %box = ... : !fix.box<!fir.array<?xU>>
2424 // %idx = ... : index
2425 // %resultAddr = coordinate_of %box, %idx : !fir.ref<U>
2426 // 2.2 (`fir.derived`)
2427 // %box = ... : !fix.box<!fir.type<derived_type{field_1:i32}>>
2428 // %idx = ... : i32
2429 // %resultAddr = coordinate_of %box, %idx : !fir.ref<i32>
2430 // 2.3 (`fir.derived` inside `fir.array`)
2431 // %box = ... : !fir.box<!fir.array<10 x !fir.type<derived_1{field_1:f32,
2432 // field_2:f32}>>> %idx1 = ... : index %idx2 = ... : i32 %resultAddr =
2433 // coordinate_of %box, %idx1, %idx2 : !fir.ref<f32>
2434 // 2.4. TODO: Either document or disable any other case that the following
2435 // implementation might convert.
2436 mlir::Value resultAddr =
2437 getBaseAddrFromBox(loc, boxTyPair, boxBaseAddr, rewriter);
2438 // Component Type
2439 auto cpnTy = fir::dyn_cast_ptrOrBoxEleTy(boxObjTy);
2440 mlir::Type llvmPtrTy = ::getLlvmPtrType(coor.getContext());
2441 mlir::Type byteTy = ::getI8Type(coor.getContext());
2442 mlir::LLVM::IntegerOverflowFlags nsw =
2443 mlir::LLVM::IntegerOverflowFlags::nsw;
2444
2445 for (unsigned i = 1, last = operands.size(); i < last; ++i) {
2446 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(cpnTy)) {
2447 if (i != 1)
2448 TODO(loc, "fir.array nested inside other array and/or derived type");
2449 // Applies byte strides from the box. Ignore lower bound from box
2450 // since fir.coordinate_of indexes are zero based. Lowering takes care
2451 // of lower bound aspects. This both accounts for dynamically sized
2452 // types and non contiguous arrays.
2453 auto idxTy = lowerTy().indexType();
2454 mlir::Value off = genConstantIndex(loc, idxTy, rewriter, 0);
2455 for (unsigned index = i, lastIndex = i + arrTy.getDimension();
2456 index < lastIndex; ++index) {
2457 mlir::Value stride = getStrideFromBox(loc, boxTyPair, operands[0],
2458 index - i, rewriter);
2459 auto sc = rewriter.create<mlir::LLVM::MulOp>(
2460 loc, idxTy, operands[index], stride, nsw);
2461 off = rewriter.create<mlir::LLVM::AddOp>(loc, idxTy, sc, off, nsw);
2462 }
2463 resultAddr = rewriter.create<mlir::LLVM::GEPOp>(
2464 loc, llvmPtrTy, byteTy, resultAddr,
2465 llvm::ArrayRef<mlir::LLVM::GEPArg>{off});
2466 i += arrTy.getDimension() - 1;
2467 cpnTy = arrTy.getEleTy();
2468 } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(cpnTy)) {
2469 mlir::Value nxtOpnd = operands[i];
2470 cpnTy = recTy.getType(getFieldNumber(recTy, nxtOpnd));
2471 auto llvmRecTy = lowerTy().convertType(recTy);
2472 resultAddr = rewriter.create<mlir::LLVM::GEPOp>(
2473 loc, llvmPtrTy, llvmRecTy, resultAddr,
2474 llvm::ArrayRef<mlir::LLVM::GEPArg>{0, nxtOpnd});
2475 } else {
2476 fir::emitFatalError(loc, "unexpected type in coordinate_of");
2477 }
2478 }
2479
2480 rewriter.replaceOp(coor, resultAddr);
2481 return mlir::success();
2482 }
2483
2484 llvm::LogicalResult
2485 doRewriteRefOrPtr(fir::CoordinateOp coor, mlir::Type llvmObjectTy,
2486 mlir::ValueRange operands, mlir::Location loc,
2487 mlir::ConversionPatternRewriter &rewriter) const {
2488 mlir::Type baseObjectTy = coor.getBaseType();
2489
2490 // Component Type
2491 mlir::Type cpnTy = fir::dyn_cast_ptrOrBoxEleTy(baseObjectTy);
2492 bool hasSubdimension = hasSubDimensions(cpnTy);
2493 bool columnIsDeferred = !hasSubdimension;
2494
2495 if (!supportedCoordinate(cpnTy, operands.drop_front(1)))
2496 TODO(loc, "unsupported combination of coordinate operands");
2497
2498 const bool hasKnownShape =
2499 arraysHaveKnownShape(cpnTy, operands.drop_front(1));
2500
2501 // If only the column is `?`, then we can simply place the column value in
2502 // the 0-th GEP position.
2503 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(cpnTy)) {
2504 if (!hasKnownShape) {
2505 const unsigned sz = arrTy.getDimension();
2506 if (arraysHaveKnownShape(arrTy.getEleTy(),
2507 operands.drop_front(1 + sz))) {
2508 fir::SequenceType::ShapeRef shape = arrTy.getShape();
2509 bool allConst = true;
2510 for (unsigned i = 0; i < sz - 1; ++i) {
2511 if (shape[i] < 0) {
2512 allConst = false;
2513 break;
2514 }
2515 }
2516 if (allConst)
2517 columnIsDeferred = true;
2518 }
2519 }
2520 }
2521
2522 if (fir::hasDynamicSize(fir::unwrapSequenceType(cpnTy)))
2523 return mlir::emitError(
2524 loc, "fir.coordinate_of with a dynamic element size is unsupported");
2525
2526 if (hasKnownShape || columnIsDeferred) {
2527 llvm::SmallVector<mlir::LLVM::GEPArg> offs;
2528 if (hasKnownShape && hasSubdimension) {
2529 offs.push_back(0);
2530 }
2531 std::optional<int> dims;
2532 llvm::SmallVector<mlir::Value> arrIdx;
2533 for (std::size_t i = 1, sz = operands.size(); i < sz; ++i) {
2534 mlir::Value nxtOpnd = operands[i];
2535
2536 if (!cpnTy)
2537 return mlir::emitError(loc, "invalid coordinate/check failed");
2538
2539 // check if the i-th coordinate relates to an array
2540 if (dims) {
2541 arrIdx.push_back(nxtOpnd);
2542 int dimsLeft = *dims;
2543 if (dimsLeft > 1) {
2544 dims = dimsLeft - 1;
2545 continue;
2546 }
2547 cpnTy = mlir::cast<fir::SequenceType>(cpnTy).getEleTy();
2548 // append array range in reverse (FIR arrays are column-major)
2549 offs.append(arrIdx.rbegin(), arrIdx.rend());
2550 arrIdx.clear();
2551 dims.reset();
2552 continue;
2553 }
2554 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(cpnTy)) {
2555 int d = arrTy.getDimension() - 1;
2556 if (d > 0) {
2557 dims = d;
2558 arrIdx.push_back(nxtOpnd);
2559 continue;
2560 }
2561 cpnTy = mlir::cast<fir::SequenceType>(cpnTy).getEleTy();
2562 offs.push_back(nxtOpnd);
2563 continue;
2564 }
2565
2566 // check if the i-th coordinate relates to a field
2567 if (auto recTy = mlir::dyn_cast<fir::RecordType>(cpnTy))
2568 cpnTy = recTy.getType(getFieldNumber(recTy, nxtOpnd));
2569 else if (auto tupTy = mlir::dyn_cast<mlir::TupleType>(cpnTy))
2570 cpnTy = tupTy.getType(getConstantIntValue(nxtOpnd));
2571 else
2572 cpnTy = nullptr;
2573
2574 offs.push_back(nxtOpnd);
2575 }
2576 if (dims)
2577 offs.append(arrIdx.rbegin(), arrIdx.rend());
2578 mlir::Value base = operands[0];
2579 mlir::Value retval = genGEP(loc, llvmObjectTy, rewriter, base, offs);
2580 rewriter.replaceOp(coor, retval);
2581 return mlir::success();
2582 }
2583
2584 return mlir::emitError(
2585 loc, "fir.coordinate_of base operand has unsupported type");
2586 }
2587 };
2588
2589 /// Convert `fir.field_index`. The conversion depends on whether the size of
2590 /// the record is static or dynamic.
2591 struct FieldIndexOpConversion : public fir::FIROpConversion<fir::FieldIndexOp> {
2592 using FIROpConversion::FIROpConversion;
2593
2594 // NB: most field references should be resolved by this point
2595 llvm::LogicalResult
2596 matchAndRewrite(fir::FieldIndexOp field, OpAdaptor adaptor,
2597 mlir::ConversionPatternRewriter &rewriter) const override {
2598 auto recTy = mlir::cast<fir::RecordType>(field.getOnType());
2599 unsigned index = recTy.getFieldIndex(field.getFieldId());
2600
2601 if (!fir::hasDynamicSize(recTy)) {
2602 // Derived type has compile-time constant layout. Return index of the
2603 // component type in the parent type (to be used in GEP).
2604 rewriter.replaceOp(field, mlir::ValueRange{genConstantOffset(
2605 field.getLoc(), rewriter, index)});
2606 return mlir::success();
2607 }
2608
2609 // Derived type has compile-time constant layout. Call the compiler
2610 // generated function to determine the byte offset of the field at runtime.
2611 // This returns a non-constant.
2612 mlir::FlatSymbolRefAttr symAttr = mlir::SymbolRefAttr::get(
2613 field.getContext(), getOffsetMethodName(recTy, field.getFieldId()));
2614 mlir::NamedAttribute callAttr = rewriter.getNamedAttr("callee", symAttr);
2615 mlir::NamedAttribute fieldAttr = rewriter.getNamedAttr(
2616 "field", mlir::IntegerAttr::get(lowerTy().indexType(), index));
2617 rewriter.replaceOpWithNewOp<mlir::LLVM::CallOp>(
2618 field, lowerTy().offsetType(), adaptor.getOperands(),
2619 llvm::ArrayRef<mlir::NamedAttribute>{callAttr, fieldAttr});
2620 return mlir::success();
2621 }
2622
2623 // Re-Construct the name of the compiler generated method that calculates the
2624 // offset
2625 inline static std::string getOffsetMethodName(fir::RecordType recTy,
2626 llvm::StringRef field) {
2627 return recTy.getName().str() + "P." + field.str() + ".offset";
2628 }
2629 };
2630
2631 /// Convert `fir.end`
2632 struct FirEndOpConversion : public fir::FIROpConversion<fir::FirEndOp> {
2633 using FIROpConversion::FIROpConversion;
2634
2635 llvm::LogicalResult
2636 matchAndRewrite(fir::FirEndOp firEnd, OpAdaptor,
2637 mlir::ConversionPatternRewriter &rewriter) const override {
2638 TODO(firEnd.getLoc(), "fir.end codegen");
2639 return mlir::failure();
2640 }
2641 };
2642
2643 /// Lower `fir.type_desc` to a global addr.
2644 struct TypeDescOpConversion : public fir::FIROpConversion<fir::TypeDescOp> {
2645 using FIROpConversion::FIROpConversion;
2646
2647 llvm::LogicalResult
2648 matchAndRewrite(fir::TypeDescOp typeDescOp, OpAdaptor adaptor,
2649 mlir::ConversionPatternRewriter &rewriter) const override {
2650 mlir::Type inTy = typeDescOp.getInType();
2651 assert(mlir::isa<fir::RecordType>(inTy) && "expecting fir.type");
2652 auto recordType = mlir::dyn_cast<fir::RecordType>(inTy);
2653 auto module = typeDescOp.getOperation()->getParentOfType<mlir::ModuleOp>();
2654 std::string typeDescName =
2655 fir::NameUniquer::getTypeDescriptorName(recordType.getName());
2656 auto llvmPtrTy = ::getLlvmPtrType(typeDescOp.getContext());
2657 if (auto global = module.lookupSymbol<mlir::LLVM::GlobalOp>(typeDescName)) {
2658 rewriter.replaceOpWithNewOp<mlir::LLVM::AddressOfOp>(
2659 typeDescOp, llvmPtrTy, global.getSymName());
2660 return mlir::success();
2661 } else if (auto global = module.lookupSymbol<fir::GlobalOp>(typeDescName)) {
2662 rewriter.replaceOpWithNewOp<mlir::LLVM::AddressOfOp>(
2663 typeDescOp, llvmPtrTy, global.getSymName());
2664 return mlir::success();
2665 }
2666 return mlir::failure();
2667 }
2668 };
2669
2670 /// Lower `fir.has_value` operation to `llvm.return` operation.
2671 struct HasValueOpConversion
2672 : public mlir::OpConversionPattern<fir::HasValueOp> {
2673 using OpConversionPattern::OpConversionPattern;
2674
2675 llvm::LogicalResult
2676 matchAndRewrite(fir::HasValueOp op, OpAdaptor adaptor,
2677 mlir::ConversionPatternRewriter &rewriter) const override {
2678 rewriter.replaceOpWithNewOp<mlir::LLVM::ReturnOp>(op,
2679 adaptor.getOperands());
2680 return mlir::success();
2681 }
2682 };
2683
2684 #ifndef NDEBUG
2685 // Check if attr's type is compatible with ty.
2686 //
2687 // This is done by comparing attr's element type, converted to LLVM type,
2688 // with ty's element type.
2689 //
2690 // Only integer and floating point (including complex) attributes are
2691 // supported. Also, attr is expected to have a TensorType and ty is expected
2692 // to be of LLVMArrayType. If any of the previous conditions is false, then
2693 // the specified attr and ty are not supported by this function and are
2694 // assumed to be compatible.
2695 static inline bool attributeTypeIsCompatible(mlir::MLIRContext *ctx,
2696 mlir::Attribute attr,
2697 mlir::Type ty) {
2698 // Get attr's LLVM element type.
2699 if (!attr)
2700 return true;
2701 auto intOrFpEleAttr = mlir::dyn_cast<mlir::DenseIntOrFPElementsAttr>(attr);
2702 if (!intOrFpEleAttr)
2703 return true;
2704 auto tensorTy = mlir::dyn_cast<mlir::TensorType>(intOrFpEleAttr.getType());
2705 if (!tensorTy)
2706 return true;
2707 mlir::Type attrEleTy =
2708 mlir::LLVMTypeConverter(ctx).convertType(tensorTy.getElementType());
2709
2710 // Get ty's element type.
2711 auto arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(ty);
2712 if (!arrTy)
2713 return true;
2714 mlir::Type eleTy = arrTy.getElementType();
2715 while ((arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(eleTy)))
2716 eleTy = arrTy.getElementType();
2717
2718 return attrEleTy == eleTy;
2719 }
2720 #endif
2721
2722 /// Lower `fir.global` operation to `llvm.global` operation.
2723 /// `fir.insert_on_range` operations are replaced with constant dense attribute
2724 /// if they are applied on the full range.
2725 struct GlobalOpConversion : public fir::FIROpConversion<fir::GlobalOp> {
2726 using FIROpConversion::FIROpConversion;
2727
2728 llvm::LogicalResult
2729 matchAndRewrite(fir::GlobalOp global, OpAdaptor adaptor,
2730 mlir::ConversionPatternRewriter &rewriter) const override {
2731
2732 mlir::LLVM::DIGlobalVariableExpressionAttr dbgExpr;
2733
2734 if (auto fusedLoc = mlir::dyn_cast<mlir::FusedLoc>(global.getLoc())) {
2735 if (auto gvAttr =
2736 mlir::dyn_cast_or_null<mlir::LLVM::DIGlobalVariableAttr>(
2737 fusedLoc.getMetadata())) {
2738 dbgExpr = mlir::LLVM::DIGlobalVariableExpressionAttr::get(
2739 global.getContext(), gvAttr, mlir::LLVM::DIExpressionAttr());
2740 }
2741 }
2742
2743 auto tyAttr = convertType(global.getType());
2744 if (auto boxType = mlir::dyn_cast<fir::BaseBoxType>(global.getType()))
2745 tyAttr = this->lowerTy().convertBoxTypeAsStruct(boxType);
2746 auto loc = global.getLoc();
2747 mlir::Attribute initAttr = global.getInitVal().value_or(mlir::Attribute());
2748 assert(attributeTypeIsCompatible(global.getContext(), initAttr, tyAttr));
2749 auto linkage = convertLinkage(global.getLinkName());
2750 auto isConst = global.getConstant().has_value();
2751 mlir::SymbolRefAttr comdat;
2752 llvm::ArrayRef<mlir::NamedAttribute> attrs;
2753 auto g = rewriter.create<mlir::LLVM::GlobalOp>(
2754 loc, tyAttr, isConst, linkage, global.getSymName(), initAttr, 0, 0,
2755 false, false, comdat, attrs, dbgExpr);
2756
2757 if (global.getAlignment() && *global.getAlignment() > 0)
2758 g.setAlignment(*global.getAlignment());
2759
2760 auto module = global->getParentOfType<mlir::ModuleOp>();
2761 // Add comdat if necessary
2762 if (fir::getTargetTriple(module).supportsCOMDAT() &&
2763 (linkage == mlir::LLVM::Linkage::Linkonce ||
2764 linkage == mlir::LLVM::Linkage::LinkonceODR)) {
2765 addComdat(g, rewriter, module);
2766 }
2767
2768 // Apply all non-Fir::GlobalOp attributes to the LLVM::GlobalOp, preserving
2769 // them; whilst taking care not to apply attributes that are lowered in
2770 // other ways.
2771 llvm::SmallDenseSet<llvm::StringRef> elidedAttrsSet(
2772 global.getAttributeNames().begin(), global.getAttributeNames().end());
2773 for (auto &attr : global->getAttrs())
2774 if (!elidedAttrsSet.contains(attr.getName().strref()))
2775 g->setAttr(attr.getName(), attr.getValue());
2776
2777 auto &gr = g.getInitializerRegion();
2778 rewriter.inlineRegionBefore(global.getRegion(), gr, gr.end());
2779 if (!gr.empty()) {
2780 // Replace insert_on_range with a constant dense attribute if the
2781 // initialization is on the full range.
2782 auto insertOnRangeOps = gr.front().getOps<fir::InsertOnRangeOp>();
2783 for (auto insertOp : insertOnRangeOps) {
2784 if (isFullRange(insertOp.getCoor(), insertOp.getType())) {
2785 auto seqTyAttr = convertType(insertOp.getType());
2786 auto *op = insertOp.getVal().getDefiningOp();
2787 auto constant = mlir::dyn_cast<mlir::arith::ConstantOp>(op);
2788 if (!constant) {
2789 auto convertOp = mlir::dyn_cast<fir::ConvertOp>(op);
2790 if (!convertOp)
2791 continue;
2792 constant = mlir::cast<mlir::arith::ConstantOp>(
2793 convertOp.getValue().getDefiningOp());
2794 }
2795 mlir::Type vecType = mlir::VectorType::get(
2796 insertOp.getType().getShape(), constant.getType());
2797 auto denseAttr = mlir::DenseElementsAttr::get(
2798 mlir::cast<mlir::ShapedType>(vecType), constant.getValue());
2799 rewriter.setInsertionPointAfter(insertOp);
2800 rewriter.replaceOpWithNewOp<mlir::arith::ConstantOp>(
2801 insertOp, seqTyAttr, denseAttr);
2802 }
2803 }
2804 }
2805 rewriter.eraseOp(global);
2806 return mlir::success();
2807 }
2808
2809 bool isFullRange(mlir::DenseIntElementsAttr indexes,
2810 fir::SequenceType seqTy) const {
2811 auto extents = seqTy.getShape();
2812 if (indexes.size() / 2 != static_cast<int64_t>(extents.size()))
2813 return false;
2814 auto cur_index = indexes.value_begin<int64_t>();
2815 for (unsigned i = 0; i < indexes.size(); i += 2) {
2816 if (*(cur_index++) != 0)
2817 return false;
2818 if (*(cur_index++) != extents[i / 2] - 1)
2819 return false;
2820 }
2821 return true;
2822 }
2823
2824 // TODO: String comparaison should be avoided. Replace linkName with an
2825 // enumeration.
2826 mlir::LLVM::Linkage
2827 convertLinkage(std::optional<llvm::StringRef> optLinkage) const {
2828 if (optLinkage) {
2829 auto name = *optLinkage;
2830 if (name == "internal")
2831 return mlir::LLVM::Linkage::Internal;
2832 if (name == "linkonce")
2833 return mlir::LLVM::Linkage::Linkonce;
2834 if (name == "linkonce_odr")
2835 return mlir::LLVM::Linkage::LinkonceODR;
2836 if (name == "common")
2837 return mlir::LLVM::Linkage::Common;
2838 if (name == "weak")
2839 return mlir::LLVM::Linkage::Weak;
2840 }
2841 return mlir::LLVM::Linkage::External;
2842 }
2843
2844 private:
2845 static void addComdat(mlir::LLVM::GlobalOp &global,
2846 mlir::ConversionPatternRewriter &rewriter,
2847 mlir::ModuleOp &module) {
2848 const char *comdatName = "__llvm_comdat";
2849 mlir::LLVM::ComdatOp comdatOp =
2850 module.lookupSymbol<mlir::LLVM::ComdatOp>(comdatName);
2851 if (!comdatOp) {
2852 comdatOp =
2853 rewriter.create<mlir::LLVM::ComdatOp>(module.getLoc(), comdatName);
2854 }
2855 mlir::OpBuilder::InsertionGuard guard(rewriter);
2856 rewriter.setInsertionPointToEnd(&comdatOp.getBody().back());
2857 auto selectorOp = rewriter.create<mlir::LLVM::ComdatSelectorOp>(
2858 comdatOp.getLoc(), global.getSymName(),
2859 mlir::LLVM::comdat::Comdat::Any);
2860 global.setComdatAttr(mlir::SymbolRefAttr::get(
2861 rewriter.getContext(), comdatName,
2862 mlir::FlatSymbolRefAttr::get(selectorOp.getSymNameAttr())));
2863 }
2864 };
2865
2866 /// `fir.load` --> `llvm.load`
2867 struct LoadOpConversion : public fir::FIROpConversion<fir::LoadOp> {
2868 using FIROpConversion::FIROpConversion;
2869
2870 llvm::LogicalResult
2871 matchAndRewrite(fir::LoadOp load, OpAdaptor adaptor,
2872 mlir::ConversionPatternRewriter &rewriter) const override {
2873 mlir::Type llvmLoadTy = convertObjectType(load.getType());
2874 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(load.getType())) {
2875 // fir.box is a special case because it is considered as an ssa values in
2876 // fir, but it is lowered as a pointer to a descriptor. So
2877 // fir.ref<fir.box> and fir.box end up being the same llvm types and
2878 // loading a fir.ref<fir.box> is implemented as taking a snapshot of the
2879 // descriptor value into a new descriptor temp.
2880 auto inputBoxStorage = adaptor.getOperands()[0];
2881 mlir::Location loc = load.getLoc();
2882 auto newBoxStorage =
2883 genAllocaAndAddrCastWithType(loc, llvmLoadTy, defaultAlign, rewriter);
2884 // TODO: always generate llvm.memcpy, LLVM is better at optimizing it than
2885 // aggregate loads + stores.
2886 if (boxTy.isAssumedRank()) {
2887
2888 TypePair boxTypePair{boxTy, llvmLoadTy};
2889 mlir::Value boxSize =
2890 computeBoxSize(loc, boxTypePair, inputBoxStorage, rewriter);
2891 auto memcpy = rewriter.create<mlir::LLVM::MemcpyOp>(
2892 loc, newBoxStorage, inputBoxStorage, boxSize, /*isVolatile=*/false);
2893 if (std::optional<mlir::ArrayAttr> optionalTag = load.getTbaa())
2894 memcpy.setTBAATags(*optionalTag);
2895 else
2896 attachTBAATag(memcpy, boxTy, boxTy, nullptr);
2897 } else {
2898 auto boxValue = rewriter.create<mlir::LLVM::LoadOp>(loc, llvmLoadTy,
2899 inputBoxStorage);
2900 if (std::optional<mlir::ArrayAttr> optionalTag = load.getTbaa())
2901 boxValue.setTBAATags(*optionalTag);
2902 else
2903 attachTBAATag(boxValue, boxTy, boxTy, nullptr);
2904 auto storeOp =
2905 rewriter.create<mlir::LLVM::StoreOp>(loc, boxValue, newBoxStorage);
2906 attachTBAATag(storeOp, boxTy, boxTy, nullptr);
2907 }
2908 rewriter.replaceOp(load, newBoxStorage);
2909 } else {
2910 auto loadOp = rewriter.create<mlir::LLVM::LoadOp>(
2911 load.getLoc(), llvmLoadTy, adaptor.getOperands(), load->getAttrs());
2912 if (std::optional<mlir::ArrayAttr> optionalTag = load.getTbaa())
2913 loadOp.setTBAATags(*optionalTag);
2914 else
2915 attachTBAATag(loadOp, load.getType(), load.getType(), nullptr);
2916 rewriter.replaceOp(load, loadOp.getResult());
2917 }
2918 return mlir::success();
2919 }
2920 };
2921
2922 /// Lower `fir.no_reassoc` to LLVM IR dialect.
2923 /// TODO: how do we want to enforce this in LLVM-IR? Can we manipulate the fast
2924 /// math flags?
2925 struct NoReassocOpConversion : public fir::FIROpConversion<fir::NoReassocOp> {
2926 using FIROpConversion::FIROpConversion;
2927
2928 llvm::LogicalResult
2929 matchAndRewrite(fir::NoReassocOp noreassoc, OpAdaptor adaptor,
2930 mlir::ConversionPatternRewriter &rewriter) const override {
2931 rewriter.replaceOp(noreassoc, adaptor.getOperands()[0]);
2932 return mlir::success();
2933 }
2934 };
2935
2936 static void genCondBrOp(mlir::Location loc, mlir::Value cmp, mlir::Block *dest,
2937 std::optional<mlir::ValueRange> destOps,
2938 mlir::ConversionPatternRewriter &rewriter,
2939 mlir::Block *newBlock) {
2940 if (destOps)
2941 rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, *destOps, newBlock,
2942 mlir::ValueRange());
2943 else
2944 rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, newBlock);
2945 }
2946
2947 template <typename A, typename B>
2948 static void genBrOp(A caseOp, mlir::Block *dest, std::optional<B> destOps,
2949 mlir::ConversionPatternRewriter &rewriter) {
2950 if (destOps)
2951 rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, *destOps, dest);
2952 else
2953 rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, std::nullopt, dest);
2954 }
2955
2956 static void genCaseLadderStep(mlir::Location loc, mlir::Value cmp,
2957 mlir::Block *dest,
2958 std::optional<mlir::ValueRange> destOps,
2959 mlir::ConversionPatternRewriter &rewriter) {
2960 auto *thisBlock = rewriter.getInsertionBlock();
2961 auto *newBlock = createBlock(rewriter, dest);
2962 rewriter.setInsertionPointToEnd(thisBlock);
2963 genCondBrOp(loc, cmp, dest, destOps, rewriter, newBlock);
2964 rewriter.setInsertionPointToEnd(newBlock);
2965 }
2966
2967 /// Conversion of `fir.select_case`
2968 ///
2969 /// The `fir.select_case` operation is converted to a if-then-else ladder.
2970 /// Depending on the case condition type, one or several comparison and
2971 /// conditional branching can be generated.
2972 ///
2973 /// A point value case such as `case(4)`, a lower bound case such as
2974 /// `case(5:)` or an upper bound case such as `case(:3)` are converted to a
2975 /// simple comparison between the selector value and the constant value in the
2976 /// case. The block associated with the case condition is then executed if
2977 /// the comparison succeed otherwise it branch to the next block with the
2978 /// comparison for the next case conditon.
2979 ///
2980 /// A closed interval case condition such as `case(7:10)` is converted with a
2981 /// first comparison and conditional branching for the lower bound. If
2982 /// successful, it branch to a second block with the comparison for the
2983 /// upper bound in the same case condition.
2984 ///
2985 /// TODO: lowering of CHARACTER type cases is not handled yet.
2986 struct SelectCaseOpConversion : public fir::FIROpConversion<fir::SelectCaseOp> {
2987 using FIROpConversion::FIROpConversion;
2988
2989 llvm::LogicalResult
2990 matchAndRewrite(fir::SelectCaseOp caseOp, OpAdaptor adaptor,
2991 mlir::ConversionPatternRewriter &rewriter) const override {
2992 unsigned conds = caseOp.getNumConditions();
2993 llvm::ArrayRef<mlir::Attribute> cases = caseOp.getCases().getValue();
2994 // Type can be CHARACTER, INTEGER, or LOGICAL (C1145)
2995 auto ty = caseOp.getSelector().getType();
2996 if (mlir::isa<fir::CharacterType>(ty)) {
2997 TODO(caseOp.getLoc(), "fir.select_case codegen with character type");
2998 return mlir::failure();
2999 }
3000 mlir::Value selector = caseOp.getSelector(adaptor.getOperands());
3001 auto loc = caseOp.getLoc();
3002 for (unsigned t = 0; t != conds; ++t) {
3003 mlir::Block *dest = caseOp.getSuccessor(t);
3004 std::optional<mlir::ValueRange> destOps =
3005 caseOp.getSuccessorOperands(adaptor.getOperands(), t);
3006 std::optional<mlir::ValueRange> cmpOps =
3007 *caseOp.getCompareOperands(adaptor.getOperands(), t);
3008 mlir::Attribute attr = cases[t];
3009 assert(mlir::isa<mlir::UnitAttr>(attr) || cmpOps.has_value());
3010 if (mlir::isa<fir::PointIntervalAttr>(attr)) {
3011 auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
3012 loc, mlir::LLVM::ICmpPredicate::eq, selector, cmpOps->front());
3013 genCaseLadderStep(loc, cmp, dest, destOps, rewriter);
3014 continue;
3015 }
3016 if (mlir::isa<fir::LowerBoundAttr>(attr)) {
3017 auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
3018 loc, mlir::LLVM::ICmpPredicate::sle, cmpOps->front(), selector);
3019 genCaseLadderStep(loc, cmp, dest, destOps, rewriter);
3020 continue;
3021 }
3022 if (mlir::isa<fir::UpperBoundAttr>(attr)) {
3023 auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
3024 loc, mlir::LLVM::ICmpPredicate::sle, selector, cmpOps->front());
3025 genCaseLadderStep(loc, cmp, dest, destOps, rewriter);
3026 continue;
3027 }
3028 if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
3029 mlir::Value caseArg0 = *cmpOps->begin();
3030 auto cmp0 = rewriter.create<mlir::LLVM::ICmpOp>(
3031 loc, mlir::LLVM::ICmpPredicate::sle, caseArg0, selector);
3032 auto *thisBlock = rewriter.getInsertionBlock();
3033 auto *newBlock1 = createBlock(rewriter, dest);
3034 auto *newBlock2 = createBlock(rewriter, dest);
3035 rewriter.setInsertionPointToEnd(thisBlock);
3036 rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp0, newBlock1, newBlock2);
3037 rewriter.setInsertionPointToEnd(newBlock1);
3038 mlir::Value caseArg1 = *(cmpOps->begin() + 1);
3039 auto cmp1 = rewriter.create<mlir::LLVM::ICmpOp>(
3040 loc, mlir::LLVM::ICmpPredicate::sle, selector, caseArg1);
3041 genCondBrOp(loc, cmp1, dest, destOps, rewriter, newBlock2);
3042 rewriter.setInsertionPointToEnd(newBlock2);
3043 continue;
3044 }
3045 assert(mlir::isa<mlir::UnitAttr>(attr));
3046 assert((t + 1 == conds) && "unit must be last");
3047 genBrOp(caseOp, dest, destOps, rewriter);
3048 }
3049 return mlir::success();
3050 }
3051 };
3052
3053 template <typename OP>
3054 static void selectMatchAndRewrite(const fir::LLVMTypeConverter &lowering,
3055 OP select, typename OP::Adaptor adaptor,
3056 mlir::ConversionPatternRewriter &rewriter) {
3057 unsigned conds = select.getNumConditions();
3058 auto cases = select.getCases().getValue();
3059 mlir::Value selector = adaptor.getSelector();
3060 auto loc = select.getLoc();
3061 assert(conds > 0 && "select must have cases");
3062
3063 llvm::SmallVector<mlir::Block *> destinations;
3064 llvm::SmallVector<mlir::ValueRange> destinationsOperands;
3065 mlir::Block *defaultDestination;
3066 mlir::ValueRange defaultOperands;
3067 llvm::SmallVector<int32_t> caseValues;
3068
3069 for (unsigned t = 0; t != conds; ++t) {
3070 mlir::Block *dest = select.getSuccessor(t);
3071 auto destOps = select.getSuccessorOperands(adaptor.getOperands(), t);
3072 const mlir::Attribute &attr = cases[t];
3073 if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr)) {
3074 destinations.push_back(dest);
3075 destinationsOperands.push_back(destOps ? *destOps : mlir::ValueRange{});
3076 caseValues.push_back(intAttr.getInt());
3077 continue;
3078 }
3079 assert(mlir::dyn_cast_or_null<mlir::UnitAttr>(attr));
3080 assert((t + 1 == conds) && "unit must be last");
3081 defaultDestination = dest;
3082 defaultOperands = destOps ? *destOps : mlir::ValueRange{};
3083 }
3084
3085 // LLVM::SwitchOp takes a i32 type for the selector.
3086 if (select.getSelector().getType() != rewriter.getI32Type())
3087 selector = rewriter.create<mlir::LLVM::TruncOp>(loc, rewriter.getI32Type(),
3088 selector);
3089
3090 rewriter.replaceOpWithNewOp<mlir::LLVM::SwitchOp>(
3091 select, selector,
3092 /*defaultDestination=*/defaultDestination,
3093 /*defaultOperands=*/defaultOperands,
3094 /*caseValues=*/caseValues,
3095 /*caseDestinations=*/destinations,
3096 /*caseOperands=*/destinationsOperands,
3097 /*branchWeights=*/llvm::ArrayRef<std::int32_t>());
3098 }
3099
3100 /// conversion of fir::SelectOp to an if-then-else ladder
3101 struct SelectOpConversion : public fir::FIROpConversion<fir::SelectOp> {
3102 using FIROpConversion::FIROpConversion;
3103
3104 llvm::LogicalResult
3105 matchAndRewrite(fir::SelectOp op, OpAdaptor adaptor,
3106 mlir::ConversionPatternRewriter &rewriter) const override {
3107 selectMatchAndRewrite<fir::SelectOp>(lowerTy(), op, adaptor, rewriter);
3108 return mlir::success();
3109 }
3110 };
3111
3112 /// conversion of fir::SelectRankOp to an if-then-else ladder
3113 struct SelectRankOpConversion : public fir::FIROpConversion<fir::SelectRankOp> {
3114 using FIROpConversion::FIROpConversion;
3115
3116 llvm::LogicalResult
3117 matchAndRewrite(fir::SelectRankOp op, OpAdaptor adaptor,
3118 mlir::ConversionPatternRewriter &rewriter) const override {
3119 selectMatchAndRewrite<fir::SelectRankOp>(lowerTy(), op, adaptor, rewriter);
3120 return mlir::success();
3121 }
3122 };
3123
3124 /// Lower `fir.select_type` to LLVM IR dialect.
3125 struct SelectTypeOpConversion : public fir::FIROpConversion<fir::SelectTypeOp> {
3126 using FIROpConversion::FIROpConversion;
3127
3128 llvm::LogicalResult
3129 matchAndRewrite(fir::SelectTypeOp select, OpAdaptor adaptor,
3130 mlir::ConversionPatternRewriter &rewriter) const override {
3131 mlir::emitError(select.getLoc(),
3132 "fir.select_type should have already been converted");
3133 return mlir::failure();
3134 }
3135 };
3136
3137 /// `fir.store` --> `llvm.store`
3138 struct StoreOpConversion : public fir::FIROpConversion<fir::StoreOp> {
3139 using FIROpConversion::FIROpConversion;
3140
3141 llvm::LogicalResult
3142 matchAndRewrite(fir::StoreOp store, OpAdaptor adaptor,
3143 mlir::ConversionPatternRewriter &rewriter) const override {
3144 mlir::Location loc = store.getLoc();
3145 mlir::Type storeTy = store.getValue().getType();
3146 mlir::Value llvmValue = adaptor.getValue();
3147 mlir::Value llvmMemref = adaptor.getMemref();
3148 mlir::LLVM::AliasAnalysisOpInterface newOp;
3149 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(storeTy)) {
3150 mlir::Type llvmBoxTy = lowerTy().convertBoxTypeAsStruct(boxTy);
3151 // fir.box value is actually in memory, load it first before storing it,
3152 // or do a memcopy for assumed-rank descriptors.
3153 if (boxTy.isAssumedRank()) {
3154 TypePair boxTypePair{boxTy, llvmBoxTy};
3155 mlir::Value boxSize =
3156 computeBoxSize(loc, boxTypePair, llvmValue, rewriter);
3157 newOp = rewriter.create<mlir::LLVM::MemcpyOp>(
3158 loc, llvmMemref, llvmValue, boxSize, /*isVolatile=*/false);
3159 } else {
3160 auto val =
3161 rewriter.create<mlir::LLVM::LoadOp>(loc, llvmBoxTy, llvmValue);
3162 attachTBAATag(val, boxTy, boxTy, nullptr);
3163 newOp = rewriter.create<mlir::LLVM::StoreOp>(loc, val, llvmMemref);
3164 }
3165 } else {
3166 newOp = rewriter.create<mlir::LLVM::StoreOp>(loc, llvmValue, llvmMemref);
3167 }
3168 if (std::optional<mlir::ArrayAttr> optionalTag = store.getTbaa())
3169 newOp.setTBAATags(*optionalTag);
3170 else
3171 attachTBAATag(newOp, storeTy, storeTy, nullptr);
3172 rewriter.eraseOp(store);
3173 return mlir::success();
3174 }
3175 };
3176
3177 namespace {
3178
3179 /// Convert `fir.unboxchar` into two `llvm.extractvalue` instructions. One for
3180 /// the character buffer and one for the buffer length.
3181 struct UnboxCharOpConversion : public fir::FIROpConversion<fir::UnboxCharOp> {
3182 using FIROpConversion::FIROpConversion;
3183
3184 llvm::LogicalResult
3185 matchAndRewrite(fir::UnboxCharOp unboxchar, OpAdaptor adaptor,
3186 mlir::ConversionPatternRewriter &rewriter) const override {
3187 mlir::Type lenTy = convertType(unboxchar.getType(1));
3188 mlir::Value tuple = adaptor.getOperands()[0];
3189
3190 mlir::Location loc = unboxchar.getLoc();
3191 mlir::Value ptrToBuffer =
3192 rewriter.create<mlir::LLVM::ExtractValueOp>(loc, tuple, 0);
3193
3194 auto len = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, tuple, 1);
3195 mlir::Value lenAfterCast = integerCast(loc, rewriter, lenTy, len);
3196
3197 rewriter.replaceOp(unboxchar,
3198 llvm::ArrayRef<mlir::Value>{ptrToBuffer, lenAfterCast});
3199 return mlir::success();
3200 }
3201 };
3202
3203 /// Lower `fir.unboxproc` operation. Unbox a procedure box value, yielding its
3204 /// components.
3205 /// TODO: Part of supporting Fortran 2003 procedure pointers.
3206 struct UnboxProcOpConversion : public fir::FIROpConversion<fir::UnboxProcOp> {
3207 using FIROpConversion::FIROpConversion;
3208
3209 llvm::LogicalResult
3210 matchAndRewrite(fir::UnboxProcOp unboxproc, OpAdaptor adaptor,
3211 mlir::ConversionPatternRewriter &rewriter) const override {
3212 TODO(unboxproc.getLoc(), "fir.unboxproc codegen");
3213 return mlir::failure();
3214 }
3215 };
3216
3217 /// convert to LLVM IR dialect `undef`
3218 struct UndefOpConversion : public fir::FIROpConversion<fir::UndefOp> {
3219 using FIROpConversion::FIROpConversion;
3220
3221 llvm::LogicalResult
3222 matchAndRewrite(fir::UndefOp undef, OpAdaptor,
3223 mlir::ConversionPatternRewriter &rewriter) const override {
3224 rewriter.replaceOpWithNewOp<mlir::LLVM::UndefOp>(
3225 undef, convertType(undef.getType()));
3226 return mlir::success();
3227 }
3228 };
3229
3230 struct ZeroOpConversion : public fir::FIROpConversion<fir::ZeroOp> {
3231 using FIROpConversion::FIROpConversion;
3232
3233 llvm::LogicalResult
3234 matchAndRewrite(fir::ZeroOp zero, OpAdaptor,
3235 mlir::ConversionPatternRewriter &rewriter) const override {
3236 mlir::Type ty = convertType(zero.getType());
3237 rewriter.replaceOpWithNewOp<mlir::LLVM::ZeroOp>(zero, ty);
3238 return mlir::success();
3239 }
3240 };
3241
3242 /// `fir.unreachable` --> `llvm.unreachable`
3243 struct UnreachableOpConversion
3244 : public fir::FIROpConversion<fir::UnreachableOp> {
3245 using FIROpConversion::FIROpConversion;
3246
3247 llvm::LogicalResult
3248 matchAndRewrite(fir::UnreachableOp unreach, OpAdaptor adaptor,
3249 mlir::ConversionPatternRewriter &rewriter) const override {
3250 rewriter.replaceOpWithNewOp<mlir::LLVM::UnreachableOp>(unreach);
3251 return mlir::success();
3252 }
3253 };
3254
3255 /// `fir.is_present` -->
3256 /// ```
3257 /// %0 = llvm.mlir.constant(0 : i64)
3258 /// %1 = llvm.ptrtoint %0
3259 /// %2 = llvm.icmp "ne" %1, %0 : i64
3260 /// ```
3261 struct IsPresentOpConversion : public fir::FIROpConversion<fir::IsPresentOp> {
3262 using FIROpConversion::FIROpConversion;
3263
3264 llvm::LogicalResult
3265 matchAndRewrite(fir::IsPresentOp isPresent, OpAdaptor adaptor,
3266 mlir::ConversionPatternRewriter &rewriter) const override {
3267 mlir::Type idxTy = lowerTy().indexType();
3268 mlir::Location loc = isPresent.getLoc();
3269 auto ptr = adaptor.getOperands()[0];
3270
3271 if (mlir::isa<fir::BoxCharType>(isPresent.getVal().getType())) {
3272 [[maybe_unused]] auto structTy =
3273 mlir::cast<mlir::LLVM::LLVMStructType>(ptr.getType());
3274 assert(!structTy.isOpaque() && !structTy.getBody().empty());
3275
3276 ptr = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, ptr, 0);
3277 }
3278 mlir::LLVM::ConstantOp c0 =
3279 genConstantIndex(isPresent.getLoc(), idxTy, rewriter, 0);
3280 auto addr = rewriter.create<mlir::LLVM::PtrToIntOp>(loc, idxTy, ptr);
3281 rewriter.replaceOpWithNewOp<mlir::LLVM::ICmpOp>(
3282 isPresent, mlir::LLVM::ICmpPredicate::ne, addr, c0);
3283
3284 return mlir::success();
3285 }
3286 };
3287
3288 /// Create value signaling an absent optional argument in a call, e.g.
3289 /// `fir.absent !fir.ref<i64>` --> `llvm.mlir.zero : !llvm.ptr<i64>`
3290 struct AbsentOpConversion : public fir::FIROpConversion<fir::AbsentOp> {
3291 using FIROpConversion::FIROpConversion;
3292
3293 llvm::LogicalResult
3294 matchAndRewrite(fir::AbsentOp absent, OpAdaptor,
3295 mlir::ConversionPatternRewriter &rewriter) const override {
3296 mlir::Type ty = convertType(absent.getType());
3297 mlir::Location loc = absent.getLoc();
3298
3299 if (mlir::isa<fir::BoxCharType>(absent.getType())) {
3300 auto structTy = mlir::cast<mlir::LLVM::LLVMStructType>(ty);
3301 assert(!structTy.isOpaque() && !structTy.getBody().empty());
3302 auto undefStruct = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
3303 auto nullField =
3304 rewriter.create<mlir::LLVM::ZeroOp>(loc, structTy.getBody()[0]);
3305 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(
3306 absent, undefStruct, nullField, 0);
3307 } else {
3308 rewriter.replaceOpWithNewOp<mlir::LLVM::ZeroOp>(absent, ty);
3309 }
3310 return mlir::success();
3311 }
3312 };
3313
3314 //
3315 // Primitive operations on Complex types
3316 //
3317
3318 template <typename OPTY>
3319 static inline mlir::LLVM::FastmathFlagsAttr getLLVMFMFAttr(OPTY op) {
3320 return mlir::LLVM::FastmathFlagsAttr::get(
3321 op.getContext(),
3322 mlir::arith::convertArithFastMathFlagsToLLVM(op.getFastmath()));
3323 }
3324
3325 /// Generate inline code for complex addition/subtraction
3326 template <typename LLVMOP, typename OPTY>
3327 static mlir::LLVM::InsertValueOp
3328 complexSum(OPTY sumop, mlir::ValueRange opnds,
3329 mlir::ConversionPatternRewriter &rewriter,
3330 const fir::LLVMTypeConverter &lowering) {
3331 mlir::LLVM::FastmathFlagsAttr fmf = getLLVMFMFAttr(sumop);
3332 mlir::Value a = opnds[0];
3333 mlir::Value b = opnds[1];
3334 auto loc = sumop.getLoc();
3335 mlir::Type eleTy = lowering.convertType(getComplexEleTy(sumop.getType()));
3336 mlir::Type ty = lowering.convertType(sumop.getType());
3337 auto x0 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, a, 0);
3338 auto y0 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, a, 1);
3339 auto x1 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, b, 0);
3340 auto y1 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, b, 1);
3341 auto rx = rewriter.create<LLVMOP>(loc, eleTy, x0, x1, fmf);
3342 auto ry = rewriter.create<LLVMOP>(loc, eleTy, y0, y1, fmf);
3343 auto r0 = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
3344 auto r1 = rewriter.create<mlir::LLVM::InsertValueOp>(loc, r0, rx, 0);
3345 return rewriter.create<mlir::LLVM::InsertValueOp>(loc, r1, ry, 1);
3346 }
3347 } // namespace
3348
3349 namespace {
3350 struct AddcOpConversion : public fir::FIROpConversion<fir::AddcOp> {
3351 using FIROpConversion::FIROpConversion;
3352
3353 llvm::LogicalResult
3354 matchAndRewrite(fir::AddcOp addc, OpAdaptor adaptor,
3355 mlir::ConversionPatternRewriter &rewriter) const override {
3356 // given: (x + iy) + (x' + iy')
3357 // result: (x + x') + i(y + y')
3358 auto r = complexSum<mlir::LLVM::FAddOp>(addc, adaptor.getOperands(),
3359 rewriter, lowerTy());
3360 rewriter.replaceOp(addc, r.getResult());
3361 return mlir::success();
3362 }
3363 };
3364
3365 struct SubcOpConversion : public fir::FIROpConversion<fir::SubcOp> {
3366 using FIROpConversion::FIROpConversion;
3367
3368 llvm::LogicalResult
3369 matchAndRewrite(fir::SubcOp subc, OpAdaptor adaptor,
3370 mlir::ConversionPatternRewriter &rewriter) const override {
3371 // given: (x + iy) - (x' + iy')
3372 // result: (x - x') + i(y - y')
3373 auto r = complexSum<mlir::LLVM::FSubOp>(subc, adaptor.getOperands(),
3374 rewriter, lowerTy());
3375 rewriter.replaceOp(subc, r.getResult());
3376 return mlir::success();
3377 }
3378 };
3379
3380 /// Inlined complex multiply
3381 struct MulcOpConversion : public fir::FIROpConversion<fir::MulcOp> {
3382 using FIROpConversion::FIROpConversion;
3383
3384 llvm::LogicalResult
3385 matchAndRewrite(fir::MulcOp mulc, OpAdaptor adaptor,
3386 mlir::ConversionPatternRewriter &rewriter) const override {
3387 // TODO: Can we use a call to __muldc3 ?
3388 // given: (x + iy) * (x' + iy')
3389 // result: (xx'-yy')+i(xy'+yx')
3390 mlir::LLVM::FastmathFlagsAttr fmf = getLLVMFMFAttr(mulc);
3391 mlir::Value a = adaptor.getOperands()[0];
3392 mlir::Value b = adaptor.getOperands()[1];
3393 auto loc = mulc.getLoc();
3394 mlir::Type eleTy = convertType(getComplexEleTy(mulc.getType()));
3395 mlir::Type ty = convertType(mulc.getType());
3396 auto x0 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, a, 0);
3397 auto y0 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, a, 1);
3398 auto x1 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, b, 0);
3399 auto y1 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, b, 1);
3400 auto xx = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, x0, x1, fmf);
3401 auto yx = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, y0, x1, fmf);
3402 auto xy = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, x0, y1, fmf);
3403 auto ri = rewriter.create<mlir::LLVM::FAddOp>(loc, eleTy, xy, yx, fmf);
3404 auto yy = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, y0, y1, fmf);
3405 auto rr = rewriter.create<mlir::LLVM::FSubOp>(loc, eleTy, xx, yy, fmf);
3406 auto ra = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
3407 auto r1 = rewriter.create<mlir::LLVM::InsertValueOp>(loc, ra, rr, 0);
3408 auto r0 = rewriter.create<mlir::LLVM::InsertValueOp>(loc, r1, ri, 1);
3409 rewriter.replaceOp(mulc, r0.getResult());
3410 return mlir::success();
3411 }
3412 };
3413
3414 /// Inlined complex division
3415 struct DivcOpConversion : public fir::FIROpConversion<fir::DivcOp> {
3416 using FIROpConversion::FIROpConversion;
3417
3418 llvm::LogicalResult
3419 matchAndRewrite(fir::DivcOp divc, OpAdaptor adaptor,
3420 mlir::ConversionPatternRewriter &rewriter) const override {
3421 // TODO: Can we use a call to __divdc3 instead?
3422 // Just generate inline code for now.
3423 // given: (x + iy) / (x' + iy')
3424 // result: ((xx'+yy')/d) + i((yx'-xy')/d) where d = x'x' + y'y'
3425 mlir::LLVM::FastmathFlagsAttr fmf = getLLVMFMFAttr(divc);
3426 mlir::Value a = adaptor.getOperands()[0];
3427 mlir::Value b = adaptor.getOperands()[1];
3428 auto loc = divc.getLoc();
3429 mlir::Type eleTy = convertType(getComplexEleTy(divc.getType()));
3430 mlir::Type ty = convertType(divc.getType());
3431 auto x0 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, a, 0);
3432 auto y0 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, a, 1);
3433 auto x1 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, b, 0);
3434 auto y1 = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, b, 1);
3435 auto xx = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, x0, x1, fmf);
3436 auto x1x1 = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, x1, x1, fmf);
3437 auto yx = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, y0, x1, fmf);
3438 auto xy = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, x0, y1, fmf);
3439 auto yy = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, y0, y1, fmf);
3440 auto y1y1 = rewriter.create<mlir::LLVM::FMulOp>(loc, eleTy, y1, y1, fmf);
3441 auto d = rewriter.create<mlir::LLVM::FAddOp>(loc, eleTy, x1x1, y1y1, fmf);
3442 auto rrn = rewriter.create<mlir::LLVM::FAddOp>(loc, eleTy, xx, yy, fmf);
3443 auto rin = rewriter.create<mlir::LLVM::FSubOp>(loc, eleTy, yx, xy, fmf);
3444 auto rr = rewriter.create<mlir::LLVM::FDivOp>(loc, eleTy, rrn, d, fmf);
3445 auto ri = rewriter.create<mlir::LLVM::FDivOp>(loc, eleTy, rin, d, fmf);
3446 auto ra = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
3447 auto r1 = rewriter.create<mlir::LLVM::InsertValueOp>(loc, ra, rr, 0);
3448 auto r0 = rewriter.create<mlir::LLVM::InsertValueOp>(loc, r1, ri, 1);
3449 rewriter.replaceOp(divc, r0.getResult());
3450 return mlir::success();
3451 }
3452 };
3453
3454 /// Inlined complex negation
3455 struct NegcOpConversion : public fir::FIROpConversion<fir::NegcOp> {
3456 using FIROpConversion::FIROpConversion;
3457
3458 llvm::LogicalResult
3459 matchAndRewrite(fir::NegcOp neg, OpAdaptor adaptor,
3460 mlir::ConversionPatternRewriter &rewriter) const override {
3461 // given: -(x + iy)
3462 // result: -x - iy
3463 auto eleTy = convertType(getComplexEleTy(neg.getType()));
3464 auto loc = neg.getLoc();
3465 mlir::Value o0 = adaptor.getOperands()[0];
3466 auto rp = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, o0, 0);
3467 auto ip = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, o0, 1);
3468 auto nrp = rewriter.create<mlir::LLVM::FNegOp>(loc, eleTy, rp);
3469 auto nip = rewriter.create<mlir::LLVM::FNegOp>(loc, eleTy, ip);
3470 auto r = rewriter.create<mlir::LLVM::InsertValueOp>(loc, o0, nrp, 0);
3471 rewriter.replaceOpWithNewOp<mlir::LLVM::InsertValueOp>(neg, r, nip, 1);
3472 return mlir::success();
3473 }
3474 };
3475
3476 struct BoxOffsetOpConversion : public fir::FIROpConversion<fir::BoxOffsetOp> {
3477 using FIROpConversion::FIROpConversion;
3478
3479 llvm::LogicalResult
3480 matchAndRewrite(fir::BoxOffsetOp boxOffset, OpAdaptor adaptor,
3481 mlir::ConversionPatternRewriter &rewriter) const override {
3482
3483 mlir::Type pty = ::getLlvmPtrType(boxOffset.getContext());
3484 mlir::Type boxType = fir::unwrapRefType(boxOffset.getBoxRef().getType());
3485 mlir::Type llvmBoxTy =
3486 lowerTy().convertBoxTypeAsStruct(mlir::cast<fir::BaseBoxType>(boxType));
3487 int fieldId = boxOffset.getField() == fir::BoxFieldAttr::derived_type
3488 ? getTypeDescFieldId(boxType)
3489 : kAddrPosInBox;
3490 rewriter.replaceOpWithNewOp<mlir::LLVM::GEPOp>(
3491 boxOffset, pty, llvmBoxTy, adaptor.getBoxRef(),
3492 llvm::ArrayRef<mlir::LLVM::GEPArg>{0, fieldId});
3493 return mlir::success();
3494 }
3495 };
3496
3497 /// Conversion pattern for operation that must be dead. The information in these
3498 /// operations is used by other operation. At this point they should not have
3499 /// anymore uses.
3500 /// These operations are normally dead after the pre-codegen pass.
3501 template <typename FromOp>
3502 struct MustBeDeadConversion : public fir::FIROpConversion<FromOp> {
3503 explicit MustBeDeadConversion(const fir::LLVMTypeConverter &lowering,
3504 const fir::FIRToLLVMPassOptions &options)
3505 : fir::FIROpConversion<FromOp>(lowering, options) {}
3506 using OpAdaptor = typename FromOp::Adaptor;
3507
3508 llvm::LogicalResult
3509 matchAndRewrite(FromOp op, OpAdaptor adaptor,
3510 mlir::ConversionPatternRewriter &rewriter) const final {
3511 if (!op->getUses().empty())
3512 return rewriter.notifyMatchFailure(op, "op must be dead");
3513 rewriter.eraseOp(op);
3514 return mlir::success();
3515 }
3516 };
3517
3518 struct ShapeOpConversion : public MustBeDeadConversion<fir::ShapeOp> {
3519 using MustBeDeadConversion::MustBeDeadConversion;
3520 };
3521
3522 struct ShapeShiftOpConversion : public MustBeDeadConversion<fir::ShapeShiftOp> {
3523 using MustBeDeadConversion::MustBeDeadConversion;
3524 };
3525
3526 struct ShiftOpConversion : public MustBeDeadConversion<fir::ShiftOp> {
3527 using MustBeDeadConversion::MustBeDeadConversion;
3528 };
3529
3530 struct SliceOpConversion : public MustBeDeadConversion<fir::SliceOp> {
3531 using MustBeDeadConversion::MustBeDeadConversion;
3532 };
3533
3534 } // namespace
3535
3536 namespace {
3537 class RenameMSVCLibmCallees
3538 : public mlir::OpRewritePattern<mlir::LLVM::CallOp> {
3539 public:
3540 using OpRewritePattern::OpRewritePattern;
3541
3542 llvm::LogicalResult
3543 matchAndRewrite(mlir::LLVM::CallOp op,
3544 mlir::PatternRewriter &rewriter) const override {
3545 rewriter.startOpModification(op);
3546 auto callee = op.getCallee();
3547 if (callee)
3548 if (*callee == "hypotf")
3549 op.setCalleeAttr(mlir::SymbolRefAttr::get(op.getContext(), "_hypotf"));
3550
3551 rewriter.finalizeOpModification(op);
3552 return mlir::success();
3553 }
3554 };
3555
3556 class RenameMSVCLibmFuncs
3557 : public mlir::OpRewritePattern<mlir::LLVM::LLVMFuncOp> {
3558 public:
3559 using OpRewritePattern::OpRewritePattern;
3560
3561 llvm::LogicalResult
3562 matchAndRewrite(mlir::LLVM::LLVMFuncOp op,
3563 mlir::PatternRewriter &rewriter) const override {
3564 rewriter.startOpModification(op);
3565 if (op.getSymName() == "hypotf")
3566 op.setSymNameAttr(rewriter.getStringAttr("_hypotf"));
3567 rewriter.finalizeOpModification(op);
3568 return mlir::success();
3569 }
3570 };
3571 } // namespace
3572
3573 namespace {
3574 /// Convert FIR dialect to LLVM dialect
3575 ///
3576 /// This pass lowers all FIR dialect operations to LLVM IR dialect. An
3577 /// MLIR pass is used to lower residual Std dialect to LLVM IR dialect.
3578 class FIRToLLVMLowering
3579 : public fir::impl::FIRToLLVMLoweringBase<FIRToLLVMLowering> {
3580 public:
3581 FIRToLLVMLowering() = default;
3582 FIRToLLVMLowering(fir::FIRToLLVMPassOptions options) : options{options} {}
3583 mlir::ModuleOp getModule() { return getOperation(); }
3584
3585 void runOnOperation() override final {
3586 auto mod = getModule();
3587 if (!forcedTargetTriple.empty())
3588 fir::setTargetTriple(mod, forcedTargetTriple);
3589
3590 if (!forcedDataLayout.empty()) {
3591 llvm::DataLayout dl(forcedDataLayout);
3592 fir::support::setMLIRDataLayout(mod, dl);
3593 }
3594
3595 if (!forcedTargetCPU.empty())
3596 fir::setTargetCPU(mod, forcedTargetCPU);
3597
3598 if (!forcedTuneCPU.empty())
3599 fir::setTuneCPU(mod, forcedTuneCPU);
3600
3601 if (!forcedTargetFeatures.empty())
3602 fir::setTargetFeatures(mod, forcedTargetFeatures);
3603
3604 // Run dynamic pass pipeline for converting Math dialect
3605 // operations into other dialects (llvm, func, etc.).
3606 // Some conversions of Math operations cannot be done
3607 // by just using conversion patterns. This is true for
3608 // conversions that affect the ModuleOp, e.g. create new
3609 // function operations in it. We have to run such conversions
3610 // as passes here.
3611 mlir::OpPassManager mathConvertionPM("builtin.module");
3612
3613 // Convert math::FPowI operations to inline implementation
3614 // only if the exponent's width is greater than 32, otherwise,
3615 // it will be lowered to LLVM intrinsic operation by a later conversion.
3616 mlir::ConvertMathToFuncsOptions mathToFuncsOptions{};
3617 mathToFuncsOptions.minWidthOfFPowIExponent = 33;
3618 mathConvertionPM.addPass(
3619 mlir::createConvertMathToFuncs(mathToFuncsOptions));
3620 mathConvertionPM.addPass(mlir::createConvertComplexToStandardPass());
3621 // Convert Math dialect operations into LLVM dialect operations.
3622 // There is no way to prefer MathToLLVM patterns over MathToLibm
3623 // patterns (applied below), so we have to run MathToLLVM conversion here.
3624 mathConvertionPM.addNestedPass<mlir::func::FuncOp>(
3625 mlir::createConvertMathToLLVMPass());
3626 if (mlir::failed(runPipeline(mathConvertionPM, mod)))
3627 return signalPassFailure();
3628
3629 std::optional<mlir::DataLayout> dl =
3630 fir::support::getOrSetDataLayout(mod, /*allowDefaultLayout=*/true);
3631 if (!dl) {
3632 mlir::emitError(mod.getLoc(),
3633 "module operation must carry a data layout attribute "
3634 "to generate llvm IR from FIR");
3635 signalPassFailure();
3636 return;
3637 }
3638
3639 auto *context = getModule().getContext();
3640 fir::LLVMTypeConverter typeConverter{getModule(),
3641 options.applyTBAA || applyTBAA,
3642 options.forceUnifiedTBAATree, *dl};
3643 mlir::RewritePatternSet pattern(context);
3644 fir::populateFIRToLLVMConversionPatterns(typeConverter, pattern, options);
3645 mlir::populateFuncToLLVMConversionPatterns(typeConverter, pattern);
3646 mlir::populateOpenMPToLLVMConversionPatterns(typeConverter, pattern);
3647 mlir::arith::populateArithToLLVMConversionPatterns(typeConverter, pattern);
3648 mlir::cf::populateControlFlowToLLVMConversionPatterns(typeConverter,
3649 pattern);
3650 // Math operations that have not been converted yet must be converted
3651 // to Libm.
3652 mlir::populateMathToLibmConversionPatterns(pattern);
3653 mlir::populateComplexToLLVMConversionPatterns(typeConverter, pattern);
3654 mlir::populateVectorToLLVMConversionPatterns(typeConverter, pattern);
3655
3656 // Flang specific overloads for OpenMP operations, to allow for special
3657 // handling of things like Box types.
3658 fir::populateOpenMPFIRToLLVMConversionPatterns(typeConverter, pattern);
3659
3660 mlir::ConversionTarget target{*context};
3661 target.addLegalDialect<mlir::LLVM::LLVMDialect>();
3662 // The OpenMP dialect is legal for Operations without regions, for those
3663 // which contains regions it is legal if the region contains only the
3664 // LLVM dialect. Add OpenMP dialect as a legal dialect for conversion and
3665 // legalize conversion of OpenMP operations without regions.
3666 mlir::configureOpenMPToLLVMConversionLegality(target, typeConverter);
3667 target.addLegalDialect<mlir::omp::OpenMPDialect>();
3668 target.addLegalDialect<mlir::acc::OpenACCDialect>();
3669
3670 // required NOPs for applying a full conversion
3671 target.addLegalOp<mlir::ModuleOp>();
3672
3673 // If we're on Windows, we might need to rename some libm calls.
3674 bool isMSVC = fir::getTargetTriple(mod).isOSMSVCRT();
3675 if (isMSVC) {
3676 pattern.insert<RenameMSVCLibmCallees, RenameMSVCLibmFuncs>(context);
3677
3678 target.addDynamicallyLegalOp<mlir::LLVM::CallOp>(
3679 [](mlir::LLVM::CallOp op) {
3680 auto callee = op.getCallee();
3681 if (!callee)
3682 return true;
3683 return *callee != "hypotf";
3684 });
3685 target.addDynamicallyLegalOp<mlir::LLVM::LLVMFuncOp>(
3686 [](mlir::LLVM::LLVMFuncOp op) {
3687 return op.getSymName() != "hypotf";
3688 });
3689 }
3690
3691 // apply the patterns
3692 if (mlir::failed(mlir::applyFullConversion(getModule(), target,
3693 std::move(pattern)))) {
3694 signalPassFailure();
3695 }
3696
3697 // Run pass to add comdats to functions that have weak linkage on relevant
3698 // platforms
3699 if (fir::getTargetTriple(mod).supportsCOMDAT()) {
3700 mlir::OpPassManager comdatPM("builtin.module");
3701 comdatPM.addPass(mlir::LLVM::createLLVMAddComdats());
3702 if (mlir::failed(runPipeline(comdatPM, mod)))
3703 return signalPassFailure();
3704 }
3705 }
3706
3707 private:
3708 fir::FIRToLLVMPassOptions options;
3709 };
3710
3711 /// Lower from LLVM IR dialect to proper LLVM-IR and dump the module
3712 struct LLVMIRLoweringPass
3713 : public mlir::PassWrapper<LLVMIRLoweringPass,
3714 mlir::OperationPass<mlir::ModuleOp>> {
3715 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LLVMIRLoweringPass)
3716
3717 LLVMIRLoweringPass(llvm::raw_ostream &output, fir::LLVMIRLoweringPrinter p)
3718 : output{output}, printer{p} {}
3719
3720 mlir::ModuleOp getModule() { return getOperation(); }
3721
3722 void runOnOperation() override final {
3723 auto *ctx = getModule().getContext();
3724 auto optName = getModule().getName();
3725 llvm::LLVMContext llvmCtx;
3726 if (auto llvmModule = mlir::translateModuleToLLVMIR(
3727 getModule(), llvmCtx, optName ? *optName : "FIRModule")) {
3728 printer(*llvmModule, output);
3729 return;
3730 }
3731
3732 mlir::emitError(mlir::UnknownLoc::get(ctx), "could not emit LLVM-IR\n");
3733 signalPassFailure();
3734 }
3735
3736 private:
3737 llvm::raw_ostream &output;
3738 fir::LLVMIRLoweringPrinter printer;
3739 };
3740
3741 } // namespace
3742
3743 std::unique_ptr<mlir::Pass> fir::createFIRToLLVMPass() {
3744 return std::make_unique<FIRToLLVMLowering>();
3745 }
3746
3747 std::unique_ptr<mlir::Pass>
3748 fir::createFIRToLLVMPass(fir::FIRToLLVMPassOptions options) {
3749 return std::make_unique<FIRToLLVMLowering>(options);
3750 }
3751
3752 std::unique_ptr<mlir::Pass>
3753 fir::createLLVMDialectToLLVMPass(llvm::raw_ostream &output,
3754 fir::LLVMIRLoweringPrinter printer) {
3755 return std::make_unique<LLVMIRLoweringPass>(output, printer);
3756 }
3757
3758 void fir::populateFIRToLLVMConversionPatterns(
3759 fir::LLVMTypeConverter &converter, mlir::RewritePatternSet &patterns,
3760 fir::FIRToLLVMPassOptions &options) {
3761 patterns.insert<
3762 AbsentOpConversion, AddcOpConversion, AddrOfOpConversion,
3763 AllocaOpConversion, AllocMemOpConversion, BoxAddrOpConversion,
3764 BoxCharLenOpConversion, BoxDimsOpConversion, BoxEleSizeOpConversion,
3765 BoxIsAllocOpConversion, BoxIsArrayOpConversion, BoxIsPtrOpConversion,
3766 BoxOffsetOpConversion, BoxProcHostOpConversion, BoxRankOpConversion,
3767 BoxTypeCodeOpConversion, BoxTypeDescOpConversion, CallOpConversion,
3768 CmpcOpConversion, ConstcOpConversion, ConvertOpConversion,
3769 CoordinateOpConversion, DTEntryOpConversion, DeclareOpConversion,
3770 DivcOpConversion, EmboxOpConversion, EmboxCharOpConversion,
3771 EmboxProcOpConversion, ExtractValueOpConversion, FieldIndexOpConversion,
3772 FirEndOpConversion, FreeMemOpConversion, GlobalLenOpConversion,
3773 GlobalOpConversion, InsertOnRangeOpConversion, IsPresentOpConversion,
3774 LenParamIndexOpConversion, LoadOpConversion, MulcOpConversion,
3775 NegcOpConversion, NoReassocOpConversion, SelectCaseOpConversion,
3776 SelectOpConversion, SelectRankOpConversion, SelectTypeOpConversion,
3777 ShapeOpConversion, ShapeShiftOpConversion, ShiftOpConversion,
3778 SliceOpConversion, StoreOpConversion, StringLitOpConversion,
3779 SubcOpConversion, TypeDescOpConversion, TypeInfoOpConversion,
3780 UnboxCharOpConversion, UnboxProcOpConversion, UndefOpConversion,
3781 UnreachableOpConversion, XArrayCoorOpConversion, XEmboxOpConversion,
3782 XReboxOpConversion, ZeroOpConversion>(converter, options);
3783
3784 // Patterns that are populated without a type converter do not trigger
3785 // target materializations for the operands of the root op.
3786 patterns.insert<HasValueOpConversion, InsertValueOpConversion>(
3787 patterns.getContext());
3788 }