Skip to content

Commit 24b62f2

Browse files
committed
[flang] Upstreaming intrinsic call lowering.
This module implements the lowering of Fortran intrinsics to the corresponding calls in support libraries (the Fortran runtime, math libraries, etc.) This revision is a tad larger because there are a large number of Fortran intrinsics and this adds lowering for a fair number of them. Differential revision: https://reviews.llvm.org/D83355
1 parent 15fa287 commit 24b62f2

9 files changed

Lines changed: 1595 additions & 104 deletions

File tree

‎flang/include/flang/Lower/CharacterExpr.h‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,19 @@ class CharacterExprHelper {
106106
/// Character lengths. TODO: move this to FirOpBuilder?
107107
mlir::Type getLengthType() { return builder.getIndexType(); }
108108

109+
/// Create an extended value from:
110+
/// - fir.boxchar<kind>
111+
/// - fir.ref<fir.array<len x fir.char<kind>>>
112+
/// - fir.array<len x fir.char<kind>>
113+
/// - fir.char<kind>
114+
/// - fir.ref<char<kind>>
115+
/// If the no length is passed, it is attempted to be extracted from \p
116+
/// character (or its type). This will crash if this is not possible.
117+
/// The returned value is a CharBoxValue if \p character is a scalar,
118+
/// otherwise it is a CharArrayBoxValue.
119+
fir::ExtendedValue toExtendedValue(mlir::Value character,
120+
mlir::Value len = {});
121+
109122
private:
110123
fir::CharBoxValue materializeValue(const fir::CharBoxValue &str);
111124
fir::CharBoxValue toDataLengthPair(mlir::Value character);

‎flang/include/flang/Lower/IntrinsicCall.h‎

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -27,39 +27,40 @@ namespace Fortran::lower {
2727

2828
/// Helper for building calls to intrinsic functions in the runtime support
2929
/// libraries.
30-
class IntrinsicCallOpsHelper {
31-
public:
32-
explicit IntrinsicCallOpsHelper(FirOpBuilder &builder, mlir::Location loc)
33-
: builder(builder), loc(loc) {}
34-
IntrinsicCallOpsHelper(const IntrinsicCallOpsHelper &) = delete;
3530

36-
/// Generate the FIR+MLIR operations for the generic intrinsic \p name
37-
/// with arguments \p args and expected result type \p resultType.
38-
/// Returned mlir::Value is the returned Fortran intrinsic value.
39-
fir::ExtendedValue genIntrinsicCall(llvm::StringRef name,
40-
mlir::Type resultType,
41-
llvm::ArrayRef<fir::ExtendedValue> args);
31+
/// Generate the FIR+MLIR operations for the generic intrinsic \p name
32+
/// with arguments \p args and expected result type \p resultType.
33+
/// Returned mlir::Value is the returned Fortran intrinsic value.
34+
fir::ExtendedValue genIntrinsicCall(FirOpBuilder &, mlir::Location,
35+
llvm::StringRef name, mlir::Type resultType,
36+
llvm::ArrayRef<fir::ExtendedValue> args);
4237

43-
//===--------------------------------------------------------------------===//
44-
// Direct access to intrinsics that may be used by lowering outside
45-
// of intrinsic call lowering.
46-
//===--------------------------------------------------------------------===//
38+
/// Get SymbolRefAttr of runtime (or wrapper function containing inlined
39+
// implementation) of an unrestricted intrinsic (defined by its signature
40+
// and generic name)
41+
mlir::SymbolRefAttr
42+
getUnrestrictedIntrinsicSymbolRefAttr(FirOpBuilder &, mlir::Location,
43+
llvm::StringRef name,
44+
mlir::FunctionType signature);
4745

48-
/// Generate maximum. There must be at least one argument and all arguments
49-
/// must have the same type.
50-
mlir::Value genMax(llvm::ArrayRef<mlir::Value> args);
46+
//===--------------------------------------------------------------------===//
47+
// Direct access to intrinsics that may be used by lowering outside
48+
// of intrinsic call lowering.
49+
//===--------------------------------------------------------------------===//
5150

52-
/// Generate minimum. Same constraints as genMax.
53-
mlir::Value genMin(llvm::ArrayRef<mlir::Value> args);
51+
/// Generate maximum. There must be at least one argument and all arguments
52+
/// must have the same type.
53+
mlir::Value genMax(FirOpBuilder &, mlir::Location,
54+
llvm::ArrayRef<mlir::Value> args);
5455

55-
/// Generate power function x**y with given the expected
56-
/// result type.
57-
mlir::Value genPow(mlir::Type resultType, mlir::Value x, mlir::Value y);
56+
/// Generate minimum. Same constraints as genMax.
57+
mlir::Value genMin(FirOpBuilder &, mlir::Location,
58+
llvm::ArrayRef<mlir::Value> args);
5859

59-
private:
60-
FirOpBuilder &builder;
61-
mlir::Location loc;
62-
};
60+
/// Generate power function x**y with given the expected
61+
/// result type.
62+
mlir::Value genPow(FirOpBuilder &, mlir::Location, mlir::Type resultType,
63+
mlir::Value x, mlir::Value y);
6364

6465
} // namespace Fortran::lower
6566

‎flang/include/flang/Lower/Mangler.h‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,32 @@
55
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66
//
77
//===----------------------------------------------------------------------===//
8+
//
9+
// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10+
//
11+
//===----------------------------------------------------------------------===//
812

9-
#ifndef FORTRAN_LOWER_MANGLER_H_
10-
#define FORTRAN_LOWER_MANGLER_H_
13+
#ifndef FORTRAN_LOWER_MANGLER_H
14+
#define FORTRAN_LOWER_MANGLER_H
1115

16+
#include "mlir/IR/StandardTypes.h"
17+
#include "llvm/ADT/StringRef.h"
1218
#include <string>
1319

1420
namespace fir {
1521
struct NameUniquer;
16-
}
1722

18-
namespace llvm {
19-
class StringRef;
20-
}
23+
/// Returns a name suitable to define mlir functions for Fortran intrinsic
24+
/// Procedure. These names are guaranteed to not conflict with user defined
25+
/// procedures. This is needed to implement Fortran generic intrinsics as
26+
/// several mlir functions specialized for the argument types.
27+
/// The result is guaranteed to be distinct for different mlir::FunctionType
28+
/// arguments. The mangling pattern is:
29+
/// fir.<generic name>.<result type>.<arg type>...
30+
/// e.g ACOS(COMPLEX(4)) is mangled as fir.acos.z4.z4
31+
std::string mangleIntrinsicProcedure(llvm::StringRef genericName,
32+
mlir::FunctionType);
33+
} // namespace fir
2134

2235
namespace Fortran {
2336
namespace common {
@@ -41,4 +54,4 @@ std::string demangleName(llvm::StringRef name);
4154
} // namespace lower
4255
} // namespace Fortran
4356

44-
#endif // FORTRAN_LOWER_MANGLER_H_
57+
#endif // FORTRAN_LOWER_MANGLER_H

‎flang/include/flang/Optimizer/Dialect/FIRType.h‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ class DimsType : public mlir::Type::TypeBase<DimsType, mlir::Type,
242242
static bool kindof(unsigned kind) { return kind == TypeKind::FIR_DIMS; }
243243

244244
/// returns -1 if the rank is unknown
245-
int getRank() const;
245+
unsigned getRank() const;
246246
};
247247

248248
/// The type of a field name. Implementations may defer the layout of a Fortran
@@ -437,6 +437,12 @@ inline bool isa_real(mlir::Type t) {
437437
return t.isa<fir::RealType>() || t.isa<mlir::FloatType>();
438438
}
439439

440+
/// Is `t` an integral type?
441+
inline bool isa_integer(mlir::Type t) {
442+
return t.isa<mlir::IndexType>() || t.isa<mlir::IntegerType>() ||
443+
t.isa<fir::IntType>();
444+
}
445+
440446
/// Is `t` a FIR or MLIR Complex type?
441447
inline bool isa_complex(mlir::Type t) {
442448
return t.isa<fir::CplxType>() || t.isa<mlir::ComplexType>();

‎flang/lib/Lower/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ add_flang_library(FortranLower
99
ConvertType.cpp
1010
DoLoopHelper.cpp
1111
FIRBuilder.cpp
12+
IntrinsicCall.cpp
1213
IO.cpp
1314
Mangler.cpp
1415
OpenMP.cpp

‎flang/lib/Lower/CharacterExpr.cpp‎

Lines changed: 80 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@ static fir::CharacterType getCharacterType(mlir::Type type) {
2121
return boxType.getEleTy();
2222
if (auto refType = type.dyn_cast<fir::ReferenceType>())
2323
type = refType.getEleTy();
24-
if (auto seqType = type.dyn_cast<fir::SequenceType>())
24+
if (auto seqType = type.dyn_cast<fir::SequenceType>()) {
25+
assert(seqType.getShape().size() == 1 && "rank must be 1");
2526
type = seqType.getEleTy();
27+
}
2628
if (auto charType = type.dyn_cast<fir::CharacterType>())
2729
return charType;
2830
llvm_unreachable("Invalid character value type");
@@ -65,38 +67,66 @@ fir::CharBoxValue Fortran::lower::CharacterExprHelper::materializeValue(
6567

6668
fir::CharBoxValue
6769
Fortran::lower::CharacterExprHelper::toDataLengthPair(mlir::Value character) {
70+
// TODO: get rid of toDataLengthPair when adding support for arrays
71+
auto charBox = toExtendedValue(character).getCharBox();
72+
assert(charBox && "Array unsupported in character lowering helper");
73+
return *charBox;
74+
}
75+
76+
fir::ExtendedValue
77+
Fortran::lower::CharacterExprHelper::toExtendedValue(mlir::Value character,
78+
mlir::Value len) {
6879
auto lenType = getLengthType();
6980
auto type = character.getType();
70-
if (auto boxCharType = type.dyn_cast<fir::BoxCharType>()) {
81+
auto base = character;
82+
mlir::Value resultLen = len;
83+
llvm::SmallVector<mlir::Value, 2> extents;
84+
85+
if (auto refType = type.dyn_cast<fir::ReferenceType>())
86+
type = refType.getEleTy();
87+
88+
if (auto arrayType = type.dyn_cast<fir::SequenceType>()) {
89+
type = arrayType.getEleTy();
90+
auto shape = arrayType.getShape();
91+
auto cstLen = shape[0];
92+
if (!resultLen && cstLen != fir::SequenceType::getUnknownExtent())
93+
resultLen = builder.createIntegerConstant(loc, lenType, cstLen);
94+
// FIXME: only allow `?` in last dimension ?
95+
auto typeExtents =
96+
llvm::ArrayRef<fir::SequenceType::Extent>{shape}.drop_front();
97+
auto indexType = builder.getIndexType();
98+
for (auto extent : typeExtents) {
99+
if (extent == fir::SequenceType::getUnknownExtent())
100+
break;
101+
extents.emplace_back(
102+
builder.createIntegerConstant(loc, indexType, extent));
103+
}
104+
// Last extent might be missing in case of assumed-size. If more extents
105+
// could not be deduced from type, that's an error (a fir.box should
106+
// have been used in the interface).
107+
if (extents.size() + 1 < typeExtents.size())
108+
mlir::emitError(loc, "cannot retrieve array extents from type");
109+
} else if (type.isa<fir::CharacterType>()) {
110+
if (!resultLen)
111+
resultLen = builder.createIntegerConstant(loc, lenType, 1);
112+
} else if (auto boxCharType = type.dyn_cast<fir::BoxCharType>()) {
71113
auto refType = builder.getRefType(boxCharType.getEleTy());
72114
auto unboxed =
73115
builder.create<fir::UnboxCharOp>(loc, refType, lenType, character);
74-
return {unboxed.getResult(0), unboxed.getResult(1)};
75-
}
76-
if (auto seqType = type.dyn_cast<fir::CharacterType>()) {
77-
// Materialize length for usage into character manipulations.
78-
auto len = builder.createIntegerConstant(loc, lenType, 1);
79-
return {character, len};
80-
}
81-
if (auto refType = type.dyn_cast<fir::ReferenceType>())
82-
type = refType.getEleTy();
83-
if (auto seqType = type.dyn_cast<fir::SequenceType>()) {
84-
assert(seqType.hasConstantShape() &&
85-
"ssa array value must have constant length");
86-
auto shape = seqType.getShape();
87-
assert(shape.size() == 1 && "only scalar character supported");
88-
// Materialize length for usage into character manipulations.
89-
auto len = builder.createIntegerConstant(loc, lenType, shape[0]);
90-
// FIXME: this seems to work for tests, but don't think it is correct
91-
if (auto load = dyn_cast<fir::LoadOp>(character.getDefiningOp()))
92-
return {load.memref(), len};
93-
return {character, len};
94-
}
95-
if (auto charTy = type.dyn_cast<fir::CharacterType>()) {
96-
auto len = builder.createIntegerConstant(loc, lenType, 1);
97-
return {character, len};
116+
base = unboxed.getResult(0);
117+
if (!resultLen)
118+
resultLen = unboxed.getResult(1);
119+
} else if (type.isa<fir::BoxType>()) {
120+
mlir::emitError(loc, "descriptor or derived type not yet handled");
121+
} else {
122+
llvm_unreachable("Cannot translate mlir::Value to character ExtendedValue");
98123
}
99-
llvm::report_fatal_error("unexpected character type");
124+
125+
if (!resultLen)
126+
mlir::emitError(loc, "no dynamic length found for character");
127+
if (!extents.empty())
128+
return fir::CharArrayBoxValue{base, resultLen, extents};
129+
return fir::CharBoxValue{base, resultLen};
100130
}
101131

102132
/// Get fir.ref<fir.char<kind>> type.
@@ -115,17 +145,15 @@ Fortran::lower::CharacterExprHelper::createEmbox(const fir::CharBoxValue &box) {
115145
auto boxCharType = fir::BoxCharType::get(builder.getContext(), kind);
116146
auto refType = getReferenceType(str);
117147
// So far, fir.emboxChar fails lowering to llvm when it is given
118-
// fir.data<fir.array<len x fir.char<kind>>> types, so convert to
119-
// fir.data<fir.char<kind>> if needed.
148+
// fir.ref<fir.array<len x fir.char<kind>>> types, so convert to
149+
// fir.ref<fir.char<kind>> if needed.
120150
auto buff = str.getBuffer();
121-
if (refType != str.getBuffer().getType())
122-
buff = builder.createConvert(loc, refType, buff);
151+
buff = builder.createConvert(loc, refType, buff);
123152
// Convert in case the provided length is not of the integer type that must
124153
// be used in boxchar.
125154
auto lenType = getLengthType();
126155
auto len = str.getLen();
127-
if (str.getLen().getType() != lenType)
128-
len = builder.createConvert(loc, lenType, len);
156+
len = builder.createConvert(loc, lenType, len);
129157
return builder.create<fir::EmboxCharOp>(loc, boxCharType, buff, len);
130158
}
131159

@@ -182,16 +210,20 @@ Fortran::lower::CharacterExprHelper::createTemp(mlir::Type type,
182210
void Fortran::lower::CharacterExprHelper::createLengthOneAssign(
183211
const fir::CharBoxValue &lhs, const fir::CharBoxValue &rhs) {
184212
auto addr = lhs.getBuffer();
185-
auto refType = getReferenceType(lhs);
186-
addr = builder.createConvert(loc, refType, addr);
187-
188213
auto val = rhs.getBuffer();
189-
if (!needToMaterialize(rhs)) {
190-
mlir::Value rhsAddr = rhs.getBuffer();
191-
rhsAddr = builder.createConvert(loc, refType, rhsAddr);
192-
val = builder.create<fir::LoadOp>(loc, rhsAddr);
214+
// If rhs value resides in memory, load it.
215+
if (!needToMaterialize(rhs))
216+
val = builder.create<fir::LoadOp>(loc, val);
217+
auto valTy = val.getType();
218+
// Precondition is rhs is size 1, but it may be wrapped in a fir.array.
219+
if (auto seqTy = valTy.dyn_cast<fir::SequenceType>()) {
220+
auto zero = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
221+
valTy = seqTy.getEleTy();
222+
val = builder.create<fir::ExtractValueOp>(loc, valTy, val, zero);
193223
}
194-
224+
auto addrTy = fir::ReferenceType::get(valTy);
225+
addr = builder.createConvert(loc, addrTy, addr);
226+
assert(fir::dyn_cast_ptrEleTy(addr.getType()) == val.getType());
195227
builder.create<fir::StoreOp>(loc, val, addr);
196228
}
197229

@@ -211,8 +243,8 @@ void Fortran::lower::CharacterExprHelper::createAssign(
211243
// if needed.
212244
mlir::Value copyCount = lhs.getLen();
213245
if (!compileTimeSameLength)
214-
copyCount = Fortran::lower::IntrinsicCallOpsHelper{builder, loc}.genMin(
215-
{lhs.getLen(), rhs.getLen()});
246+
copyCount =
247+
Fortran::lower::genMin(builder, loc, {lhs.getLen(), rhs.getLen()});
216248

217249
fir::CharBoxValue safeRhs = rhs;
218250
if (needToMaterialize(rhs)) {
@@ -433,7 +465,8 @@ Fortran::lower::CharacterExprHelper::materializeCharacter(mlir::Value str) {
433465

434466
bool Fortran::lower::CharacterExprHelper::isCharacterLiteral(mlir::Type type) {
435467
if (auto seqType = type.dyn_cast<fir::SequenceType>())
436-
return seqType.getEleTy().isa<fir::CharacterType>();
468+
return (seqType.getShape().size() == 1) &&
469+
seqType.getEleTy().isa<fir::CharacterType>();
437470
return false;
438471
}
439472

@@ -442,9 +475,9 @@ bool Fortran::lower::CharacterExprHelper::isCharacter(mlir::Type type) {
442475
return true;
443476
if (auto refType = type.dyn_cast<fir::ReferenceType>())
444477
type = refType.getEleTy();
445-
if (auto seqType = type.dyn_cast<fir::SequenceType>()) {
446-
type = seqType.getEleTy();
447-
}
478+
if (auto seqType = type.dyn_cast<fir::SequenceType>())
479+
if (seqType.getShape().size() == 1)
480+
type = seqType.getEleTy();
448481
return type.isa<fir::CharacterType>();
449482
}
450483

0 commit comments

Comments
 (0)