Reapply "[mlir] Mark isa/dyn_cast/cast/... member functions depreca… (#90406)

…ted. (#89998)" (#90250)

This partially reverts commit 7aedd7dc754c74a49fe84ed2640e269c25414087.

This change removes calls to the deprecated member functions. It does
not mark the functions deprecated yet and does not disable the
deprecation warning in TypeSwitch. This seems to cause problems with
MSVC.
This commit is contained in:
Christian Sigg 2024-04-28 22:01:42 +02:00 committed by GitHub
parent c9dae43438
commit fac349a169
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
93 changed files with 1326 additions and 1275 deletions

View File

@ -90,7 +90,7 @@ inline std::string mangleArrayLiteral(
return mangleArrayLiteral(x.values().size() * sizeof(x.values()[0]), return mangleArrayLiteral(x.values().size() * sizeof(x.values()[0]),
x.shape(), Fortran::common::TypeCategory::Derived, x.shape(), Fortran::common::TypeCategory::Derived,
/*kind=*/0, /*charLen=*/-1, /*kind=*/0, /*charLen=*/-1,
eleTy.cast<fir::RecordType>().getName()); mlir::cast<fir::RecordType>(eleTy).getName());
} }
/// Return the compiler-generated name of a static namelist variable descriptor. /// Return the compiler-generated name of a static namelist variable descriptor.

View File

@ -88,7 +88,7 @@ public:
// name must be used so that we add to the tbaa tree added in the FIR pass // name must be used so that we add to the tbaa tree added in the FIR pass
mlir::Attribute attr = func->getAttr(getInternalFuncNameAttrName()); mlir::Attribute attr = func->getAttr(getInternalFuncNameAttrName());
if (attr) { if (attr) {
return getFuncTree(attr.cast<mlir::StringAttr>()); return getFuncTree(mlir::cast<mlir::StringAttr>(attr));
} }
return getFuncTree(func.getSymNameAttr()); return getFuncTree(func.getSymNameAttr());
} }

View File

@ -78,7 +78,7 @@ class CharBoxValue : public AbstractBox {
public: public:
CharBoxValue(mlir::Value addr, mlir::Value len) CharBoxValue(mlir::Value addr, mlir::Value len)
: AbstractBox{addr}, len{len} { : AbstractBox{addr}, len{len} {
if (addr && addr.getType().template isa<fir::BoxCharType>()) if (addr && mlir::isa<fir::BoxCharType>(addr.getType()))
fir::emitFatalError(addr.getLoc(), fir::emitFatalError(addr.getLoc(),
"BoxChar should not be in CharBoxValue"); "BoxChar should not be in CharBoxValue");
} }
@ -221,7 +221,7 @@ public:
auto type = getAddr().getType(); auto type = getAddr().getType();
if (auto pointedTy = fir::dyn_cast_ptrEleTy(type)) if (auto pointedTy = fir::dyn_cast_ptrEleTy(type))
type = pointedTy; type = pointedTy;
return type.cast<fir::BaseBoxType>(); return mlir::cast<fir::BaseBoxType>(type);
} }
/// Return the part of the address type after memory and box types. That is /// Return the part of the address type after memory and box types. That is
/// the element type, maybe wrapped in a fir.array type. /// the element type, maybe wrapped in a fir.array type.
@ -243,22 +243,22 @@ public:
/// Get the scalar type related to the described entity /// Get the scalar type related to the described entity
mlir::Type getEleTy() const { mlir::Type getEleTy() const {
auto type = getBaseTy(); auto type = getBaseTy();
if (auto seqTy = type.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type))
return seqTy.getEleTy(); return seqTy.getEleTy();
return type; return type;
} }
/// Is the entity an array or an assumed rank ? /// Is the entity an array or an assumed rank ?
bool hasRank() const { return getBaseTy().isa<fir::SequenceType>(); } bool hasRank() const { return mlir::isa<fir::SequenceType>(getBaseTy()); }
/// Is this an assumed rank ? /// Is this an assumed rank ?
bool hasAssumedRank() const { bool hasAssumedRank() const {
auto seqTy = getBaseTy().dyn_cast<fir::SequenceType>(); auto seqTy = mlir::dyn_cast<fir::SequenceType>(getBaseTy());
return seqTy && seqTy.hasUnknownShape(); return seqTy && seqTy.hasUnknownShape();
} }
/// Returns the rank of the entity. Beware that zero will be returned for /// Returns the rank of the entity. Beware that zero will be returned for
/// both scalars and assumed rank. /// both scalars and assumed rank.
unsigned rank() const { unsigned rank() const {
if (auto seqTy = getBaseTy().dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(getBaseTy()))
return seqTy.getDimension(); return seqTy.getDimension();
return 0; return 0;
} }
@ -267,7 +267,7 @@ public:
bool isCharacter() const { return fir::isa_char(getEleTy()); } bool isCharacter() const { return fir::isa_char(getEleTy()); }
/// Is this a derived type entity ? /// Is this a derived type entity ?
bool isDerived() const { return getEleTy().isa<fir::RecordType>(); } bool isDerived() const { return mlir::isa<fir::RecordType>(getEleTy()); }
bool isDerivedWithLenParameters() const { bool isDerivedWithLenParameters() const {
return fir::isRecordWithTypeParameters(getEleTy()); return fir::isRecordWithTypeParameters(getEleTy());
@ -377,11 +377,11 @@ public:
} }
/// Is this a Fortran pointer ? /// Is this a Fortran pointer ?
bool isPointer() const { bool isPointer() const {
return getBoxTy().getEleTy().isa<fir::PointerType>(); return mlir::isa<fir::PointerType>(getBoxTy().getEleTy());
} }
/// Is this an allocatable ? /// Is this an allocatable ?
bool isAllocatable() const { bool isAllocatable() const {
return getBoxTy().getEleTy().isa<fir::HeapType>(); return mlir::isa<fir::HeapType>(getBoxTy().getEleTy());
} }
// Replace the fir.ref<fir.box>, keeping any non-deferred parameters. // Replace the fir.ref<fir.box>, keeping any non-deferred parameters.
MutableBoxValue clone(mlir::Value newBox) const { MutableBoxValue clone(mlir::Value newBox) const {
@ -488,7 +488,7 @@ public:
if (const auto *b = getUnboxed()) { if (const auto *b = getUnboxed()) {
if (*b) { if (*b) {
auto type = b->getType(); auto type = b->getType();
if (type.template isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(type))
fir::emitFatalError(b->getLoc(), "BoxChar should be unboxed"); fir::emitFatalError(b->getLoc(), "BoxChar should be unboxed");
type = fir::unwrapSequenceType(fir::unwrapRefType(type)); type = fir::unwrapSequenceType(fir::unwrapRefType(type));
if (fir::isa_char(type)) if (fir::isa_char(type))

View File

@ -43,9 +43,9 @@ template <typename B>
void genCharacterCopy(mlir::Value src, mlir::Value srcLen, mlir::Value dst, void genCharacterCopy(mlir::Value src, mlir::Value srcLen, mlir::Value dst,
mlir::Value dstLen, B &builder, mlir::Location loc) { mlir::Value dstLen, B &builder, mlir::Location loc) {
auto srcTy = auto srcTy =
fir::dyn_cast_ptrEleTy(src.getType()).template cast<fir::CharacterType>(); mlir::cast<fir::CharacterType>(fir::dyn_cast_ptrEleTy(src.getType()));
auto dstTy = auto dstTy =
fir::dyn_cast_ptrEleTy(dst.getType()).template cast<fir::CharacterType>(); mlir::cast<fir::CharacterType>(fir::dyn_cast_ptrEleTy(dst.getType()));
if (!srcLen && !dstLen && srcTy.getFKind() == dstTy.getFKind() && if (!srcLen && !dstLen && srcTy.getFKind() == dstTy.getFKind() &&
srcTy.getLen() == dstTy.getLen()) { srcTy.getLen() == dstTy.getLen()) {
// same size, so just use load and store // same size, so just use load and store
@ -61,8 +61,8 @@ void genCharacterCopy(mlir::Value src, mlir::Value srcLen, mlir::Value dst,
fir::CharacterType::getSingleton(ty.getContext(), ty.getFKind()))); fir::CharacterType::getSingleton(ty.getContext(), ty.getFKind())));
}; };
auto toEleTy = [&](fir::ReferenceType ty) { auto toEleTy = [&](fir::ReferenceType ty) {
auto seqTy = ty.getEleTy().cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(ty.getEleTy());
return seqTy.getEleTy().cast<fir::CharacterType>(); return mlir::cast<fir::CharacterType>(seqTy.getEleTy());
}; };
auto toCoorTy = [&](fir::ReferenceType ty) { auto toCoorTy = [&](fir::ReferenceType ty) {
return fir::ReferenceType::get(toEleTy(ty)); return fir::ReferenceType::get(toEleTy(ty));
@ -190,8 +190,8 @@ originateIndices(mlir::Location loc, B &builder, mlir::Type memTy,
if (origins.empty()) { if (origins.empty()) {
assert(!shapeVal || mlir::isa<fir::ShapeOp>(shapeVal.getDefiningOp())); assert(!shapeVal || mlir::isa<fir::ShapeOp>(shapeVal.getDefiningOp()));
auto ty = fir::dyn_cast_ptrOrBoxEleTy(memTy); auto ty = fir::dyn_cast_ptrOrBoxEleTy(memTy);
assert(ty && ty.isa<fir::SequenceType>()); assert(ty && mlir::isa<fir::SequenceType>(ty));
auto seqTy = ty.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(ty);
auto one = builder.template create<mlir::arith::ConstantIndexOp>(loc, 1); auto one = builder.template create<mlir::arith::ConstantIndexOp>(loc, 1);
const auto dimension = seqTy.getDimension(); const auto dimension = seqTy.getDimension();
if (shapeVal) { if (shapeVal) {

View File

@ -77,12 +77,12 @@ public:
/// Return the rank of this entity or -1 if it is an assumed rank. /// Return the rank of this entity or -1 if it is an assumed rank.
int getRank() const { int getRank() const {
mlir::Type type = fir::unwrapPassByRefType(fir::unwrapRefType(getType())); mlir::Type type = fir::unwrapPassByRefType(fir::unwrapRefType(getType()));
if (auto seqTy = type.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type)) {
if (seqTy.hasUnknownShape()) if (seqTy.hasUnknownShape())
return -1; return -1;
return seqTy.getDimension(); return seqTy.getDimension();
} }
if (auto exprType = type.dyn_cast<hlfir::ExprType>()) if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(type))
return exprType.getRank(); return exprType.getRank();
return 0; return 0;
} }
@ -99,17 +99,17 @@ public:
bool hasLengthParameters() const { bool hasLengthParameters() const {
mlir::Type eleTy = getFortranElementType(); mlir::Type eleTy = getFortranElementType();
return eleTy.isa<fir::CharacterType>() || return mlir::isa<fir::CharacterType>(eleTy) ||
fir::isRecordWithTypeParameters(eleTy); fir::isRecordWithTypeParameters(eleTy);
} }
bool isCharacter() const { bool isCharacter() const {
return getFortranElementType().isa<fir::CharacterType>(); return mlir::isa<fir::CharacterType>(getFortranElementType());
} }
bool hasIntrinsicType() const { bool hasIntrinsicType() const {
mlir::Type eleTy = getFortranElementType(); mlir::Type eleTy = getFortranElementType();
return fir::isa_trivial(eleTy) || eleTy.isa<fir::CharacterType>(); return fir::isa_trivial(eleTy) || mlir::isa<fir::CharacterType>(eleTy);
} }
bool isDerivedWithLengthParameters() const { bool isDerivedWithLengthParameters() const {
@ -124,8 +124,8 @@ public:
if (auto varIface = getIfVariableInterface()) { if (auto varIface = getIfVariableInterface()) {
if (auto shape = varIface.getShape()) { if (auto shape = varIface.getShape()) {
auto shapeTy = shape.getType(); auto shapeTy = shape.getType();
return shapeTy.isa<fir::ShiftType>() || return mlir::isa<fir::ShiftType>(shapeTy) ||
shapeTy.isa<fir::ShapeShiftType>(); mlir::isa<fir::ShapeShiftType>(shapeTy);
} }
return false; return false;
} }

View File

@ -663,8 +663,8 @@ static inline mlir::FunctionType genFuncType(mlir::MLIRContext *context,
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
static inline mlir::Type getConvertedElementType(mlir::MLIRContext *context, static inline mlir::Type getConvertedElementType(mlir::MLIRContext *context,
mlir::Type eleTy) { mlir::Type eleTy) {
if (eleTy.isa<mlir::IntegerType>() && !eleTy.isSignlessInteger()) { if (mlir::isa<mlir::IntegerType>(eleTy) && !eleTy.isSignlessInteger()) {
const auto intTy{eleTy.dyn_cast<mlir::IntegerType>()}; const auto intTy{mlir::dyn_cast<mlir::IntegerType>(eleTy)};
auto newEleTy{mlir::IntegerType::get(context, intTy.getWidth())}; auto newEleTy{mlir::IntegerType::get(context, intTy.getWidth())};
return newEleTy; return newEleTy;
} }

View File

@ -180,10 +180,10 @@ struct VecTypeInfo {
// Returns a VecTypeInfo with element type and length of given fir vector type. // Returns a VecTypeInfo with element type and length of given fir vector type.
// Preserves signness of fir vector type if element type of integer. // Preserves signness of fir vector type if element type of integer.
static inline VecTypeInfo getVecTypeFromFirType(mlir::Type firTy) { static inline VecTypeInfo getVecTypeFromFirType(mlir::Type firTy) {
assert(firTy.isa<fir::VectorType>()); assert(mlir::isa<fir::VectorType>(firTy));
VecTypeInfo vecTyInfo; VecTypeInfo vecTyInfo;
vecTyInfo.eleTy = firTy.dyn_cast<fir::VectorType>().getEleTy(); vecTyInfo.eleTy = mlir::dyn_cast<fir::VectorType>(firTy).getEleTy();
vecTyInfo.len = firTy.dyn_cast<fir::VectorType>().getLen(); vecTyInfo.len = mlir::dyn_cast<fir::VectorType>(firTy).getLen();
return vecTyInfo; return vecTyInfo;
} }

View File

@ -21,17 +21,18 @@ include "flang/Optimizer/Dialect/FIROps.td"
def IdenticalTypePred : Constraint<CPred<"$0.getType() == $1.getType()">>; def IdenticalTypePred : Constraint<CPred<"$0.getType() == $1.getType()">>;
def IntegerTypePred : Constraint<CPred<"fir::isa_integer($0.getType())">>; def IntegerTypePred : Constraint<CPred<"fir::isa_integer($0.getType())">>;
def IndexTypePred : Constraint<CPred<"$0.getType().isa<mlir::IndexType>()">>; def IndexTypePred : Constraint<CPred<
"mlir::isa<mlir::IndexType>($0.getType())">>;
// Widths are monotonic. // Widths are monotonic.
// $0.bits >= $1.bits >= $2.bits or $0.bits <= $1.bits <= $2.bits // $0.bits >= $1.bits >= $2.bits or $0.bits <= $1.bits <= $2.bits
def MonotonicTypePred def MonotonicTypePred
: Constraint<CPred<"(($0.getType().isa<mlir::IntegerType>() && " : Constraint<CPred<"((mlir::isa<mlir::IntegerType>($0.getType()) && "
" $1.getType().isa<mlir::IntegerType>() && " " mlir::isa<mlir::IntegerType>($1.getType()) && "
" $2.getType().isa<mlir::IntegerType>()) || " " mlir::isa<mlir::IntegerType>($2.getType())) || "
" ($0.getType().isa<mlir::FloatType>() && " " (mlir::isa<mlir::FloatType>($0.getType()) && "
" $1.getType().isa<mlir::FloatType>() && " " mlir::isa<mlir::FloatType>($1.getType()) && "
" $2.getType().isa<mlir::FloatType>())) && " " mlir::isa<mlir::FloatType>($2.getType()))) && "
"(($0.getType().getIntOrFloatBitWidth() <= " "(($0.getType().getIntOrFloatBitWidth() <= "
" $1.getType().getIntOrFloatBitWidth() && " " $1.getType().getIntOrFloatBitWidth() && "
" $1.getType().getIntOrFloatBitWidth() <= " " $1.getType().getIntOrFloatBitWidth() <= "
@ -42,8 +43,8 @@ def MonotonicTypePred
" $2.getType().getIntOrFloatBitWidth()))">>; " $2.getType().getIntOrFloatBitWidth()))">>;
def IntPred : Constraint<CPred< def IntPred : Constraint<CPred<
"$0.getType().isa<mlir::IntegerType>() && " "mlir::isa<mlir::IntegerType>($0.getType()) && "
"$1.getType().isa<mlir::IntegerType>()">>; "mlir::isa<mlir::IntegerType>($1.getType())">>;
// If both are int type and the first is smaller than the second. // If both are int type and the first is smaller than the second.
// $0.bits <= $1.bits // $0.bits <= $1.bits
@ -101,8 +102,8 @@ def CombineConvertTruncOptPattern
def createConstantOp def createConstantOp
: NativeCodeCall<"$_builder.create<mlir::arith::ConstantOp>" : NativeCodeCall<"$_builder.create<mlir::arith::ConstantOp>"
"($_loc, $_builder.getIndexType(), " "($_loc, $_builder.getIndexType(), "
"rewriter.getIndexAttr($1.dyn_cast<mlir::IntegerAttr>()" "rewriter.getIndexAttr("
".getInt()))">; "mlir::dyn_cast<mlir::IntegerAttr>($1).getInt()))">;
def ForwardConstantConvertPattern def ForwardConstantConvertPattern
: Pat<(fir_ConvertOp:$res (Arith_ConstantOp:$cnt $attr)), : Pat<(fir_ConvertOp:$res (Arith_ConstantOp:$cnt $attr)),

View File

@ -2708,14 +2708,14 @@ def fir_ConvertOp : fir_OneResultOp<"convert", [NoMemoryEffect]> {
let hasCanonicalizer = 1; let hasCanonicalizer = 1;
} }
def FortranTypeAttr : Attr<And<[CPred<"$_self.isa<mlir::TypeAttr>()">, def FortranTypeAttr : Attr<And<[CPred<"mlir::isa<mlir::TypeAttr>($_self)">,
Or<[CPred<"$_self.cast<mlir::TypeAttr>().getValue().isa<fir::CharacterType," Or<[CPred<"mlir::isa<fir::CharacterType, fir::ComplexType, "
"fir::ComplexType, fir::IntegerType, fir::LogicalType," "fir::IntegerType, fir::LogicalType, fir::RealType, "
"fir::RealType, fir::RecordType>()">]>]>, "fir::RecordType>(mlir::cast<mlir::TypeAttr>($_self).getValue())"
"Fortran surface type"> { >]>]>, "Fortran surface type"> {
let storageType = [{ ::mlir::TypeAttr }]; let storageType = [{ ::mlir::TypeAttr }];
let returnType = "mlir::Type"; let returnType = "mlir::Type";
let convertFromStorage = "$_self.getValue().cast<mlir::Type>()"; let convertFromStorage = "mlir::cast<mlir::Type>($_self.getValue())";
} }
def fir_TypeDescOp : fir_OneResultOp<"type_desc", [NoMemoryEffect]> { def fir_TypeDescOp : fir_OneResultOp<"type_desc", [NoMemoryEffect]> {

View File

@ -97,35 +97,36 @@ bool isa_fir_or_std_type(mlir::Type t);
/// Is `t` a FIR dialect type that implies a memory (de)reference? /// Is `t` a FIR dialect type that implies a memory (de)reference?
inline bool isa_ref_type(mlir::Type t) { inline bool isa_ref_type(mlir::Type t) {
return t.isa<fir::ReferenceType, fir::PointerType, fir::HeapType, return mlir::isa<fir::ReferenceType, fir::PointerType, fir::HeapType,
fir::LLVMPointerType>(); fir::LLVMPointerType>(t);
} }
/// Is `t` a boxed type? /// Is `t` a boxed type?
inline bool isa_box_type(mlir::Type t) { inline bool isa_box_type(mlir::Type t) {
return t.isa<fir::BaseBoxType, fir::BoxCharType, fir::BoxProcType>(); return mlir::isa<fir::BaseBoxType, fir::BoxCharType, fir::BoxProcType>(t);
} }
/// Is `t` a type that is always trivially pass-by-reference? Specifically, this /// Is `t` a type that is always trivially pass-by-reference? Specifically, this
/// is testing if `t` is a ReferenceType or any box type. Compare this to /// is testing if `t` is a ReferenceType or any box type. Compare this to
/// conformsWithPassByRef(), which includes pointers and allocatables. /// conformsWithPassByRef(), which includes pointers and allocatables.
inline bool isa_passbyref_type(mlir::Type t) { inline bool isa_passbyref_type(mlir::Type t) {
return t.isa<fir::ReferenceType, mlir::FunctionType>() || isa_box_type(t); return mlir::isa<fir::ReferenceType, mlir::FunctionType>(t) ||
isa_box_type(t);
} }
/// Is `t` a type that can conform to be pass-by-reference? Depending on the /// Is `t` a type that can conform to be pass-by-reference? Depending on the
/// context, these types may simply demote to pass-by-reference or a reference /// context, these types may simply demote to pass-by-reference or a reference
/// to them may have to be passed instead. Functions are always referent. /// to them may have to be passed instead. Functions are always referent.
inline bool conformsWithPassByRef(mlir::Type t) { inline bool conformsWithPassByRef(mlir::Type t) {
return isa_ref_type(t) || isa_box_type(t) || t.isa<mlir::FunctionType>(); return isa_ref_type(t) || isa_box_type(t) || mlir::isa<mlir::FunctionType>(t);
} }
/// Is `t` a derived (record) type? /// Is `t` a derived (record) type?
inline bool isa_derived(mlir::Type t) { return t.isa<fir::RecordType>(); } inline bool isa_derived(mlir::Type t) { return mlir::isa<fir::RecordType>(t); }
/// Is `t` type(c_ptr) or type(c_funptr)? /// Is `t` type(c_ptr) or type(c_funptr)?
inline bool isa_builtin_cptr_type(mlir::Type t) { inline bool isa_builtin_cptr_type(mlir::Type t) {
if (auto recTy = t.dyn_cast_or_null<fir::RecordType>()) if (auto recTy = mlir::dyn_cast_or_null<fir::RecordType>(t))
return recTy.getName().ends_with("T__builtin_c_ptr") || return recTy.getName().ends_with("T__builtin_c_ptr") ||
recTy.getName().ends_with("T__builtin_c_funptr"); recTy.getName().ends_with("T__builtin_c_funptr");
return false; return false;
@ -133,7 +134,7 @@ inline bool isa_builtin_cptr_type(mlir::Type t) {
/// Is `t` a FIR dialect aggregate type? /// Is `t` a FIR dialect aggregate type?
inline bool isa_aggregate(mlir::Type t) { inline bool isa_aggregate(mlir::Type t) {
return t.isa<SequenceType, mlir::TupleType>() || fir::isa_derived(t); return mlir::isa<SequenceType, mlir::TupleType>(t) || fir::isa_derived(t);
} }
/// Extract the `Type` pointed to from a FIR memory reference type. If `t` is /// Extract the `Type` pointed to from a FIR memory reference type. If `t` is
@ -146,17 +147,17 @@ mlir::Type dyn_cast_ptrOrBoxEleTy(mlir::Type t);
/// Is `t` a FIR Real or MLIR Float type? /// Is `t` a FIR Real or MLIR Float type?
inline bool isa_real(mlir::Type t) { inline bool isa_real(mlir::Type t) {
return t.isa<fir::RealType, mlir::FloatType>(); return mlir::isa<fir::RealType, mlir::FloatType>(t);
} }
/// Is `t` an integral type? /// Is `t` an integral type?
inline bool isa_integer(mlir::Type t) { inline bool isa_integer(mlir::Type t) {
return t.isa<mlir::IndexType, mlir::IntegerType, fir::IntegerType>(); return mlir::isa<mlir::IndexType, mlir::IntegerType, fir::IntegerType>(t);
} }
/// Is `t` a vector type? /// Is `t` a vector type?
inline bool isa_vector(mlir::Type t) { inline bool isa_vector(mlir::Type t) {
return t.isa<mlir::VectorType, fir::VectorType>(); return mlir::isa<mlir::VectorType, fir::VectorType>(t);
} }
mlir::Type parseFirType(FIROpsDialect *, mlir::DialectAsmParser &parser); mlir::Type parseFirType(FIROpsDialect *, mlir::DialectAsmParser &parser);
@ -169,22 +170,22 @@ void verifyIntegralType(mlir::Type type);
/// Is `t` a FIR or MLIR Complex type? /// Is `t` a FIR or MLIR Complex type?
inline bool isa_complex(mlir::Type t) { inline bool isa_complex(mlir::Type t) {
return t.isa<fir::ComplexType, mlir::ComplexType>(); return mlir::isa<fir::ComplexType, mlir::ComplexType>(t);
} }
/// Is `t` a CHARACTER type? Does not check the length. /// Is `t` a CHARACTER type? Does not check the length.
inline bool isa_char(mlir::Type t) { return t.isa<fir::CharacterType>(); } inline bool isa_char(mlir::Type t) { return mlir::isa<fir::CharacterType>(t); }
/// Is `t` a trivial intrinsic type? CHARACTER is <em>excluded</em> because it /// Is `t` a trivial intrinsic type? CHARACTER is <em>excluded</em> because it
/// is a dependent type. /// is a dependent type.
inline bool isa_trivial(mlir::Type t) { inline bool isa_trivial(mlir::Type t) {
return isa_integer(t) || isa_real(t) || isa_complex(t) || isa_vector(t) || return isa_integer(t) || isa_real(t) || isa_complex(t) || isa_vector(t) ||
t.isa<fir::LogicalType>(); mlir::isa<fir::LogicalType>(t);
} }
/// Is `t` a CHARACTER type with a LEN other than 1? /// Is `t` a CHARACTER type with a LEN other than 1?
inline bool isa_char_string(mlir::Type t) { inline bool isa_char_string(mlir::Type t) {
if (auto ct = t.dyn_cast_or_null<fir::CharacterType>()) if (auto ct = mlir::dyn_cast_or_null<fir::CharacterType>(t))
return ct.getLen() != fir::CharacterType::singleton(); return ct.getLen() != fir::CharacterType::singleton();
return false; return false;
} }
@ -198,7 +199,7 @@ bool isa_unknown_size_box(mlir::Type t);
/// Returns true iff `t` is a fir.char type and has an unknown length. /// Returns true iff `t` is a fir.char type and has an unknown length.
inline bool characterWithDynamicLen(mlir::Type t) { inline bool characterWithDynamicLen(mlir::Type t) {
if (auto charTy = t.dyn_cast<fir::CharacterType>()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(t))
return charTy.hasDynamicLen(); return charTy.hasDynamicLen();
return false; return false;
} }
@ -213,11 +214,11 @@ inline bool sequenceWithNonConstantShape(fir::SequenceType seqTy) {
bool hasDynamicSize(mlir::Type t); bool hasDynamicSize(mlir::Type t);
inline unsigned getRankOfShapeType(mlir::Type t) { inline unsigned getRankOfShapeType(mlir::Type t) {
if (auto shTy = t.dyn_cast<fir::ShapeType>()) if (auto shTy = mlir::dyn_cast<fir::ShapeType>(t))
return shTy.getRank(); return shTy.getRank();
if (auto shTy = t.dyn_cast<fir::ShapeShiftType>()) if (auto shTy = mlir::dyn_cast<fir::ShapeShiftType>(t))
return shTy.getRank(); return shTy.getRank();
if (auto shTy = t.dyn_cast<fir::ShiftType>()) if (auto shTy = mlir::dyn_cast<fir::ShiftType>(t))
return shTy.getRank(); return shTy.getRank();
return 0; return 0;
} }
@ -225,14 +226,14 @@ inline unsigned getRankOfShapeType(mlir::Type t) {
/// Get the memory reference type of the data pointer from the box type, /// Get the memory reference type of the data pointer from the box type,
inline mlir::Type boxMemRefType(fir::BaseBoxType t) { inline mlir::Type boxMemRefType(fir::BaseBoxType t) {
auto eleTy = t.getEleTy(); auto eleTy = t.getEleTy();
if (!eleTy.isa<fir::PointerType, fir::HeapType>()) if (!mlir::isa<fir::PointerType, fir::HeapType>(eleTy))
eleTy = fir::ReferenceType::get(t); eleTy = fir::ReferenceType::get(t);
return eleTy; return eleTy;
} }
/// If `t` is a SequenceType return its element type, otherwise return `t`. /// If `t` is a SequenceType return its element type, otherwise return `t`.
inline mlir::Type unwrapSequenceType(mlir::Type t) { inline mlir::Type unwrapSequenceType(mlir::Type t) {
if (auto seqTy = t.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(t))
return seqTy.getEleTy(); return seqTy.getEleTy();
return t; return t;
} }
@ -278,7 +279,7 @@ inline fir::SequenceType unwrapUntilSeqType(mlir::Type t) {
t = ty; t = ty;
continue; continue;
} }
if (auto seqTy = t.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(t))
return seqTy; return seqTy;
return {}; return {};
} }
@ -287,8 +288,8 @@ inline fir::SequenceType unwrapUntilSeqType(mlir::Type t) {
/// Unwrap the referential and sequential outer types (if any). Returns the /// Unwrap the referential and sequential outer types (if any). Returns the
/// the element if type is fir::RecordType /// the element if type is fir::RecordType
inline fir::RecordType unwrapIfDerived(fir::BaseBoxType boxTy) { inline fir::RecordType unwrapIfDerived(fir::BaseBoxType boxTy) {
return fir::unwrapSequenceType(fir::unwrapRefType(boxTy.getEleTy())) return mlir::dyn_cast<fir::RecordType>(
.template dyn_cast<fir::RecordType>(); fir::unwrapSequenceType(fir::unwrapRefType(boxTy.getEleTy())));
} }
/// Return true iff `boxTy` wraps a fir::RecordType with length parameters /// Return true iff `boxTy` wraps a fir::RecordType with length parameters
@ -377,7 +378,7 @@ bool isRecordWithDescriptorMember(mlir::Type ty);
/// Return true iff `ty` is a RecordType with type parameters. /// Return true iff `ty` is a RecordType with type parameters.
inline bool isRecordWithTypeParameters(mlir::Type ty) { inline bool isRecordWithTypeParameters(mlir::Type ty) {
if (auto recTy = ty.dyn_cast_or_null<fir::RecordType>()) if (auto recTy = mlir::dyn_cast_or_null<fir::RecordType>(ty))
return recTy.isDependentType(); return recTy.isDependentType();
return false; return false;
} }
@ -401,14 +402,14 @@ mlir::Type fromRealTypeID(mlir::MLIRContext *context, llvm::Type::TypeID typeID,
int getTypeCode(mlir::Type ty, const KindMapping &kindMap); int getTypeCode(mlir::Type ty, const KindMapping &kindMap);
inline bool BaseBoxType::classof(mlir::Type type) { inline bool BaseBoxType::classof(mlir::Type type) {
return type.isa<fir::BoxType, fir::ClassType>(); return mlir::isa<fir::BoxType, fir::ClassType>(type);
} }
/// Return true iff `ty` is none or fir.array<none>. /// Return true iff `ty` is none or fir.array<none>.
inline bool isNoneOrSeqNone(mlir::Type type) { inline bool isNoneOrSeqNone(mlir::Type type) {
if (auto seqTy = type.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type))
return seqTy.getEleTy().isa<mlir::NoneType>(); return mlir::isa<mlir::NoneType>(seqTy.getEleTy());
return type.isa<mlir::NoneType>(); return mlir::isa<mlir::NoneType>(type);
} }
/// Return a fir.box<T> or fir.class<T> if the type is polymorphic. If the type /// Return a fir.box<T> or fir.class<T> if the type is polymorphic. If the type
@ -428,16 +429,16 @@ inline mlir::Type wrapInClassOrBoxType(mlir::Type eleTy,
/// !fir.array<2xf32> -> !fir.array<2xnone> /// !fir.array<2xf32> -> !fir.array<2xnone>
/// !fir.heap<!fir.array<2xf32>> -> !fir.heap<!fir.array<2xnone>> /// !fir.heap<!fir.array<2xf32>> -> !fir.heap<!fir.array<2xnone>>
inline mlir::Type updateTypeForUnlimitedPolymorphic(mlir::Type ty) { inline mlir::Type updateTypeForUnlimitedPolymorphic(mlir::Type ty) {
if (auto seqTy = ty.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
return fir::SequenceType::get( return fir::SequenceType::get(
seqTy.getShape(), updateTypeForUnlimitedPolymorphic(seqTy.getEleTy())); seqTy.getShape(), updateTypeForUnlimitedPolymorphic(seqTy.getEleTy()));
if (auto heapTy = ty.dyn_cast<fir::HeapType>()) if (auto heapTy = mlir::dyn_cast<fir::HeapType>(ty))
return fir::HeapType::get( return fir::HeapType::get(
updateTypeForUnlimitedPolymorphic(heapTy.getEleTy())); updateTypeForUnlimitedPolymorphic(heapTy.getEleTy()));
if (auto pointerTy = ty.dyn_cast<fir::PointerType>()) if (auto pointerTy = mlir::dyn_cast<fir::PointerType>(ty))
return fir::PointerType::get( return fir::PointerType::get(
updateTypeForUnlimitedPolymorphic(pointerTy.getEleTy())); updateTypeForUnlimitedPolymorphic(pointerTy.getEleTy()));
if (!ty.isa<mlir::NoneType, fir::RecordType>()) if (!mlir::isa<mlir::NoneType, fir::RecordType>(ty))
return mlir::NoneType::get(ty.getContext()); return mlir::NoneType::get(ty.getContext());
return ty; return ty;
} }
@ -451,18 +452,19 @@ mlir::Type changeElementType(mlir::Type type, mlir::Type newElementType,
/// Is `t` an address to fir.box or class type? /// Is `t` an address to fir.box or class type?
inline bool isBoxAddress(mlir::Type t) { inline bool isBoxAddress(mlir::Type t) {
return fir::isa_ref_type(t) && fir::unwrapRefType(t).isa<fir::BaseBoxType>(); return fir::isa_ref_type(t) &&
mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(t));
} }
/// Is `t` a fir.box or class address or value type? /// Is `t` a fir.box or class address or value type?
inline bool isBoxAddressOrValue(mlir::Type t) { inline bool isBoxAddressOrValue(mlir::Type t) {
return fir::unwrapRefType(t).isa<fir::BaseBoxType>(); return mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(t));
} }
/// Is this a fir.boxproc address type? /// Is this a fir.boxproc address type?
inline bool isBoxProcAddressType(mlir::Type t) { inline bool isBoxProcAddressType(mlir::Type t) {
t = fir::dyn_cast_ptrEleTy(t); t = fir::dyn_cast_ptrEleTy(t);
return t && t.isa<fir::BoxProcType>(); return t && mlir::isa<fir::BoxProcType>(t);
} }
/// Return a string representation of `ty`. /// Return a string representation of `ty`.

View File

@ -578,7 +578,7 @@ def fir_VoidType : FIR_Type<"Void", "void"> {
// Whether a type is a BaseBoxType // Whether a type is a BaseBoxType
def IsBaseBoxTypePred def IsBaseBoxTypePred
: CPred<"$_self.isa<::fir::BaseBoxType>()">; : CPred<"mlir::isa<::fir::BaseBoxType>($_self)">;
def fir_BaseBoxType : Type<IsBaseBoxTypePred, "fir.box or fir.class type">; def fir_BaseBoxType : Type<IsBaseBoxTypePred, "fir.box or fir.class type">;
// Generalized FIR and standard dialect types representing intrinsic types // Generalized FIR and standard dialect types representing intrinsic types

View File

@ -75,7 +75,7 @@ def fir_FortranVariableOpInterface : OpInterface<"FortranVariableOpInterface"> {
/// variable. /// variable.
mlir::Type getElementOrSequenceType() { mlir::Type getElementOrSequenceType() {
mlir::Type type = fir::unwrapPassByRefType(fir::unwrapRefType(getBase().getType())); mlir::Type type = fir::unwrapPassByRefType(fir::unwrapRefType(getBase().getType()));
if (auto boxCharType = type.dyn_cast<fir::BoxCharType>()) if (auto boxCharType = mlir::dyn_cast<fir::BoxCharType>(type))
return boxCharType.getEleTy(); return boxCharType.getEleTy();
return type; return type;
} }
@ -87,13 +87,13 @@ def fir_FortranVariableOpInterface : OpInterface<"FortranVariableOpInterface"> {
/// Is the variable an array? /// Is the variable an array?
bool isArray() { bool isArray() {
return getElementOrSequenceType().isa<fir::SequenceType>(); return mlir::isa<fir::SequenceType>(getElementOrSequenceType());
} }
/// Return the rank of the entity if it is known at compile time. /// Return the rank of the entity if it is known at compile time.
std::optional<unsigned> getRank() { std::optional<unsigned> getRank() {
if (auto sequenceType = if (auto sequenceType =
getElementOrSequenceType().dyn_cast<fir::SequenceType>()) { mlir::dyn_cast<fir::SequenceType>(getElementOrSequenceType())) {
if (sequenceType.hasUnknownShape()) if (sequenceType.hasUnknownShape())
return {}; return {};
return sequenceType.getDimension(); return sequenceType.getDimension();
@ -133,7 +133,7 @@ def fir_FortranVariableOpInterface : OpInterface<"FortranVariableOpInterface"> {
/// Is this a Fortran character variable? /// Is this a Fortran character variable?
bool isCharacter() { bool isCharacter() {
return getElementType().isa<fir::CharacterType>(); return mlir::isa<fir::CharacterType>(getElementType());
} }
/// Is this a Fortran character variable with an explicit length? /// Is this a Fortran character variable with an explicit length?
@ -149,7 +149,7 @@ def fir_FortranVariableOpInterface : OpInterface<"FortranVariableOpInterface"> {
/// Is this variable represented as a fir.box or fir.class value? /// Is this variable represented as a fir.box or fir.class value?
bool isBoxValue() { bool isBoxValue() {
return getBase().getType().isa<fir::BaseBoxType>(); return mlir::isa<fir::BaseBoxType>(getBase().getType());
} }
/// Is this variable represented as a fir.box or fir.class address? /// Is this variable represented as a fir.box or fir.class address?

View File

@ -40,9 +40,9 @@ namespace hlfir {
inline mlir::Type getFortranElementType(mlir::Type type) { inline mlir::Type getFortranElementType(mlir::Type type) {
type = fir::unwrapSequenceType( type = fir::unwrapSequenceType(
fir::unwrapPassByRefType(fir::unwrapRefType(type))); fir::unwrapPassByRefType(fir::unwrapRefType(type)));
if (auto exprType = type.dyn_cast<hlfir::ExprType>()) if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(type))
return exprType.getEleTy(); return exprType.getEleTy();
if (auto boxCharType = type.dyn_cast<fir::BoxCharType>()) if (auto boxCharType = mlir::dyn_cast<fir::BoxCharType>(type))
return boxCharType.getEleTy(); return boxCharType.getEleTy();
return type; return type;
} }
@ -51,12 +51,12 @@ inline mlir::Type getFortranElementType(mlir::Type type) {
/// fir.array type. Otherwise, returns the Fortran element typeof the entity. /// fir.array type. Otherwise, returns the Fortran element typeof the entity.
inline mlir::Type getFortranElementOrSequenceType(mlir::Type type) { inline mlir::Type getFortranElementOrSequenceType(mlir::Type type) {
type = fir::unwrapPassByRefType(fir::unwrapRefType(type)); type = fir::unwrapPassByRefType(fir::unwrapRefType(type));
if (auto exprType = type.dyn_cast<hlfir::ExprType>()) { if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(type)) {
if (exprType.isArray()) if (exprType.isArray())
return fir::SequenceType::get(exprType.getShape(), exprType.getEleTy()); return fir::SequenceType::get(exprType.getShape(), exprType.getEleTy());
return exprType.getEleTy(); return exprType.getEleTy();
} }
if (auto boxCharType = type.dyn_cast<fir::BoxCharType>()) if (auto boxCharType = mlir::dyn_cast<fir::BoxCharType>(type))
return boxCharType.getEleTy(); return boxCharType.getEleTy();
return type; return type;
} }
@ -64,16 +64,16 @@ inline mlir::Type getFortranElementOrSequenceType(mlir::Type type) {
/// Is this a fir.box or fir.class address type? /// Is this a fir.box or fir.class address type?
inline bool isBoxAddressType(mlir::Type type) { inline bool isBoxAddressType(mlir::Type type) {
type = fir::dyn_cast_ptrEleTy(type); type = fir::dyn_cast_ptrEleTy(type);
return type && type.isa<fir::BaseBoxType>(); return type && mlir::isa<fir::BaseBoxType>(type);
} }
/// Is this a fir.box or fir.class address or value type? /// Is this a fir.box or fir.class address or value type?
inline bool isBoxAddressOrValueType(mlir::Type type) { inline bool isBoxAddressOrValueType(mlir::Type type) {
return fir::unwrapRefType(type).isa<fir::BaseBoxType>(); return mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(type));
} }
inline bool isPolymorphicType(mlir::Type type) { inline bool isPolymorphicType(mlir::Type type) {
if (auto exprType = type.dyn_cast<hlfir::ExprType>()) if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(type))
return exprType.isPolymorphic(); return exprType.isPolymorphic();
return fir::isPolymorphicType(type); return fir::isPolymorphicType(type);
} }
@ -81,14 +81,14 @@ inline bool isPolymorphicType(mlir::Type type) {
/// Is this an SSA value type for the value of a Fortran procedure /// Is this an SSA value type for the value of a Fortran procedure
/// designator ? /// designator ?
inline bool isFortranProcedureValue(mlir::Type type) { inline bool isFortranProcedureValue(mlir::Type type) {
return type.isa<fir::BoxProcType>() || return mlir::isa<fir::BoxProcType>(type) ||
(type.isa<mlir::TupleType>() && (mlir::isa<mlir::TupleType>(type) &&
fir::isCharacterProcedureTuple(type, /*acceptRawFunc=*/false)); fir::isCharacterProcedureTuple(type, /*acceptRawFunc=*/false));
} }
/// Is this an SSA value type for the value of a Fortran expression? /// Is this an SSA value type for the value of a Fortran expression?
inline bool isFortranValueType(mlir::Type type) { inline bool isFortranValueType(mlir::Type type) {
return type.isa<hlfir::ExprType>() || fir::isa_trivial(type) || return mlir::isa<hlfir::ExprType>(type) || fir::isa_trivial(type) ||
isFortranProcedureValue(type); isFortranProcedureValue(type);
} }

View File

@ -29,7 +29,9 @@
namespace fir { namespace fir {
/// Return the integer value of a arith::ConstantOp. /// Return the integer value of a arith::ConstantOp.
inline std::int64_t toInt(mlir::arith::ConstantOp cop) { inline std::int64_t toInt(mlir::arith::ConstantOp cop) {
return cop.getValue().cast<mlir::IntegerAttr>().getValue().getSExtValue(); return mlir::cast<mlir::IntegerAttr>(cop.getValue())
.getValue()
.getSExtValue();
} }
// Reconstruct binding tables for dynamic dispatch. // Reconstruct binding tables for dynamic dispatch.

View File

@ -20,7 +20,7 @@ struct OpenMPPointerLikeModel
: public mlir::omp::PointerLikeType::ExternalModel< : public mlir::omp::PointerLikeType::ExternalModel<
OpenMPPointerLikeModel<T>, T> { OpenMPPointerLikeModel<T>, T> {
mlir::Type getElementType(mlir::Type pointer) const { mlir::Type getElementType(mlir::Type pointer) const {
return pointer.cast<T>().getElementType(); return mlir::cast<T>(pointer).getElementType();
} }
}; };
@ -29,7 +29,7 @@ struct OpenACCPointerLikeModel
: public mlir::acc::PointerLikeType::ExternalModel< : public mlir::acc::PointerLikeType::ExternalModel<
OpenACCPointerLikeModel<T>, T> { OpenACCPointerLikeModel<T>, T> {
mlir::Type getElementType(mlir::Type pointer) const { mlir::Type getElementType(mlir::Type pointer) const {
return pointer.cast<T>().getElementType(); return mlir::cast<T>(pointer).getElementType();
} }
}; };

View File

@ -162,7 +162,7 @@ static void genRuntimeInitCharacter(fir::FirOpBuilder &builder,
args.push_back(builder.createConvert(loc, inputTypes[0], box.getAddr())); args.push_back(builder.createConvert(loc, inputTypes[0], box.getAddr()));
args.push_back(builder.createConvert(loc, inputTypes[1], len)); args.push_back(builder.createConvert(loc, inputTypes[1], len));
if (kind == 0) if (kind == 0)
kind = box.getEleTy().cast<fir::CharacterType>().getFKind(); kind = mlir::cast<fir::CharacterType>(box.getEleTy()).getFKind();
args.push_back(builder.createIntegerConstant(loc, inputTypes[2], kind)); args.push_back(builder.createIntegerConstant(loc, inputTypes[2], kind));
int rank = box.rank(); int rank = box.rank();
args.push_back(builder.createIntegerConstant(loc, inputTypes[3], rank)); args.push_back(builder.createIntegerConstant(loc, inputTypes[3], rank));
@ -879,7 +879,7 @@ void Fortran::lower::genDeallocateIfAllocated(
builder.genIfThen(loc, isAllocated) builder.genIfThen(loc, isAllocated)
.genThen([&]() { .genThen([&]() {
if (mlir::Type eleType = box.getEleTy(); if (mlir::Type eleType = box.getEleTy();
eleType.isa<fir::RecordType>() && box.isPolymorphic()) { mlir::isa<fir::RecordType>(eleType) && box.isPolymorphic()) {
mlir::Value declaredTypeDesc = builder.create<fir::TypeDescOp>( mlir::Value declaredTypeDesc = builder.create<fir::TypeDescOp>(
loc, mlir::TypeAttr::get(eleType)); loc, mlir::TypeAttr::get(eleType));
genDeallocateBox(converter, box, loc, sym, declaredTypeDesc); genDeallocateBox(converter, box, loc, sym, declaredTypeDesc);
@ -918,7 +918,7 @@ void Fortran::lower::genDeallocateStmt(
mlir::Value declaredTypeDesc = {}; mlir::Value declaredTypeDesc = {};
if (box.isPolymorphic()) { if (box.isPolymorphic()) {
mlir::Type eleType = box.getEleTy(); mlir::Type eleType = box.getEleTy();
if (eleType.isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(eleType))
if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec = if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
symbol.GetType()->AsDerived()) { symbol.GetType()->AsDerived()) {
declaredTypeDesc = declaredTypeDesc =
@ -1007,7 +1007,7 @@ createMutableProperties(Fortran::lower::AbstractConverter &converter,
fir::MutableProperties mutableProperties; fir::MutableProperties mutableProperties;
std::string name = converter.mangleName(sym); std::string name = converter.mangleName(sym);
mlir::Type baseAddrTy = converter.genType(sym); mlir::Type baseAddrTy = converter.genType(sym);
if (auto boxType = baseAddrTy.dyn_cast<fir::BaseBoxType>()) if (auto boxType = mlir::dyn_cast<fir::BaseBoxType>(baseAddrTy))
baseAddrTy = boxType.getEleTy(); baseAddrTy = boxType.getEleTy();
// Allocate and set a variable to hold the address. // Allocate and set a variable to hold the address.
// It will be set to null in setUnallocatedStatus. // It will be set to null in setUnallocatedStatus.
@ -1032,9 +1032,9 @@ createMutableProperties(Fortran::lower::AbstractConverter &converter,
mlir::Type eleTy = baseAddrTy; mlir::Type eleTy = baseAddrTy;
if (auto newTy = fir::dyn_cast_ptrEleTy(eleTy)) if (auto newTy = fir::dyn_cast_ptrEleTy(eleTy))
eleTy = newTy; eleTy = newTy;
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
eleTy = seqTy.getEleTy(); eleTy = seqTy.getEleTy();
if (auto record = eleTy.dyn_cast<fir::RecordType>()) if (auto record = mlir::dyn_cast<fir::RecordType>(eleTy))
if (record.getNumLenParams() != 0) if (record.getNumLenParams() != 0)
TODO(loc, "deferred length type parameters."); TODO(loc, "deferred length type parameters.");
if (fir::isa_char(eleTy) && nonDeferredParams.empty()) { if (fir::isa_char(eleTy) && nonDeferredParams.empty()) {

View File

@ -683,7 +683,7 @@ public:
auto if_builder = builder->genIfThenElse(loc, isAllocated); auto if_builder = builder->genIfThenElse(loc, isAllocated);
if_builder.genThen([&]() { if_builder.genThen([&]() {
std::string name = mangleName(sym) + ".alloc"; std::string name = mangleName(sym) + ".alloc";
if (auto seqTy = symType.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(symType)) {
fir::ExtendedValue read = fir::factory::genMutableBoxRead( fir::ExtendedValue read = fir::factory::genMutableBoxRead(
*builder, loc, box, /*mayBePolymorphic=*/false); *builder, loc, box, /*mayBePolymorphic=*/false);
if (auto read_arr_box = read.getBoxOf<fir::ArrayBoxValue>()) { if (auto read_arr_box = read.getBoxOf<fir::ArrayBoxValue>()) {
@ -1132,7 +1132,7 @@ private:
fir::ExtendedValue lhs = symBoxToExtendedValue(lhs_sb); fir::ExtendedValue lhs = symBoxToExtendedValue(lhs_sb);
fir::ExtendedValue rhs = symBoxToExtendedValue(rhs_sb); fir::ExtendedValue rhs = symBoxToExtendedValue(rhs_sb);
mlir::Type symType = genType(sym); mlir::Type symType = genType(sym);
if (auto seqTy = symType.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(symType)) {
Fortran::lower::StatementContext stmtCtx; Fortran::lower::StatementContext stmtCtx;
Fortran::lower::createSomeArrayAssignment(*this, lhs, rhs, localSymbols, Fortran::lower::createSomeArrayAssignment(*this, lhs, rhs, localSymbols,
stmtCtx); stmtCtx);
@ -1355,7 +1355,7 @@ private:
return; return;
} }
mlir::Type selectorType = selector.getType(); mlir::Type selectorType = selector.getType();
bool realSelector = selectorType.isa<mlir::FloatType>(); bool realSelector = mlir::isa<mlir::FloatType>(selectorType);
assert((inArithmeticIfContext || !realSelector) && "invalid selector type"); assert((inArithmeticIfContext || !realSelector) && "invalid selector type");
mlir::Value zero; mlir::Value zero;
if (inArithmeticIfContext) if (inArithmeticIfContext)
@ -1630,7 +1630,7 @@ private:
stmtCtx); stmtCtx);
stmtCtx.finalizeAndReset(); stmtCtx.finalizeAndReset();
// Raise an exception if REAL expr is a NaN. // Raise an exception if REAL expr is a NaN.
if (expr.getType().isa<mlir::FloatType>()) if (mlir::isa<mlir::FloatType>(expr.getType()))
expr = builder->create<mlir::arith::AddFOp>(toLocation(), expr, expr); expr = builder->create<mlir::arith::AddFOp>(toLocation(), expr, expr);
// An empty valueList indicates to genMultiwayBranch that the branch is // An empty valueList indicates to genMultiwayBranch that the branch is
// an ArithmeticIfStmt that has two branches on value 0 or 0.0. // an ArithmeticIfStmt that has two branches on value 0 or 0.0.
@ -2807,7 +2807,7 @@ private:
auto caseValue = valueList.begin(); auto caseValue = valueList.begin();
auto caseBlock = blockList.begin(); auto caseBlock = blockList.begin();
for (mlir::Attribute attr : attrList) { for (mlir::Attribute attr : attrList) {
if (attr.isa<mlir::UnitAttr>()) { if (mlir::isa<mlir::UnitAttr>(attr)) {
genBranch(*caseBlock++); genBranch(*caseBlock++);
break; break;
} }
@ -2825,7 +2825,7 @@ private:
rhsVal.second); rhsVal.second);
}; };
mlir::Block *newBlock = insertBlock(*caseBlock); mlir::Block *newBlock = insertBlock(*caseBlock);
if (attr.isa<fir::ClosedIntervalAttr>()) { if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
mlir::Block *newBlock2 = insertBlock(*caseBlock); mlir::Block *newBlock2 = insertBlock(*caseBlock);
mlir::Value cond = mlir::Value cond =
genCond(*caseValue++, mlir::arith::CmpIPredicate::sge); genCond(*caseValue++, mlir::arith::CmpIPredicate::sge);
@ -2838,12 +2838,12 @@ private:
continue; continue;
} }
mlir::arith::CmpIPredicate pred; mlir::arith::CmpIPredicate pred;
if (attr.isa<fir::PointIntervalAttr>()) { if (mlir::isa<fir::PointIntervalAttr>(attr)) {
pred = mlir::arith::CmpIPredicate::eq; pred = mlir::arith::CmpIPredicate::eq;
} else if (attr.isa<fir::LowerBoundAttr>()) { } else if (mlir::isa<fir::LowerBoundAttr>(attr)) {
pred = mlir::arith::CmpIPredicate::sge; pred = mlir::arith::CmpIPredicate::sge;
} else { } else {
assert(attr.isa<fir::UpperBoundAttr>() && "unexpected predicate"); assert(mlir::isa<fir::UpperBoundAttr>(attr) && "unexpected predicate");
pred = mlir::arith::CmpIPredicate::sle; pred = mlir::arith::CmpIPredicate::sle;
} }
mlir::Value cond = genCond(*caseValue++, pred); mlir::Value cond = genCond(*caseValue++, pred);
@ -3105,7 +3105,7 @@ private:
bool isPointer = fir::isPointerType(baseTy); bool isPointer = fir::isPointerType(baseTy);
bool isAllocatable = fir::isAllocatableType(baseTy); bool isAllocatable = fir::isAllocatableType(baseTy);
bool isArray = bool isArray =
fir::dyn_cast_ptrOrBoxEleTy(baseTy).isa<fir::SequenceType>(); mlir::isa<fir::SequenceType>(fir::dyn_cast_ptrOrBoxEleTy(baseTy));
const fir::BoxValue *selectorBox = selector.getBoxOf<fir::BoxValue>(); const fir::BoxValue *selectorBox = selector.getBoxOf<fir::BoxValue>();
if (std::holds_alternative<Fortran::parser::Default>(guard.u)) { if (std::holds_alternative<Fortran::parser::Default>(guard.u)) {
// CLASS DEFAULT // CLASS DEFAULT
@ -3114,12 +3114,12 @@ private:
std::get_if<Fortran::parser::TypeSpec>(&guard.u)) { std::get_if<Fortran::parser::TypeSpec>(&guard.u)) {
// TYPE IS // TYPE IS
fir::ExactTypeAttr attr = fir::ExactTypeAttr attr =
typeGuardAttr.dyn_cast<fir::ExactTypeAttr>(); mlir::dyn_cast<fir::ExactTypeAttr>(typeGuardAttr);
mlir::Value exactValue; mlir::Value exactValue;
mlir::Type addrTy = attr.getType(); mlir::Type addrTy = attr.getType();
if (isArray) { if (isArray) {
auto seqTy = fir::dyn_cast_ptrOrBoxEleTy(baseTy) auto seqTy = mlir::dyn_cast<fir::SequenceType>(
.dyn_cast<fir::SequenceType>(); fir::dyn_cast_ptrOrBoxEleTy(baseTy));
addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType()); addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType());
} }
if (isPointer) if (isPointer)
@ -3141,7 +3141,7 @@ private:
addAssocEntitySymbol(selectorBox->clone(exact)); addAssocEntitySymbol(selectorBox->clone(exact));
} else if (intrinsic->category() == } else if (intrinsic->category() ==
Fortran::common::TypeCategory::Character) { Fortran::common::TypeCategory::Character) {
auto charTy = attr.getType().dyn_cast<fir::CharacterType>(); auto charTy = mlir::dyn_cast<fir::CharacterType>(attr.getType());
mlir::Value charLen = mlir::Value charLen =
fir::factory::CharacterExprHelper(*builder, loc) fir::factory::CharacterExprHelper(*builder, loc)
.readLengthFromBox(fir::getBase(selector), charTy); .readLengthFromBox(fir::getBase(selector), charTy);
@ -3158,11 +3158,12 @@ private:
} else if (std::holds_alternative<Fortran::parser::DerivedTypeSpec>( } else if (std::holds_alternative<Fortran::parser::DerivedTypeSpec>(
guard.u)) { guard.u)) {
// CLASS IS // CLASS IS
fir::SubclassAttr attr = typeGuardAttr.dyn_cast<fir::SubclassAttr>(); fir::SubclassAttr attr =
mlir::dyn_cast<fir::SubclassAttr>(typeGuardAttr);
mlir::Type addrTy = attr.getType(); mlir::Type addrTy = attr.getType();
if (isArray) { if (isArray) {
auto seqTy = fir::dyn_cast_ptrOrBoxEleTy(baseTy) auto seqTy = mlir::dyn_cast<fir::SequenceType>(
.dyn_cast<fir::SequenceType>(); fir::dyn_cast_ptrOrBoxEleTy(baseTy));
addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType()); addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType());
} }
if (isPointer) if (isPointer)
@ -4157,7 +4158,7 @@ private:
} else if (isDerivedCategory(lhsType->category())) { } else if (isDerivedCategory(lhsType->category())) {
// Handle parent component. // Handle parent component.
if (Fortran::lower::isParentComponent(assign.lhs)) { if (Fortran::lower::isParentComponent(assign.lhs)) {
if (!fir::getBase(lhs).getType().isa<fir::BaseBoxType>()) if (!mlir::isa<fir::BaseBoxType>(fir::getBase(lhs).getType()))
lhs = fir::getBase(builder->createBox(loc, lhs)); lhs = fir::getBase(builder->createBox(loc, lhs));
lhs = Fortran::lower::updateBoxForParentComponent(*this, lhs, lhs = Fortran::lower::updateBoxForParentComponent(*this, lhs,
assign.lhs); assign.lhs);
@ -5508,7 +5509,7 @@ Fortran::lower::LoweringBridge::LoweringBridge(
default: default:
break; break;
} }
if (!diag.getLocation().isa<mlir::UnknownLoc>()) if (!mlir::isa<mlir::UnknownLoc>(diag.getLocation()))
os << diag.getLocation() << ": "; os << diag.getLocation() << ": ";
os << diag << '\n'; os << diag << '\n';
os.flush(); os.flush();

View File

@ -1182,7 +1182,7 @@ private:
Property prop = Property::BaseAddress; Property prop = Property::BaseAddress;
if (isValueAttr) { if (isValueAttr) {
bool isBuiltinCptrType = fir::isa_builtin_cptr_type(type); bool isBuiltinCptrType = fir::isa_builtin_cptr_type(type);
if (isBindC || (!type.isa<fir::SequenceType>() && if (isBindC || (!mlir::isa<fir::SequenceType>(type) &&
!obj.attrs.test(Attrs::Optional) && !obj.attrs.test(Attrs::Optional) &&
(dynamicType.category() != (dynamicType.category() !=
Fortran::common::TypeCategory::Derived || Fortran::common::TypeCategory::Derived ||
@ -1190,7 +1190,7 @@ private:
passBy = PassEntityBy::Value; passBy = PassEntityBy::Value;
prop = Property::Value; prop = Property::Value;
if (isBuiltinCptrType) { if (isBuiltinCptrType) {
auto recTy = type.dyn_cast<fir::RecordType>(); auto recTy = mlir::dyn_cast<fir::RecordType>(type);
mlir::Type fieldTy = recTy.getTypeList()[0].second; mlir::Type fieldTy = recTy.getTypeList()[0].second;
passType = fir::ReferenceType::get(fieldTy); passType = fir::ReferenceType::get(fieldTy);
} else { } else {
@ -1714,7 +1714,7 @@ mlir::Type Fortran::lower::getDummyProcedureType(
} }
bool Fortran::lower::isCPtrArgByValueType(mlir::Type ty) { bool Fortran::lower::isCPtrArgByValueType(mlir::Type ty) {
return ty.isa<fir::ReferenceType>() && return mlir::isa<fir::ReferenceType>(ty) &&
fir::isa_integer(fir::unwrapRefType(ty)); fir::isa_integer(fir::unwrapRefType(ty));
} }

View File

@ -336,7 +336,7 @@ public:
if (!extent) if (!extent)
extent = builder.createIntegerConstant(loc, builder.getIndexType(), 0); extent = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
if (missingLengthParameters) { if (missingLengthParameters) {
if (declaredType.getEleTy().isa<fir::CharacterType>()) if (mlir::isa<fir::CharacterType>(declaredType.getEleTy()))
emboxLengths.push_back(builder.createIntegerConstant( emboxLengths.push_back(builder.createIntegerConstant(
loc, builder.getCharacterLengthType(), 0)); loc, builder.getCharacterLengthType(), 0));
else else
@ -357,7 +357,7 @@ public:
bool useSimplePushRuntime(hlfir::Entity value) { bool useSimplePushRuntime(hlfir::Entity value) {
return value.isScalar() && return value.isScalar() &&
!arrayConstructorElementType.isa<fir::CharacterType>() && !mlir::isa<fir::CharacterType>(arrayConstructorElementType) &&
!fir::isRecordWithAllocatableMember(arrayConstructorElementType) && !fir::isRecordWithAllocatableMember(arrayConstructorElementType) &&
!fir::isRecordWithTypeParameters(arrayConstructorElementType); !fir::isRecordWithTypeParameters(arrayConstructorElementType);
} }
@ -370,7 +370,7 @@ public:
auto [addrExv, cleanUp] = hlfir::convertToAddress( auto [addrExv, cleanUp] = hlfir::convertToAddress(
loc, builder, value, arrayConstructorElementType); loc, builder, value, arrayConstructorElementType);
mlir::Value addr = fir::getBase(addrExv); mlir::Value addr = fir::getBase(addrExv);
if (addr.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(addr.getType()))
addr = builder.create<fir::BoxAddrOp>(loc, addr); addr = builder.create<fir::BoxAddrOp>(loc, addr);
fir::runtime::genPushArrayConstructorSimpleScalar( fir::runtime::genPushArrayConstructorSimpleScalar(
loc, builder, arrayConstructorVector, addr); loc, builder, arrayConstructorVector, addr);
@ -564,7 +564,7 @@ struct LengthAndTypeCollector<Character<Kind>> {
/// lowering an ac-value and must be delayed? /// lowering an ac-value and must be delayed?
static bool missingLengthParameters(mlir::Type elementType, static bool missingLengthParameters(mlir::Type elementType,
llvm::ArrayRef<mlir::Value> lengths) { llvm::ArrayRef<mlir::Value> lengths) {
return (elementType.isa<fir::CharacterType>() || return (mlir::isa<fir::CharacterType>(elementType) ||
fir::isRecordWithTypeParameters(elementType)) && fir::isRecordWithTypeParameters(elementType)) &&
lengths.empty(); lengths.empty();
} }
@ -702,7 +702,8 @@ static ArrayCtorLoweringStrategy selectArrayCtorLoweringStrategy(
// Based on what was gathered and the result of the analysis, select and // Based on what was gathered and the result of the analysis, select and
// instantiate the right lowering strategy for the array constructor. // instantiate the right lowering strategy for the array constructor.
if (!extent || needToEvaluateOneExprToGetLengthParameters || if (!extent || needToEvaluateOneExprToGetLengthParameters ||
analysis.anyArrayExpr || declaredType.getEleTy().isa<fir::RecordType>()) analysis.anyArrayExpr ||
mlir::isa<fir::RecordType>(declaredType.getEleTy()))
return RuntimeTempStrategy( return RuntimeTempStrategy(
loc, builder, stmtCtx, symMap, declaredType, loc, builder, stmtCtx, symMap, declaredType,
extent ? std::optional<mlir::Value>(extent) : std::nullopt, lengths, extent ? std::optional<mlir::Value>(extent) : std::nullopt, lengths,

View File

@ -49,15 +49,15 @@ static fir::ExtendedValue toExtendedValue(mlir::Location loc, mlir::Value base,
llvm::ArrayRef<mlir::Value> extents, llvm::ArrayRef<mlir::Value> extents,
llvm::ArrayRef<mlir::Value> lengths) { llvm::ArrayRef<mlir::Value> lengths) {
mlir::Type type = base.getType(); mlir::Type type = base.getType();
if (type.isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(type))
return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents); return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents);
type = fir::unwrapRefType(type); type = fir::unwrapRefType(type);
if (type.isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(type))
return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {}); return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {});
if (auto seqTy = type.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type)) {
if (seqTy.getDimension() != extents.size()) if (seqTy.getDimension() != extents.size())
fir::emitFatalError(loc, "incorrect number of extents for array"); fir::emitFatalError(loc, "incorrect number of extents for array");
if (seqTy.getEleTy().isa<fir::CharacterType>()) { if (mlir::isa<fir::CharacterType>(seqTy.getEleTy())) {
if (lengths.empty()) if (lengths.empty())
fir::emitFatalError(loc, "missing length for character"); fir::emitFatalError(loc, "missing length for character");
assert(lengths.size() == 1); assert(lengths.size() == 1);
@ -65,7 +65,7 @@ static fir::ExtendedValue toExtendedValue(mlir::Location loc, mlir::Value base,
} }
return fir::ArrayBoxValue(base, extents); return fir::ArrayBoxValue(base, extents);
} }
if (type.isa<fir::CharacterType>()) { if (mlir::isa<fir::CharacterType>(type)) {
if (lengths.empty()) if (lengths.empty())
fir::emitFatalError(loc, "missing length for character"); fir::emitFatalError(loc, "missing length for character");
assert(lengths.size() == 1); assert(lengths.size() == 1);
@ -193,7 +193,7 @@ static mlir::Value remapActualToDummyDescriptor(
llvm::SmallVector<mlir::Value> lengths; llvm::SmallVector<mlir::Value> lengths;
mlir::Type dummyBoxType = caller.getDummyArgumentType(arg); mlir::Type dummyBoxType = caller.getDummyArgumentType(arg);
mlir::Type dummyBaseType = fir::unwrapPassByRefType(dummyBoxType); mlir::Type dummyBaseType = fir::unwrapPassByRefType(dummyBoxType);
if (dummyBaseType.isa<fir::SequenceType>()) if (mlir::isa<fir::SequenceType>(dummyBaseType))
caller.walkDummyArgumentExtents( caller.walkDummyArgumentExtents(
arg, [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) { arg, [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
extents.emplace_back(lowerSpecExpr(e, isAssumedSizeExtent)); extents.emplace_back(lowerSpecExpr(e, isAssumedSizeExtent));
@ -338,7 +338,7 @@ std::pair<fir::ExtendedValue, bool> Fortran::lower::genCallOpAndResult(
if (!caller.callerAllocateResult()) if (!caller.callerAllocateResult())
return {}; return {};
mlir::Type type = caller.getResultStorageType(); mlir::Type type = caller.getResultStorageType();
if (type.isa<fir::SequenceType>()) if (mlir::isa<fir::SequenceType>(type))
caller.walkResultExtents( caller.walkResultExtents(
[&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) { [&](const Fortran::lower::SomeExpr &e, bool isAssumedSizeExtent) {
assert(!isAssumedSizeExtent && "result cannot be assumed-size"); assert(!isAssumedSizeExtent && "result cannot be assumed-size");
@ -353,7 +353,7 @@ std::pair<fir::ExtendedValue, bool> Fortran::lower::genCallOpAndResult(
// Result length parameters should not be provided to box storage // Result length parameters should not be provided to box storage
// allocation and save_results, but they are still useful information to // allocation and save_results, but they are still useful information to
// keep in the ExtendedValue if non-deferred. // keep in the ExtendedValue if non-deferred.
if (!type.isa<fir::BoxType>()) { if (!mlir::isa<fir::BoxType>(type)) {
if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) { if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) {
// Calling an assumed length function. This is only possible if this // Calling an assumed length function. This is only possible if this
// is a call to a character dummy procedure. // is a call to a character dummy procedure.
@ -478,7 +478,7 @@ std::pair<fir::ExtendedValue, bool> Fortran::lower::genCallOpAndResult(
// FIR. // FIR.
if (funcPointer) { if (funcPointer) {
operands.push_back( operands.push_back(
funcPointer.getType().isa<fir::BoxProcType>() mlir::isa<fir::BoxProcType>(funcPointer.getType())
? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer) ? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer)
: builder.createConvert(loc, funcType, funcPointer)); : builder.createConvert(loc, funcType, funcPointer));
} }
@ -492,8 +492,8 @@ std::pair<fir::ExtendedValue, bool> Fortran::lower::genCallOpAndResult(
// arguments of any type and vice versa. // arguments of any type and vice versa.
mlir::Value cast; mlir::Value cast;
auto *context = builder.getContext(); auto *context = builder.getContext();
if (snd.isa<fir::BoxProcType>() && if (mlir::isa<fir::BoxProcType>(snd) &&
fst.getType().isa<mlir::FunctionType>()) { mlir::isa<mlir::FunctionType>(fst.getType())) {
auto funcTy = auto funcTy =
mlir::FunctionType::get(context, std::nullopt, std::nullopt); mlir::FunctionType::get(context, std::nullopt, std::nullopt);
auto boxProcTy = builder.getBoxProcType(funcTy); auto boxProcTy = builder.getBoxProcType(funcTy);
@ -734,9 +734,9 @@ std::pair<fir::ExtendedValue, bool> Fortran::lower::genCallOpAndResult(
// Call a BIND(C) function that return a char. // Call a BIND(C) function that return a char.
if (caller.characterize().IsBindC() && if (caller.characterize().IsBindC() &&
funcType.getResults()[0].isa<fir::CharacterType>()) { mlir::isa<fir::CharacterType>(funcType.getResults()[0])) {
fir::CharacterType charTy = fir::CharacterType charTy =
funcType.getResults()[0].dyn_cast<fir::CharacterType>(); mlir::dyn_cast<fir::CharacterType>(funcType.getResults()[0]);
mlir::Value len = builder.createIntegerConstant( mlir::Value len = builder.createIntegerConstant(
loc, builder.getCharacterLengthType(), charTy.getLen()); loc, builder.getCharacterLengthType(), charTy.getLen());
return {fir::CharBoxValue{callResult, len}, /*resultIsFinalized=*/false}; return {fir::CharBoxValue{callResult, len}, /*resultIsFinalized=*/false};
@ -890,7 +890,7 @@ extendedValueToHlfirEntity(mlir::Location loc, fir::FirOpBuilder &builder,
mlir::Type firBaseTy = firBase.getType(); mlir::Type firBaseTy = firBase.getType();
if (fir::isa_trivial(firBaseTy)) if (fir::isa_trivial(firBaseTy))
return hlfir::EntityWithAttributes{firBase}; return hlfir::EntityWithAttributes{firBase};
if (auto charTy = firBase.getType().dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(firBase.getType())) {
// CHAR() intrinsic and BIND(C) procedures returning CHARACTER(1) // CHAR() intrinsic and BIND(C) procedures returning CHARACTER(1)
// are lowered to a fir.char<kind,1> that is not in memory. // are lowered to a fir.char<kind,1> that is not in memory.
// This tends to cause a lot of bugs because the rest of the // This tends to cause a lot of bugs because the rest of the
@ -1061,7 +1061,7 @@ static hlfir::Entity fixProcedureDummyMismatch(mlir::Location loc,
fir::FirOpBuilder &builder, fir::FirOpBuilder &builder,
hlfir::Entity actual, hlfir::Entity actual,
mlir::Type dummyType) { mlir::Type dummyType) {
if (actual.getType().isa<fir::BoxProcType>() && if (mlir::isa<fir::BoxProcType>(actual.getType()) &&
fir::isCharacterProcedureTuple(dummyType)) { fir::isCharacterProcedureTuple(dummyType)) {
mlir::Value length = mlir::Value length =
builder.create<fir::UndefOp>(loc, builder.getCharacterLengthType()); builder.create<fir::UndefOp>(loc, builder.getCharacterLengthType());
@ -1070,7 +1070,7 @@ static hlfir::Entity fixProcedureDummyMismatch(mlir::Location loc,
return hlfir::Entity{tuple}; return hlfir::Entity{tuple};
} }
assert(fir::isCharacterProcedureTuple(actual.getType()) && assert(fir::isCharacterProcedureTuple(actual.getType()) &&
dummyType.isa<fir::BoxProcType>() && mlir::isa<fir::BoxProcType>(dummyType) &&
"unsupported dummy procedure mismatch with the actual argument"); "unsupported dummy procedure mismatch with the actual argument");
mlir::Value boxProc = fir::factory::extractCharacterProcedureTuple( mlir::Value boxProc = fir::factory::extractCharacterProcedureTuple(
builder, loc, actual, /*openBoxProc=*/false) builder, loc, actual, /*openBoxProc=*/false)
@ -1143,7 +1143,7 @@ static PreparedDummyArgument preparePresentUserCallActualArgument(
assert(actual.isProcedure()); assert(actual.isProcedure());
// Do nothing if this is a procedure argument. It is already a // Do nothing if this is a procedure argument. It is already a
// fir.boxproc/fir.tuple<fir.boxproc, len> as it should. // fir.boxproc/fir.tuple<fir.boxproc, len> as it should.
if (!actual.getType().isa<fir::BoxProcType>() && if (!mlir::isa<fir::BoxProcType>(actual.getType()) &&
actual.getType() != dummyType) actual.getType() != dummyType)
// The actual argument may be a procedure that returns character (a // The actual argument may be a procedure that returns character (a
// fir.tuple<fir.boxproc, len>) while the dummy is not. Extract the tuple // fir.tuple<fir.boxproc, len>) while the dummy is not. Extract the tuple
@ -1164,7 +1164,7 @@ static PreparedDummyArgument preparePresentUserCallActualArgument(
// dynamic type matters to determine the contiguity. // dynamic type matters to determine the contiguity.
const bool mustSetDynamicTypeToDummyType = const bool mustSetDynamicTypeToDummyType =
passingPolymorphicToNonPolymorphic && passingPolymorphicToNonPolymorphic &&
(actual.isArray() || dummyType.isa<fir::BaseBoxType>()); (actual.isArray() || mlir::isa<fir::BaseBoxType>(dummyType));
// The simple contiguity of the actual is "lost" when passing a polymorphic // The simple contiguity of the actual is "lost" when passing a polymorphic
// to a non polymorphic entity because the dummy dynamic type matters for // to a non polymorphic entity because the dummy dynamic type matters for
@ -1236,7 +1236,7 @@ static PreparedDummyArgument preparePresentUserCallActualArgument(
preparedDummy.pushExprAssociateCleanUp(associate); preparedDummy.pushExprAssociateCleanUp(associate);
} else if (mustDoCopyInOut) { } else if (mustDoCopyInOut) {
// Copy-in non contiguous variables. // Copy-in non contiguous variables.
assert(entity.getType().isa<fir::BaseBoxType>() && assert(mlir::isa<fir::BaseBoxType>(entity.getType()) &&
"expect non simply contiguous variables to be boxes"); "expect non simply contiguous variables to be boxes");
if (actualIsAssumedRank) if (actualIsAssumedRank)
TODO(loc, "copy-in and copy-out of assumed-rank arguments"); TODO(loc, "copy-in and copy-out of assumed-rank arguments");
@ -1294,13 +1294,14 @@ static PreparedDummyArgument preparePresentUserCallActualArgument(
// Step 3: now that the dummy argument storage has been prepared, package // Step 3: now that the dummy argument storage has been prepared, package
// it according to the interface. // it according to the interface.
mlir::Value addr; mlir::Value addr;
if (dummyTypeWithActualRank.isa<fir::BoxCharType>()) { if (mlir::isa<fir::BoxCharType>(dummyTypeWithActualRank)) {
addr = hlfir::genVariableBoxChar(loc, builder, entity); addr = hlfir::genVariableBoxChar(loc, builder, entity);
} else if (dummyTypeWithActualRank.isa<fir::BaseBoxType>()) { } else if (mlir::isa<fir::BaseBoxType>(dummyTypeWithActualRank)) {
entity = hlfir::genVariableBox(loc, builder, entity); entity = hlfir::genVariableBox(loc, builder, entity);
// Ensures the box has the right attributes and that it holds an // Ensures the box has the right attributes and that it holds an
// addendum if needed. // addendum if needed.
fir::BaseBoxType actualBoxType = entity.getType().cast<fir::BaseBoxType>(); fir::BaseBoxType actualBoxType =
mlir::cast<fir::BaseBoxType>(entity.getType());
mlir::Type boxEleType = actualBoxType.getEleTy(); mlir::Type boxEleType = actualBoxType.getEleTy();
// For now, assume it is not OK to pass the allocatable/pointer // For now, assume it is not OK to pass the allocatable/pointer
// descriptor to a non pointer/allocatable dummy. That is a strict // descriptor to a non pointer/allocatable dummy. That is a strict
@ -1567,7 +1568,7 @@ genUserCall(Fortran::lower::PreparedActualArguments &loweredActuals,
// callee side, and it is illegal to use NULL without a MOLD if any // callee side, and it is illegal to use NULL without a MOLD if any
// dummy length parameters are assumed. // dummy length parameters are assumed.
mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy); mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy);
assert(boxTy && boxTy.isa<fir::BaseBoxType>() && assert(boxTy && mlir::isa<fir::BaseBoxType>(boxTy) &&
"must be a fir.box type"); "must be a fir.box type");
mlir::Value boxStorage = mlir::Value boxStorage =
fir::factory::genNullBoxStorage(builder, loc, boxTy); fir::factory::genNullBoxStorage(builder, loc, boxTy);
@ -1635,7 +1636,8 @@ genUserCall(Fortran::lower::PreparedActualArguments &loweredActuals,
caller, callSiteType, callContext.resultType, caller, callSiteType, callContext.resultType,
callContext.isElementalProcWithArrayArgs()); callContext.isElementalProcWithArrayArgs());
// For procedure pointer function result, just return the call. // For procedure pointer function result, just return the call.
if (callContext.resultType && callContext.resultType->isa<fir::BoxProcType>()) if (callContext.resultType &&
mlir::isa<fir::BoxProcType>(*callContext.resultType))
return hlfir::EntityWithAttributes(fir::getBase(result)); return hlfir::EntityWithAttributes(fir::getBase(result));
/// Clean-up associations and copy-in. /// Clean-up associations and copy-in.
@ -2115,9 +2117,9 @@ public:
hlfir::getFortranElementType(*callContext.resultType); hlfir::getFortranElementType(*callContext.resultType);
// Get result length parameters. // Get result length parameters.
llvm::SmallVector<mlir::Value> typeParams; llvm::SmallVector<mlir::Value> typeParams;
if (elementType.isa<fir::CharacterType>() || if (mlir::isa<fir::CharacterType>(elementType) ||
fir::isRecordWithTypeParameters(elementType)) { fir::isRecordWithTypeParameters(elementType)) {
auto charType = elementType.dyn_cast<fir::CharacterType>(); auto charType = mlir::dyn_cast<fir::CharacterType>(elementType);
if (charType && charType.hasConstantLen()) if (charType && charType.hasConstantLen())
typeParams.push_back(builder.createIntegerConstant( typeParams.push_back(builder.createIntegerConstant(
loc, builder.getIndexType(), charType.getLen())); loc, builder.getIndexType(), charType.getLen()));
@ -2523,7 +2525,7 @@ genIntrinsicRef(const Fortran::evaluate::SpecificIntrinsic *intrinsic,
} }
std::optional<hlfir::EntityWithAttributes> result = genHLFIRIntrinsicRefCore( std::optional<hlfir::EntityWithAttributes> result = genHLFIRIntrinsicRefCore(
loweredActuals, intrinsic, argLowering, callContext); loweredActuals, intrinsic, argLowering, callContext);
if (result && result->getType().isa<hlfir::ExprType>()) { if (result && mlir::isa<hlfir::ExprType>(result->getType())) {
fir::FirOpBuilder *bldr = &callContext.getBuilder(); fir::FirOpBuilder *bldr = &callContext.getBuilder();
callContext.stmtCtx.attachCleanup( callContext.stmtCtx.attachCleanup(
[=]() { bldr->create<hlfir::DestroyOp>(loc, *result); }); [=]() { bldr->create<hlfir::DestroyOp>(loc, *result); });

View File

@ -184,8 +184,8 @@ private:
if (!attributeElementType || attributes.empty()) if (!attributeElementType || attributes.empty())
return {}; return {};
assert(symTy.isa<fir::SequenceType>() && "expecting an array global"); assert(mlir::isa<fir::SequenceType>(symTy) && "expecting an array global");
auto arrTy = symTy.cast<fir::SequenceType>(); auto arrTy = mlir::cast<fir::SequenceType>(symTy);
llvm::SmallVector<int64_t> tensorShape(arrTy.getShape()); llvm::SmallVector<int64_t> tensorShape(arrTy.getShape());
std::reverse(tensorShape.begin(), tensorShape.end()); std::reverse(tensorShape.begin(), tensorShape.end());
auto tensorTy = auto tensorTy =
@ -423,14 +423,14 @@ static mlir::Value genStructureComponentInit(
// address field, which ought to be an intptr_t on the target. // address field, which ought to be an intptr_t on the target.
mlir::Value addr = fir::getBase( mlir::Value addr = fir::getBase(
Fortran::lower::genExtAddrInInitializer(converter, loc, expr)); Fortran::lower::genExtAddrInInitializer(converter, loc, expr));
if (addr.getType().isa<fir::BoxProcType>()) if (mlir::isa<fir::BoxProcType>(addr.getType()))
addr = builder.create<fir::BoxAddrOp>(loc, addr); addr = builder.create<fir::BoxAddrOp>(loc, addr);
assert((fir::isa_ref_type(addr.getType()) || assert((fir::isa_ref_type(addr.getType()) ||
addr.getType().isa<mlir::FunctionType>()) && mlir::isa<mlir::FunctionType>(addr.getType())) &&
"expect reference type for address field"); "expect reference type for address field");
assert(fir::isa_derived(componentTy) && assert(fir::isa_derived(componentTy) &&
"expect C_PTR, C_FUNPTR to be a record"); "expect C_PTR, C_FUNPTR to be a record");
auto cPtrRecTy = componentTy.cast<fir::RecordType>(); auto cPtrRecTy = mlir::cast<fir::RecordType>(componentTy);
llvm::StringRef addrFieldName = Fortran::lower::builtin::cptrFieldName; llvm::StringRef addrFieldName = Fortran::lower::builtin::cptrFieldName;
mlir::Type addrFieldTy = cPtrRecTy.getType(addrFieldName); mlir::Type addrFieldTy = cPtrRecTy.getType(addrFieldName);
auto addrField = builder.create<fir::FieldIndexOp>( auto addrField = builder.create<fir::FieldIndexOp>(
@ -460,7 +460,7 @@ static mlir::Value genInlinedStructureCtorLitImpl(
Fortran::lower::AbstractConverter &converter, mlir::Location loc, Fortran::lower::AbstractConverter &converter, mlir::Location loc,
const Fortran::evaluate::StructureConstructor &ctor, mlir::Type type) { const Fortran::evaluate::StructureConstructor &ctor, mlir::Type type) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); fir::FirOpBuilder &builder = converter.getFirOpBuilder();
auto recTy = type.cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(type);
if (!converter.getLoweringOptions().getLowerToHighLevelFIR()) { if (!converter.getLoweringOptions().getLowerToHighLevelFIR()) {
mlir::Value res = builder.create<fir::UndefOp>(loc, recTy); mlir::Value res = builder.create<fir::UndefOp>(loc, recTy);
@ -587,7 +587,7 @@ genInlinedArrayLit(Fortran::lower::AbstractConverter &converter,
} while (con.IncrementSubscripts(subscripts)); } while (con.IncrementSubscripts(subscripts));
} else if constexpr (T::category == Fortran::common::TypeCategory::Derived) { } else if constexpr (T::category == Fortran::common::TypeCategory::Derived) {
do { do {
mlir::Type eleTy = arrayTy.cast<fir::SequenceType>().getEleTy(); mlir::Type eleTy = mlir::cast<fir::SequenceType>(arrayTy).getEleTy();
mlir::Value elementVal = mlir::Value elementVal =
genScalarLit(converter, loc, con.At(subscripts), eleTy, genScalarLit(converter, loc, con.At(subscripts), eleTy,
/*outlineInReadOnlyMemory=*/false); /*outlineInReadOnlyMemory=*/false);
@ -597,7 +597,7 @@ genInlinedArrayLit(Fortran::lower::AbstractConverter &converter,
} else { } else {
llvm::SmallVector<mlir::Attribute> rangeStartIdx; llvm::SmallVector<mlir::Attribute> rangeStartIdx;
uint64_t rangeSize = 0; uint64_t rangeSize = 0;
mlir::Type eleTy = arrayTy.cast<fir::SequenceType>().getEleTy(); mlir::Type eleTy = mlir::cast<fir::SequenceType>(arrayTy).getEleTy();
do { do {
auto getElementVal = [&]() { auto getElementVal = [&]() {
return builder.createConvert(loc, eleTy, return builder.createConvert(loc, eleTy,
@ -620,12 +620,11 @@ genInlinedArrayLit(Fortran::lower::AbstractConverter &converter,
llvm::SmallVector<int64_t> rangeBounds; llvm::SmallVector<int64_t> rangeBounds;
llvm::SmallVector<mlir::Attribute> idx = createIdx(); llvm::SmallVector<mlir::Attribute> idx = createIdx();
for (size_t i = 0; i < idx.size(); ++i) { for (size_t i = 0; i < idx.size(); ++i) {
rangeBounds.push_back(rangeStartIdx[i] rangeBounds.push_back(mlir::cast<mlir::IntegerAttr>(rangeStartIdx[i])
.cast<mlir::IntegerAttr>()
.getValue() .getValue()
.getSExtValue()); .getSExtValue());
rangeBounds.push_back( rangeBounds.push_back(
idx[i].cast<mlir::IntegerAttr>().getValue().getSExtValue()); mlir::cast<mlir::IntegerAttr>(idx[i]).getValue().getSExtValue());
} }
array = builder.create<fir::InsertOnRangeOp>( array = builder.create<fir::InsertOnRangeOp>(
loc, arrayTy, array, getElementVal(), loc, arrayTy, array, getElementVal(),
@ -647,7 +646,7 @@ genOutlineArrayLit(Fortran::lower::AbstractConverter &converter,
mlir::Location loc, mlir::Type arrayTy, mlir::Location loc, mlir::Type arrayTy,
const Fortran::evaluate::Constant<T> &constant) { const Fortran::evaluate::Constant<T> &constant) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type eleTy = arrayTy.cast<fir::SequenceType>().getEleTy(); mlir::Type eleTy = mlir::cast<fir::SequenceType>(arrayTy).getEleTy();
llvm::StringRef globalName = converter.getUniqueLitName( llvm::StringRef globalName = converter.getUniqueLitName(
loc, std::make_unique<Fortran::lower::SomeExpr>(toEvExpr(constant)), loc, std::make_unique<Fortran::lower::SomeExpr>(toEvExpr(constant)),
eleTy); eleTy);

View File

@ -267,7 +267,7 @@ arrayLoadExtValue(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Type ty = fir::applyPathToType(arrTy, path); mlir::Type ty = fir::applyPathToType(arrTy, path);
if (!ty) if (!ty)
fir::emitFatalError(loc, "path does not apply to type"); fir::emitFatalError(loc, "path does not apply to type");
if (!ty.isa<fir::SequenceType>()) { if (!mlir::isa<fir::SequenceType>(ty)) {
if (fir::isa_char(ty)) { if (fir::isa_char(ty)) {
mlir::Value len = newLen; mlir::Value len = newLen;
if (!len) if (!len)
@ -282,7 +282,7 @@ arrayLoadExtValue(fir::FirOpBuilder &builder, mlir::Location loc,
} }
return newBase; return newBase;
} }
arrTy = ty.cast<fir::SequenceType>(); arrTy = mlir::cast<fir::SequenceType>(ty);
} }
auto arrayToExtendedValue = auto arrayToExtendedValue =
@ -412,15 +412,15 @@ static fir::ExtendedValue genLoad(fir::FirOpBuilder &builder,
return addr.match( return addr.match(
[](const fir::CharBoxValue &box) -> fir::ExtendedValue { return box; }, [](const fir::CharBoxValue &box) -> fir::ExtendedValue { return box; },
[&](const fir::PolymorphicValue &p) -> fir::ExtendedValue { [&](const fir::PolymorphicValue &p) -> fir::ExtendedValue {
if (fir::unwrapRefType(fir::getBase(p).getType()) if (mlir::isa<fir::RecordType>(
.isa<fir::RecordType>()) fir::unwrapRefType(fir::getBase(p).getType())))
return p; return p;
mlir::Value load = builder.create<fir::LoadOp>(loc, fir::getBase(p)); mlir::Value load = builder.create<fir::LoadOp>(loc, fir::getBase(p));
return fir::PolymorphicValue(load, p.getSourceBox()); return fir::PolymorphicValue(load, p.getSourceBox());
}, },
[&](const fir::UnboxedValue &v) -> fir::ExtendedValue { [&](const fir::UnboxedValue &v) -> fir::ExtendedValue {
if (fir::unwrapRefType(fir::getBase(v).getType()) if (mlir::isa<fir::RecordType>(
.isa<fir::RecordType>()) fir::unwrapRefType(fir::getBase(v).getType())))
return v; return v;
return builder.create<fir::LoadOp>(loc, fir::getBase(v)); return builder.create<fir::LoadOp>(loc, fir::getBase(v));
}, },
@ -536,8 +536,8 @@ static mlir::Value
createBoxProcCharTuple(Fortran::lower::AbstractConverter &converter, createBoxProcCharTuple(Fortran::lower::AbstractConverter &converter,
mlir::Type argTy, mlir::Value funcAddr, mlir::Type argTy, mlir::Value funcAddr,
mlir::Value charLen) { mlir::Value charLen) {
auto boxTy = auto boxTy = mlir::cast<fir::BoxProcType>(
argTy.cast<mlir::TupleType>().getType(0).cast<fir::BoxProcType>(); mlir::cast<mlir::TupleType>(argTy).getType(0));
mlir::Location loc = converter.getCurrentLocation(); mlir::Location loc = converter.getCurrentLocation();
auto &builder = converter.getFirOpBuilder(); auto &builder = converter.getFirOpBuilder();
@ -549,7 +549,7 @@ createBoxProcCharTuple(Fortran::lower::AbstractConverter &converter,
mlir::Type toTy = boxTy.getEleTy(); mlir::Type toTy = boxTy.getEleTy();
if (fir::isa_ref_type(fromTy)) if (fir::isa_ref_type(fromTy))
funcAddr = builder.createConvert(loc, toTy, funcAddr); funcAddr = builder.createConvert(loc, toTy, funcAddr);
else if (fromTy.isa<fir::BoxProcType>()) else if (mlir::isa<fir::BoxProcType>(fromTy))
funcAddr = builder.create<fir::BoxAddrOp>(loc, toTy, funcAddr); funcAddr = builder.create<fir::BoxAddrOp>(loc, toTy, funcAddr);
auto boxProc = [&]() -> mlir::Value { auto boxProc = [&]() -> mlir::Value {
@ -575,7 +575,7 @@ absentBoxToUnallocatedBox(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value isPresent) { mlir::Value isPresent) {
mlir::Value box = fir::getBase(exv); mlir::Value box = fir::getBase(exv);
mlir::Type boxType = box.getType(); mlir::Type boxType = box.getType();
assert(boxType.isa<fir::BoxType>() && "argument must be a fir.box"); assert(mlir::isa<fir::BoxType>(boxType) && "argument must be a fir.box");
mlir::Value emptyBox = mlir::Value emptyBox =
fir::factory::createUnallocatedBox(builder, loc, boxType, std::nullopt); fir::factory::createUnallocatedBox(builder, loc, boxType, std::nullopt);
auto safeToReadBox = auto safeToReadBox =
@ -915,7 +915,7 @@ public:
if (inInitializer) if (inInitializer)
return Fortran::lower::genInlinedStructureCtorLit(converter, loc, ctor); return Fortran::lower::genInlinedStructureCtorLit(converter, loc, ctor);
mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor)); mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor));
auto recTy = ty.cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(ty);
auto fieldTy = fir::FieldType::get(ty.getContext()); auto fieldTy = fir::FieldType::get(ty.getContext());
mlir::Value res = builder.createTemporary(loc, recTy); mlir::Value res = builder.createTemporary(loc, recTy);
mlir::Value box = builder.createBox(loc, fir::ExtendedValue{res}); mlir::Value box = builder.createBox(loc, fir::ExtendedValue{res});
@ -1172,8 +1172,8 @@ public:
if (!charBox) if (!charBox)
fir::emitFatalError(loc, "expected scalar character"); fir::emitFatalError(loc, "expected scalar character");
mlir::Value charAddr = charBox->getAddr(); mlir::Value charAddr = charBox->getAddr();
auto charType = auto charType = mlir::cast<fir::CharacterType>(
fir::unwrapPassByRefType(charAddr.getType()).cast<fir::CharacterType>(); fir::unwrapPassByRefType(charAddr.getType()));
if (charType.hasConstantLen()) { if (charType.hasConstantLen()) {
// Erase previous constant length from the base type. // Erase previous constant length from the base type.
fir::CharacterType::LenType newLen = fir::CharacterType::unknownLen(); fir::CharacterType::LenType newLen = fir::CharacterType::unknownLen();
@ -1441,7 +1441,7 @@ public:
auto fldTy = fir::FieldType::get(&converter.getMLIRContext()); auto fldTy = fir::FieldType::get(&converter.getMLIRContext());
// FIXME: need to thread the LEN type parameters here. // FIXME: need to thread the LEN type parameters here.
for (const Fortran::evaluate::Component *field : list) { for (const Fortran::evaluate::Component *field : list) {
auto recTy = ty.cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(ty);
const Fortran::semantics::Symbol &sym = getLastSym(*field); const Fortran::semantics::Symbol &sym = getLastSym(*field);
std::string name = converter.getRecordTypeFieldName(sym); std::string name = converter.getRecordTypeFieldName(sym);
coorArgs.push_back(builder.create<fir::FieldIndexOp>( coorArgs.push_back(builder.create<fir::FieldIndexOp>(
@ -1478,7 +1478,7 @@ public:
mlir::Type genSubType(mlir::Type arrTy, unsigned dims) { mlir::Type genSubType(mlir::Type arrTy, unsigned dims) {
mlir::Type unwrapTy = fir::dyn_cast_ptrOrBoxEleTy(arrTy); mlir::Type unwrapTy = fir::dyn_cast_ptrOrBoxEleTy(arrTy);
assert(unwrapTy && "must be a pointer or box type"); assert(unwrapTy && "must be a pointer or box type");
auto seqTy = unwrapTy.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(unwrapTy);
llvm::ArrayRef<int64_t> shape = seqTy.getShape(); llvm::ArrayRef<int64_t> shape = seqTy.getShape();
assert(shape.size() > 0 && "removing columns for sequence sans shape"); assert(shape.size() > 0 && "removing columns for sequence sans shape");
assert(dims <= shape.size() && "removing more columns than exist"); assert(dims <= shape.size() && "removing more columns than exist");
@ -1550,9 +1550,9 @@ public:
} }
mlir::Type eleTy = fir::dyn_cast_ptrOrBoxEleTy(base.getType()); mlir::Type eleTy = fir::dyn_cast_ptrOrBoxEleTy(base.getType());
if (auto classTy = eleTy.dyn_cast<fir::ClassType>()) if (auto classTy = mlir::dyn_cast<fir::ClassType>(eleTy))
eleTy = classTy.getEleTy(); eleTy = classTy.getEleTy();
auto seqTy = eleTy.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(eleTy);
assert(args.size() == seqTy.getDimension()); assert(args.size() == seqTy.getDimension());
mlir::Type ty = builder.getRefType(seqTy.getEleTy()); mlir::Type ty = builder.getRefType(seqTy.getEleTy());
auto addr = builder.create<fir::CoordinateOp>(loc, ty, base, args); auto addr = builder.create<fir::CoordinateOp>(loc, ty, base, args);
@ -1571,7 +1571,7 @@ public:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
mlir::Value addr = fir::getBase(array); mlir::Value addr = fir::getBase(array);
mlir::Type arrTy = fir::dyn_cast_ptrEleTy(addr.getType()); mlir::Type arrTy = fir::dyn_cast_ptrEleTy(addr.getType());
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(eleTy)); mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(eleTy));
mlir::Type refTy = builder.getRefType(eleTy); mlir::Type refTy = builder.getRefType(eleTy);
mlir::Value base = builder.createConvert(loc, seqTy, addr); mlir::Value base = builder.createConvert(loc, seqTy, addr);
@ -1656,7 +1656,7 @@ public:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
mlir::Value addr = fir::getBase(exv); mlir::Value addr = fir::getBase(exv);
mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType()); mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType());
mlir::Type eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); mlir::Type eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
mlir::Type refTy = builder.getRefType(eleTy); mlir::Type refTy = builder.getRefType(eleTy);
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
llvm::SmallVector<mlir::Value> arrayCoorArgs; llvm::SmallVector<mlir::Value> arrayCoorArgs;
@ -1766,8 +1766,9 @@ public:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
ExtValue exv = genBoxArg(expr); ExtValue exv = genBoxArg(expr);
auto exvTy = fir::getBase(exv).getType(); auto exvTy = fir::getBase(exv).getType();
if (exvTy.isa<mlir::FunctionType>()) { if (mlir::isa<mlir::FunctionType>(exvTy)) {
auto boxProcTy = builder.getBoxProcType(exvTy.cast<mlir::FunctionType>()); auto boxProcTy =
builder.getBoxProcType(mlir::cast<mlir::FunctionType>(exvTy));
return builder.create<fir::EmboxProcOp>(loc, boxProcTy, return builder.create<fir::EmboxProcOp>(loc, boxProcTy,
fir::getBase(exv)); fir::getBase(exv));
} }
@ -1861,7 +1862,7 @@ public:
// IS_CONTIGUOUS may require an assumed size TYPE(*) to be passed to // IS_CONTIGUOUS may require an assumed size TYPE(*) to be passed to
// the intrinsic library utility as a fir.box. // the intrinsic library utility as a fir.box.
if (argRules.lowerAs == fir::LowerIntrinsicArgAs::Box && if (argRules.lowerAs == fir::LowerIntrinsicArgAs::Box &&
!fir::getBase(exv).getType().isa<fir::BaseBoxType>()) { !mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType())) {
operands.emplace_back( operands.emplace_back(
fir::factory::createBoxValue(builder, loc, exv)); fir::factory::createBoxValue(builder, loc, exv));
continue; continue;
@ -2005,7 +2006,7 @@ public:
fir::getTypeParams(mold); fir::getTypeParams(mold);
mlir::Value charLen; mlir::Value charLen;
mlir::Type elementType = fir::unwrapSequenceType(type); mlir::Type elementType = fir::unwrapSequenceType(type);
if (auto charType = elementType.dyn_cast<fir::CharacterType>()) { if (auto charType = mlir::dyn_cast<fir::CharacterType>(elementType)) {
charLen = allocMemTypeParams.empty() charLen = allocMemTypeParams.empty()
? fir::factory::readCharLen(builder, loc, mold) ? fir::factory::readCharLen(builder, loc, mold)
: allocMemTypeParams[0]; : allocMemTypeParams[0];
@ -2017,7 +2018,7 @@ public:
mlir::Value temp = builder.create<fir::AllocMemOp>( mlir::Value temp = builder.create<fir::AllocMemOp>(
loc, type, tempName, allocMemTypeParams, extents); loc, type, tempName, allocMemTypeParams, extents);
if (fir::unwrapSequenceType(type).isa<fir::CharacterType>()) if (mlir::isa<fir::CharacterType>(fir::unwrapSequenceType(type)))
return fir::CharArrayBoxValue{temp, charLen, extents}; return fir::CharArrayBoxValue{temp, charLen, extents};
return fir::ArrayBoxValue{temp, extents}; return fir::ArrayBoxValue{temp, extents};
} }
@ -2166,7 +2167,7 @@ public:
// We have to initialize the temp if it may have components // We have to initialize the temp if it may have components
// that need initialization. If there are no components // that need initialization. If there are no components
// requiring initialization, then the call is a no-op. // requiring initialization, then the call is a no-op.
if (getElementTypeOf(temp).isa<fir::RecordType>()) { if (mlir::isa<fir::RecordType>(getElementTypeOf(temp))) {
mlir::Value tempBox = fir::getBase(builder.createBox(loc, temp)); mlir::Value tempBox = fir::getBase(builder.createBox(loc, temp));
fir::runtime::genDerivedTypeInitialize(builder, loc, tempBox); fir::runtime::genDerivedTypeInitialize(builder, loc, tempBox);
} }
@ -2312,7 +2313,7 @@ public:
if (!copyOutPair.restrictCopyAndFreeAtRuntime) { if (!copyOutPair.restrictCopyAndFreeAtRuntime) {
doCopyOut(); doCopyOut();
if (fir::getElementTypeOf(copyOutPair.temp).isa<fir::RecordType>()) { if (mlir::isa<fir::RecordType>(fir::getElementTypeOf(copyOutPair.temp))) {
// Destroy components of the temporary (if any). // Destroy components of the temporary (if any).
// If there are no components requiring destruction, then the call // If there are no components requiring destruction, then the call
// is a no-op. // is a no-op.
@ -2330,7 +2331,8 @@ public:
builder.genIfThen(loc, *copyOutPair.restrictCopyAndFreeAtRuntime) builder.genIfThen(loc, *copyOutPair.restrictCopyAndFreeAtRuntime)
.genThen([&]() { .genThen([&]() {
doCopyOut(); doCopyOut();
if (fir::getElementTypeOf(copyOutPair.temp).isa<fir::RecordType>()) { if (mlir::isa<fir::RecordType>(
fir::getElementTypeOf(copyOutPair.temp))) {
// Destroy components of the temporary (if any). // Destroy components of the temporary (if any).
// If there are no components requiring destruction, then the call // If there are no components requiring destruction, then the call
// is a no-op. // is a no-op.
@ -2381,7 +2383,7 @@ public:
mlir::Value actualArgBase = fir::getBase(actualArg); mlir::Value actualArgBase = fir::getBase(actualArg);
mlir::Value isPresent = builder.create<fir::IsPresentOp>( mlir::Value isPresent = builder.create<fir::IsPresentOp>(
loc, builder.getI1Type(), actualArgBase); loc, builder.getI1Type(), actualArgBase);
if (!actualArgBase.getType().isa<fir::BoxType>()) if (!mlir::isa<fir::BoxType>(actualArgBase.getType()))
return {actualArg, isPresent}; return {actualArg, isPresent};
ExtValue safeToReadBox = ExtValue safeToReadBox =
absentBoxToUnallocatedBox(builder, loc, actualArg, isPresent); absentBoxToUnallocatedBox(builder, loc, actualArg, isPresent);
@ -2408,7 +2410,7 @@ public:
fir::getAdaptToByRefAttr(builder)}); fir::getAdaptToByRefAttr(builder)});
return fir::CharBoxValue{temp, len}; return fir::CharBoxValue{temp, len};
} }
assert((fir::isa_trivial(type) || type.isa<fir::RecordType>()) && assert((fir::isa_trivial(type) || mlir::isa<fir::RecordType>(type)) &&
"must be simple scalar"); "must be simple scalar");
return builder.createTemporary(loc, type, return builder.createTemporary(loc, type,
llvm::ArrayRef<mlir::NamedAttribute>{ llvm::ArrayRef<mlir::NamedAttribute>{
@ -2585,7 +2587,7 @@ public:
// callee side, and it is illegal to use NULL without a MOLD if any // callee side, and it is illegal to use NULL without a MOLD if any
// dummy length parameters are assumed. // dummy length parameters are assumed.
mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy); mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy);
assert(boxTy && boxTy.isa<fir::BaseBoxType>() && assert(boxTy && mlir::isa<fir::BaseBoxType>(boxTy) &&
"must be a fir.box type"); "must be a fir.box type");
mlir::Value boxStorage = builder.createTemporary(loc, boxTy); mlir::Value boxStorage = builder.createTemporary(loc, boxTy);
mlir::Value nullBox = fir::factory::createUnallocatedBox( mlir::Value nullBox = fir::factory::createUnallocatedBox(
@ -2643,10 +2645,11 @@ public:
// If a character procedure was passed instead, handle the // If a character procedure was passed instead, handle the
// mismatch. // mismatch.
auto funcTy = auto funcTy =
x.getAddr().getType().dyn_cast<mlir::FunctionType>(); mlir::dyn_cast<mlir::FunctionType>(x.getAddr().getType());
if (funcTy && funcTy.getNumResults() == 1 && if (funcTy && funcTy.getNumResults() == 1 &&
funcTy.getResult(0).isa<fir::BoxCharType>()) { mlir::isa<fir::BoxCharType>(funcTy.getResult(0))) {
auto boxTy = funcTy.getResult(0).cast<fir::BoxCharType>(); auto boxTy =
mlir::cast<fir::BoxCharType>(funcTy.getResult(0));
mlir::Value ref = builder.createConvert( mlir::Value ref = builder.createConvert(
loc, builder.getRefType(boxTy.getEleTy()), x.getAddr()); loc, builder.getRefType(boxTy.getEleTy()), x.getAddr());
auto len = builder.create<fir::UndefOp>( auto len = builder.create<fir::UndefOp>(
@ -2667,7 +2670,7 @@ public:
// free-casting the base address to be a !fir.char reference and // free-casting the base address to be a !fir.char reference and
// setting the LEN argument to undefined. What could go wrong? // setting the LEN argument to undefined. What could go wrong?
auto dataPtr = fir::getBase(x); auto dataPtr = fir::getBase(x);
assert(!dataPtr.getType().template isa<fir::BoxType>()); assert(!mlir::isa<fir::BoxType>(dataPtr.getType()));
return builder.convertWithSemantics( return builder.convertWithSemantics(
loc, argTy, dataPtr, loc, argTy, dataPtr,
/*allowCharacterConversion=*/true); /*allowCharacterConversion=*/true);
@ -2742,7 +2745,7 @@ public:
loc, loc,
fir::ClassType::get(mlir::NoneType::get(builder.getContext())), fir::ClassType::get(mlir::NoneType::get(builder.getContext())),
box); box);
} else if (box.getType().isa<fir::BoxType>() && } else if (mlir::isa<fir::BoxType>(box.getType()) &&
fir::isPolymorphicType(argTy)) { fir::isPolymorphicType(argTy)) {
box = builder.create<fir::ReboxOp>(loc, argTy, box, mlir::Value{}, box = builder.create<fir::ReboxOp>(loc, argTy, box, mlir::Value{},
/*slice=*/mlir::Value{}); /*slice=*/mlir::Value{});
@ -2791,7 +2794,7 @@ public:
: builder.createBox(getLoc(), genTempExtAddr(*expr), : builder.createBox(getLoc(), genTempExtAddr(*expr),
fir::isPolymorphicType(argTy), fir::isPolymorphicType(argTy),
fir::isAssumedType(argTy)); fir::isAssumedType(argTy));
if (box.getType().isa<fir::BoxType>() && if (mlir::isa<fir::BoxType>(box.getType()) &&
fir::isPolymorphicType(argTy) && !fir::isAssumedType(argTy)) { fir::isPolymorphicType(argTy) && !fir::isAssumedType(argTy)) {
mlir::Type actualTy = argTy; mlir::Type actualTy = argTy;
if (Fortran::lower::isParentComponent(*expr)) if (Fortran::lower::isParentComponent(*expr))
@ -3030,10 +3033,11 @@ private:
Fortran::common::ScopedSet(semant, PushVal); Fortran::common::ScopedSet(semant, PushVal);
static bool isAdjustedArrayElementType(mlir::Type t) { static bool isAdjustedArrayElementType(mlir::Type t) {
return fir::isa_char(t) || fir::isa_derived(t) || t.isa<fir::SequenceType>(); return fir::isa_char(t) || fir::isa_derived(t) ||
mlir::isa<fir::SequenceType>(t);
} }
static bool elementTypeWasAdjusted(mlir::Type t) { static bool elementTypeWasAdjusted(mlir::Type t) {
if (auto ty = t.dyn_cast<fir::ReferenceType>()) if (auto ty = mlir::dyn_cast<fir::ReferenceType>(t))
return isAdjustedArrayElementType(ty.getEleTy()); return isAdjustedArrayElementType(ty.getEleTy());
return false; return false;
} }
@ -3050,15 +3054,15 @@ static void genScalarUserDefinedAssignmentCall(fir::FirOpBuilder &builder,
auto prepareUserDefinedArg = auto prepareUserDefinedArg =
[](fir::FirOpBuilder &builder, mlir::Location loc, [](fir::FirOpBuilder &builder, mlir::Location loc,
const fir::ExtendedValue &value, mlir::Type argType) -> mlir::Value { const fir::ExtendedValue &value, mlir::Type argType) -> mlir::Value {
if (argType.isa<fir::BoxCharType>()) { if (mlir::isa<fir::BoxCharType>(argType)) {
const fir::CharBoxValue *charBox = value.getCharBox(); const fir::CharBoxValue *charBox = value.getCharBox();
assert(charBox && "argument type mismatch in elemental user assignment"); assert(charBox && "argument type mismatch in elemental user assignment");
return fir::factory::CharacterExprHelper{builder, loc}.createEmbox( return fir::factory::CharacterExprHelper{builder, loc}.createEmbox(
*charBox); *charBox);
} }
if (argType.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(argType)) {
mlir::Value box = mlir::Value box =
builder.createBox(loc, value, argType.isa<fir::ClassType>()); builder.createBox(loc, value, mlir::isa<fir::ClassType>(argType));
return builder.createConvert(loc, argType, box); return builder.createConvert(loc, argType, box);
} }
// Simple pass by address. // Simple pass by address.
@ -3170,7 +3174,7 @@ convertToArrayBoxValue(mlir::Location loc, fir::FirOpBuilder &builder,
mlir::Value val, mlir::Value len) { mlir::Value val, mlir::Value len) {
mlir::Type ty = fir::unwrapRefType(val.getType()); mlir::Type ty = fir::unwrapRefType(val.getType());
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
auto seqTy = ty.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(ty);
auto undef = builder.create<fir::UndefOp>(loc, idxTy); auto undef = builder.create<fir::UndefOp>(loc, idxTy);
llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), undef); llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), undef);
if (fir::isa_char(seqTy.getEleTy())) if (fir::isa_char(seqTy.getEleTy()))
@ -3462,7 +3466,7 @@ public:
[&](const auto &e) { [&](const auto &e) {
auto f = genarr(e); auto f = genarr(e);
ExtValue exv = f(IterationSpace{}); ExtValue exv = f(IterationSpace{});
if (fir::getBase(exv).getType().template isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType()))
return exv; return exv;
fir::emitFatalError(getLoc(), "array must be emboxed"); fir::emitFatalError(getLoc(), "array must be emboxed");
}, },
@ -3487,10 +3491,9 @@ public:
tempRes, dest.getSlice(), tempRes, dest.getSlice(),
dest.getTypeparams()); dest.getTypeparams());
auto arrTy = auto arrTy = mlir::cast<fir::SequenceType>(
fir::dyn_cast_ptrEleTy(tempRes.getType()).cast<fir::SequenceType>(); fir::dyn_cast_ptrEleTy(tempRes.getType()));
if (auto charTy = if (auto charTy = mlir::dyn_cast<fir::CharacterType>(arrTy.getEleTy())) {
arrTy.getEleTy().template dyn_cast<fir::CharacterType>()) {
if (fir::characterWithDynamicLen(charTy)) if (fir::characterWithDynamicLen(charTy))
TODO(loc, "CHARACTER does not have constant LEN"); TODO(loc, "CHARACTER does not have constant LEN");
mlir::Value len = builder.createIntegerConstant( mlir::Value len = builder.createIntegerConstant(
@ -3912,17 +3915,18 @@ private:
mlir::Value convertElementForUpdate(mlir::Location loc, mlir::Type eleTy, mlir::Value convertElementForUpdate(mlir::Location loc, mlir::Type eleTy,
mlir::Value origVal) { mlir::Value origVal) {
if (auto origEleTy = fir::dyn_cast_ptrEleTy(origVal.getType())) if (auto origEleTy = fir::dyn_cast_ptrEleTy(origVal.getType()))
if (origEleTy.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(origEleTy)) {
// If origVal is a box variable, load it so it is in the value domain. // If origVal is a box variable, load it so it is in the value domain.
origVal = builder.create<fir::LoadOp>(loc, origVal); origVal = builder.create<fir::LoadOp>(loc, origVal);
} }
if (origVal.getType().isa<fir::BoxType>() && !eleTy.isa<fir::BoxType>()) { if (mlir::isa<fir::BoxType>(origVal.getType()) &&
!mlir::isa<fir::BoxType>(eleTy)) {
if (isPointerAssignment()) if (isPointerAssignment())
TODO(loc, "lhs of pointer assignment returned unexpected value"); TODO(loc, "lhs of pointer assignment returned unexpected value");
TODO(loc, "invalid box conversion in elemental computation"); TODO(loc, "invalid box conversion in elemental computation");
} }
if (isPointerAssignment() && eleTy.isa<fir::BoxType>() && if (isPointerAssignment() && mlir::isa<fir::BoxType>(eleTy) &&
!origVal.getType().isa<fir::BoxType>()) { !mlir::isa<fir::BoxType>(origVal.getType())) {
// This is a pointer assignment and the rhs is a raw reference to a TARGET // This is a pointer assignment and the rhs is a raw reference to a TARGET
// in memory. Embox the reference so it can be stored to the boxed // in memory. Embox the reference so it can be stored to the boxed
// POINTER variable. // POINTER variable.
@ -3930,7 +3934,7 @@ private:
if (auto eleTy = fir::dyn_cast_ptrEleTy(origVal.getType()); if (auto eleTy = fir::dyn_cast_ptrEleTy(origVal.getType());
fir::hasDynamicSize(eleTy)) fir::hasDynamicSize(eleTy))
TODO(loc, "TARGET of pointer assignment with runtime size/shape"); TODO(loc, "TARGET of pointer assignment with runtime size/shape");
auto memrefTy = fir::boxMemRefType(eleTy.cast<fir::BoxType>()); auto memrefTy = fir::boxMemRefType(mlir::cast<fir::BoxType>(eleTy));
auto castTo = builder.createConvert(loc, memrefTy, origVal); auto castTo = builder.createConvert(loc, memrefTy, origVal);
origVal = builder.create<fir::EmboxOp>(loc, eleTy, castTo); origVal = builder.create<fir::EmboxOp>(loc, eleTy, castTo);
} }
@ -3982,7 +3986,7 @@ private:
auto arrayOp = builder.create<fir::ArrayAccessOp>( auto arrayOp = builder.create<fir::ArrayAccessOp>(
loc, resRefTy, innerArg, iterSpace.iterVec(), loc, resRefTy, innerArg, iterSpace.iterVec(),
fir::factory::getTypeParams(loc, builder, destination)); fir::factory::getTypeParams(loc, builder, destination));
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
llvm::SmallVector<mlir::Value> substringBounds; llvm::SmallVector<mlir::Value> substringBounds;
populateBounds(substringBounds, substring); populateBounds(substringBounds, substring);
mlir::Value dstLen = fir::factory::genLenOfCharacter( mlir::Value dstLen = fir::factory::genLenOfCharacter(
@ -3996,7 +4000,7 @@ private:
loc, destination, builder, arrayOp, exv, eleTy, innerArg); loc, destination, builder, arrayOp, exv, eleTy, innerArg);
return abstractArrayExtValue(amend /*FIXME: typeparams?*/); return abstractArrayExtValue(amend /*FIXME: typeparams?*/);
} }
assert(eleTy.isa<fir::SequenceType>() && "must be an array"); assert(mlir::isa<fir::SequenceType>(eleTy) && "must be an array");
TODO(loc, "array (as element) assignment"); TODO(loc, "array (as element) assignment");
} }
// By value semantics. The element is being assigned by value. // By value semantics. The element is being assigned by value.
@ -4060,7 +4064,7 @@ private:
llvm::SmallVector<mlir::Value> getShape(ArrayOperand array) { llvm::SmallVector<mlir::Value> getShape(ArrayOperand array) {
if (array.slice) if (array.slice)
return computeSliceShape(array.slice); return computeSliceShape(array.slice);
if (array.memref.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(array.memref.getType()))
return fir::factory::readExtents(builder, getLoc(), return fir::factory::readExtents(builder, getLoc(),
fir::BoxValue{array.memref}); fir::BoxValue{array.memref});
return fir::factory::getExtents(array.shape); return fir::factory::getExtents(array.shape);
@ -4133,7 +4137,7 @@ private:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
return [=, builder = &converter.getFirOpBuilder()](IterSpace iters) { return [=, builder = &converter.getFirOpBuilder()](IterSpace iters) {
mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(tmp.getType()); mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(tmp.getType());
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
mlir::Type eleRefTy = builder->getRefType(eleTy); mlir::Type eleRefTy = builder->getRefType(eleTy);
mlir::IntegerType i1Ty = builder->getI1Type(); mlir::IntegerType i1Ty = builder->getI1Type();
// Adjust indices for any shift of the origin of the array. // Adjust indices for any shift of the origin of the array.
@ -4442,15 +4446,15 @@ private:
TODO(loc, "polymorphic array temporary"); TODO(loc, "polymorphic array temporary");
if (ccLoadDest) if (ccLoadDest)
return (*ccLoadDest)(shape); return (*ccLoadDest)(shape);
auto seqTy = type.dyn_cast<fir::SequenceType>(); auto seqTy = mlir::dyn_cast<fir::SequenceType>(type);
assert(seqTy && "must be an array"); assert(seqTy && "must be an array");
// TODO: Need to thread the LEN parameters here. For character, they may // TODO: Need to thread the LEN parameters here. For character, they may
// differ from the operands length (e.g concatenation). So the array loads // differ from the operands length (e.g concatenation). So the array loads
// type parameters are not enough. // type parameters are not enough.
if (auto charTy = seqTy.getEleTy().dyn_cast<fir::CharacterType>()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(seqTy.getEleTy()))
if (charTy.hasDynamicLen()) if (charTy.hasDynamicLen())
TODO(loc, "character array expression temp with dynamic length"); TODO(loc, "character array expression temp with dynamic length");
if (auto recTy = seqTy.getEleTy().dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(seqTy.getEleTy()))
if (recTy.getNumLenParams() > 0) if (recTy.getNumLenParams() > 0)
TODO(loc, "derived type array expression temp with LEN parameters"); TODO(loc, "derived type array expression temp with LEN parameters");
if (mlir::Type eleTy = fir::unwrapSequenceType(type); if (mlir::Type eleTy = fir::unwrapSequenceType(type);
@ -4827,7 +4831,7 @@ private:
}); });
} else { } else {
ExtValue exv = asScalarRef(*expr); ExtValue exv = asScalarRef(*expr);
if (fir::getBase(exv).getType().isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType())) {
operands.emplace_back( operands.emplace_back(
[=](IterSpace iters) -> ExtValue { return exv; }); [=](IterSpace iters) -> ExtValue { return exv; });
} else { } else {
@ -5565,7 +5569,7 @@ private:
} }
static mlir::Type unwrapBoxEleTy(mlir::Type ty) { static mlir::Type unwrapBoxEleTy(mlir::Type ty) {
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty))
return fir::unwrapRefType(boxTy.getEleTy()); return fir::unwrapRefType(boxTy.getEleTy());
return ty; return ty;
} }
@ -5575,7 +5579,7 @@ private:
ty = unwrapBoxEleTy(ty); ty = unwrapBoxEleTy(ty);
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
for (auto extent : ty.cast<fir::SequenceType>().getShape()) { for (auto extent : mlir::cast<fir::SequenceType>(ty).getShape()) {
auto v = extent == fir::SequenceType::getUnknownExtent() auto v = extent == fir::SequenceType::getUnknownExtent()
? builder.create<fir::UndefOp>(loc, idxTy).getResult() ? builder.create<fir::UndefOp>(loc, idxTy).getResult()
: builder.createIntegerConstant(loc, idxTy, extent); : builder.createIntegerConstant(loc, idxTy, extent);
@ -5638,7 +5642,8 @@ private:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
mlir::Value memref = fir::getBase(extMemref); mlir::Value memref = fir::getBase(extMemref);
mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(memref.getType()); mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(memref.getType());
assert(arrTy.isa<fir::SequenceType>() && "memory ref must be an array"); assert(mlir::isa<fir::SequenceType>(arrTy) &&
"memory ref must be an array");
mlir::Value shape = builder.createShape(loc, extMemref); mlir::Value shape = builder.createShape(loc, extMemref);
mlir::Value slice; mlir::Value slice;
if (components.isSlice()) { if (components.isSlice()) {
@ -5688,12 +5693,12 @@ private:
components.suffixComponents); components.suffixComponents);
} }
if (components.hasComponents()) { if (components.hasComponents()) {
auto seqTy = arrTy.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(arrTy);
mlir::Type eleTy = mlir::Type eleTy =
fir::applyPathToType(seqTy.getEleTy(), components.suffixComponents); fir::applyPathToType(seqTy.getEleTy(), components.suffixComponents);
if (!eleTy) if (!eleTy)
fir::emitFatalError(loc, "slicing path is ill-formed"); fir::emitFatalError(loc, "slicing path is ill-formed");
if (auto realTy = eleTy.dyn_cast<fir::RealType>()) if (auto realTy = mlir::dyn_cast<fir::RealType>(eleTy))
eleTy = Fortran::lower::convertReal(realTy.getContext(), eleTy = Fortran::lower::convertReal(realTy.getContext(),
realTy.getFKind()); realTy.getFKind());
@ -5713,13 +5718,14 @@ private:
// value. The value of the box is forwarded in the continuation. // value. The value of the box is forwarded in the continuation.
mlir::Type reduceTy = reduceRank(arrTy, slice); mlir::Type reduceTy = reduceRank(arrTy, slice);
mlir::Type boxTy = fir::BoxType::get(reduceTy); mlir::Type boxTy = fir::BoxType::get(reduceTy);
if (memref.getType().isa<fir::ClassType>() && !components.hasComponents()) if (mlir::isa<fir::ClassType>(memref.getType()) &&
!components.hasComponents())
boxTy = fir::ClassType::get(reduceTy); boxTy = fir::ClassType::get(reduceTy);
if (components.substring) { if (components.substring) {
// Adjust char length to substring size. // Adjust char length to substring size.
fir::CharacterType charTy = fir::CharacterType charTy =
fir::factory::CharacterExprHelper::getCharType(reduceTy); fir::factory::CharacterExprHelper::getCharType(reduceTy);
auto seqTy = reduceTy.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(reduceTy);
// TODO: Use a constant for fir.char LEN if we can compute it. // TODO: Use a constant for fir.char LEN if we can compute it.
boxTy = fir::BoxType::get( boxTy = fir::BoxType::get(
fir::SequenceType::get(fir::CharacterType::getUnknownLen( fir::SequenceType::get(fir::CharacterType::getUnknownLen(
@ -5734,7 +5740,7 @@ private:
nonDeferredLenParams = fir::factory::getNonDeferredLenParams(extMemref); nonDeferredLenParams = fir::factory::getNonDeferredLenParams(extMemref);
} }
mlir::Value embox = mlir::Value embox =
memref.getType().isa<fir::BaseBoxType>() mlir::isa<fir::BaseBoxType>(memref.getType())
? builder.create<fir::ReboxOp>(loc, boxTy, memref, shape, slice) ? builder.create<fir::ReboxOp>(loc, boxTy, memref, shape, slice)
.getResult() .getResult()
: builder : builder
@ -5745,7 +5751,7 @@ private:
return fir::BoxValue(embox, lbounds, nonDeferredLenParams); return fir::BoxValue(embox, lbounds, nonDeferredLenParams);
}; };
} }
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
if (isReferentiallyOpaque()) { if (isReferentiallyOpaque()) {
// Semantics are an opaque reference to an array. // Semantics are an opaque reference to an array.
// This case forwards a continuation that will generate the address // This case forwards a continuation that will generate the address
@ -5760,12 +5766,12 @@ private:
mlir::Value coor = builder.create<fir::ArrayCoorOp>( mlir::Value coor = builder.create<fir::ArrayCoorOp>(
loc, refEleTy, memref, shape, slice, indices, loc, refEleTy, memref, shape, slice, indices,
fir::getTypeParams(extMemref)); fir::getTypeParams(extMemref));
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
llvm::SmallVector<mlir::Value> substringBounds; llvm::SmallVector<mlir::Value> substringBounds;
populateBounds(substringBounds, components.substring); populateBounds(substringBounds, components.substring);
if (!substringBounds.empty()) { if (!substringBounds.empty()) {
mlir::Value dstLen = fir::factory::genLenOfCharacter( mlir::Value dstLen = fir::factory::genLenOfCharacter(
builder, loc, arrTy.cast<fir::SequenceType>(), memref, builder, loc, mlir::cast<fir::SequenceType>(arrTy), memref,
fir::getTypeParams(extMemref), iters.iterVec(), fir::getTypeParams(extMemref), iters.iterVec(),
substringBounds); substringBounds);
fir::CharBoxValue dstChar(coor, dstLen); fir::CharBoxValue dstChar(coor, dstLen);
@ -5863,7 +5869,7 @@ private:
mlir::Type eleRefTy = builder.getRefType(eleTy); mlir::Type eleRefTy = builder.getRefType(eleTy);
mlir::Value arrayOp = builder.create<fir::ArrayAccessOp>( mlir::Value arrayOp = builder.create<fir::ArrayAccessOp>(
loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams); loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
llvm::SmallVector<mlir::Value> substringBounds; llvm::SmallVector<mlir::Value> substringBounds;
populateBounds(substringBounds, components.substring); populateBounds(substringBounds, components.substring);
if (!substringBounds.empty()) { if (!substringBounds.empty()) {
@ -5896,7 +5902,7 @@ private:
const bool hasOptionalAttr = const bool hasOptionalAttr =
fir::valueHasFirAttribute(base, fir::getOptionalAttrName()); fir::valueHasFirAttribute(base, fir::getOptionalAttrName());
mlir::Type baseType = fir::unwrapRefType(base.getType()); mlir::Type baseType = fir::unwrapRefType(base.getType());
const bool isBox = baseType.isa<fir::BoxType>(); const bool isBox = mlir::isa<fir::BoxType>(baseType);
const bool isAllocOrPtr = const bool isAllocOrPtr =
Fortran::evaluate::IsAllocatableOrPointerObject(expr); Fortran::evaluate::IsAllocatableOrPointerObject(expr);
mlir::Type arrType = fir::unwrapPassByRefType(baseType); mlir::Type arrType = fir::unwrapPassByRefType(baseType);
@ -5989,7 +5995,7 @@ private:
if (slice) { if (slice) {
auto slOp = mlir::dyn_cast<fir::SliceOp>(slice.getDefiningOp()); auto slOp = mlir::dyn_cast<fir::SliceOp>(slice.getDefiningOp());
assert(slOp && "expected slice op"); assert(slOp && "expected slice op");
auto seqTy = arrTy.dyn_cast<fir::SequenceType>(); auto seqTy = mlir::dyn_cast<fir::SequenceType>(arrTy);
assert(seqTy && "expected array type"); assert(seqTy && "expected array type");
mlir::Operation::operand_range triples = slOp.getTriples(); mlir::Operation::operand_range triples = slOp.getTriples();
fir::SequenceType::Shape shape; fir::SequenceType::Shape shape;
@ -6053,7 +6059,7 @@ private:
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
mlir::Value multiplier = builder.createIntegerConstant(loc, idxTy, 1); mlir::Value multiplier = builder.createIntegerConstant(loc, idxTy, 1);
if (fir::hasDynamicSize(eleTy)) { if (fir::hasDynamicSize(eleTy)) {
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
// Array of char with dynamic LEN parameter. Downcast to an array // Array of char with dynamic LEN parameter. Downcast to an array
// of singleton char, and scale by the len type parameter from // of singleton char, and scale by the len type parameter from
// `exv`. // `exv`.
@ -6074,7 +6080,7 @@ private:
}); });
fir::CharacterType newEleTy = fir::CharacterType::getSingleton( fir::CharacterType newEleTy = fir::CharacterType::getSingleton(
eleTy.getContext(), charTy.getFKind()); eleTy.getContext(), charTy.getFKind());
if (auto seqTy = resTy.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(resTy)) {
assert(eleTy == seqTy.getEleTy()); assert(eleTy == seqTy.getEleTy());
resTy = fir::SequenceType::get(seqTy.getShape(), newEleTy); resTy = fir::SequenceType::get(seqTy.getShape(), newEleTy);
} }
@ -6161,7 +6167,7 @@ private:
if (!eleSz) { if (!eleSz) {
// Compute the element size at runtime. // Compute the element size at runtime.
assert(fir::hasDynamicSize(eleTy)); assert(fir::hasDynamicSize(eleTy));
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
auto charBytes = auto charBytes =
builder.getKindMap().getCharacterBitsize(charTy.getFKind()) / 8; builder.getKindMap().getCharacterBitsize(charTy.getFKind()) / 8;
mlir::Value bytes = mlir::Value bytes =
@ -6181,7 +6187,7 @@ private:
auto computeCoordinate = [&](mlir::Value buff, mlir::Value off) { auto computeCoordinate = [&](mlir::Value buff, mlir::Value off) {
mlir::Type refTy = eleRefTy; mlir::Type refTy = eleRefTy;
if (fir::hasDynamicSize(eleTy)) { if (fir::hasDynamicSize(eleTy)) {
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
// Scale a simple pointer using dynamic length and offset values. // Scale a simple pointer using dynamic length and offset values.
auto chTy = fir::CharacterType::getSingleton(charTy.getContext(), auto chTy = fir::CharacterType::getSingleton(charTy.getContext(),
charTy.getFKind()); charTy.getFKind());
@ -6308,7 +6314,7 @@ private:
builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.upper()))); builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.upper())));
mlir::Value step = mlir::Value step =
builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.stride()))); builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.stride())));
auto seqTy = resTy.template cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(resTy);
mlir::Type eleTy = fir::unwrapSequenceType(seqTy); mlir::Type eleTy = fir::unwrapSequenceType(seqTy);
auto loop = auto loop =
builder.create<fir::DoLoopOp>(loc, lo, up, step, /*unordered=*/false, builder.create<fir::DoLoopOp>(loc, lo, up, step, /*unordered=*/false,
@ -6375,7 +6381,7 @@ private:
auto evExpr = toEvExpr(x); auto evExpr = toEvExpr(x);
mlir::Type resTy = translateSomeExprToFIRType(converter, evExpr); mlir::Type resTy = translateSomeExprToFIRType(converter, evExpr);
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
auto seqTy = resTy.template cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(resTy);
mlir::Type eleTy = fir::unwrapSequenceType(resTy); mlir::Type eleTy = fir::unwrapSequenceType(resTy);
mlir::Value buffSize = builder.createTemporary(loc, idxTy, ".buff.size"); mlir::Value buffSize = builder.createTemporary(loc, idxTy, ".buff.size");
mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0); mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
@ -6719,7 +6725,7 @@ private:
auto fieldTy = fir::FieldType::get(builder.getContext()); auto fieldTy = fir::FieldType::get(builder.getContext());
std::string name = std::string name =
converter.getRecordTypeFieldName(getLastSym(*x)); converter.getRecordTypeFieldName(getLastSym(*x));
if (auto recTy = ty.dyn_cast<fir::RecordType>()) { if (auto recTy = mlir::dyn_cast<fir::RecordType>(ty)) {
ty = recTy.getType(name); ty = recTy.getType(name);
auto fld = builder.create<fir::FieldIndexOp>( auto fld = builder.create<fir::FieldIndexOp>(
loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv)); loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv));
@ -6728,7 +6734,7 @@ private:
// Need an intermediate dereference if the boxed value // Need an intermediate dereference if the boxed value
// appears in the middle of the component path or if it is // appears in the middle of the component path or if it is
// on the right and this is not a pointer assignment. // on the right and this is not a pointer assignment.
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
auto currentFunc = components.getExtendCoorRef(); auto currentFunc = components.getExtendCoorRef();
auto loc = getLoc(); auto loc = getLoc();
auto *bldr = &converter.getFirOpBuilder(); auto *bldr = &converter.getFirOpBuilder();
@ -6739,9 +6745,9 @@ private:
deref = true; deref = true;
} }
} }
} else if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) { } else if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
ty = fir::unwrapRefType(boxTy.getEleTy()); ty = fir::unwrapRefType(boxTy.getEleTy());
auto recTy = ty.cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(ty);
ty = recTy.getType(name); ty = recTy.getType(name);
auto fld = builder.create<fir::FieldIndexOp>( auto fld = builder.create<fir::FieldIndexOp>(
loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv)); loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv));
@ -6790,7 +6796,7 @@ private:
auto arrayOp = builder.create<fir::ArrayAccessOp>( auto arrayOp = builder.create<fir::ArrayAccessOp>(
loc, eleRefTy, innerArg, iters.iterVec(), loc, eleRefTy, innerArg, iters.iterVec(),
fir::factory::getTypeParams(loc, builder, load)); fir::factory::getTypeParams(loc, builder, load));
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
mlir::Value dstLen = fir::factory::genLenOfCharacter( mlir::Value dstLen = fir::factory::genLenOfCharacter(
builder, loc, load, iters.iterVec(), substringBounds); builder, loc, load, iters.iterVec(), substringBounds);
fir::ArrayAmendOp amend = createCharArrayAmend( fir::ArrayAmendOp amend = createCharArrayAmend(
@ -6806,13 +6812,13 @@ private:
return arrayLoadExtValue(builder, loc, load, iters.iterVec(), return arrayLoadExtValue(builder, loc, load, iters.iterVec(),
amend); amend);
} }
assert(eleTy.isa<fir::SequenceType>()); assert(mlir::isa<fir::SequenceType>(eleTy));
TODO(loc, "array (as element) assignment"); TODO(loc, "array (as element) assignment");
} }
if (components.hasExtendCoorRef()) { if (components.hasExtendCoorRef()) {
auto eleBoxTy = auto eleBoxTy =
fir::applyPathToType(innerArg.getType(), iters.iterVec()); fir::applyPathToType(innerArg.getType(), iters.iterVec());
if (!eleBoxTy || !eleBoxTy.isa<fir::BoxType>()) if (!eleBoxTy || !mlir::isa<fir::BoxType>(eleBoxTy))
TODO(loc, "assignment in a FORALL involving a designator with a " TODO(loc, "assignment in a FORALL involving a designator with a "
"POINTER or ALLOCATABLE component part-ref"); "POINTER or ALLOCATABLE component part-ref");
auto arrayOp = builder.create<fir::ArrayAccessOp>( auto arrayOp = builder.create<fir::ArrayAccessOp>(
@ -6824,7 +6830,7 @@ private:
// assignment, then insert the dereference of the box before any // assignment, then insert the dereference of the box before any
// conversion and store. // conversion and store.
if (!isPointerAssignment()) { if (!isPointerAssignment()) {
if (auto boxTy = eleTy.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(eleTy)) {
eleTy = fir::boxMemRefType(boxTy); eleTy = fir::boxMemRefType(boxTy);
addr = builder.create<fir::BoxAddrOp>(loc, eleTy, addr); addr = builder.create<fir::BoxAddrOp>(loc, eleTy, addr);
eleTy = fir::unwrapRefType(eleTy); eleTy = fir::unwrapRefType(eleTy);
@ -6885,7 +6891,7 @@ private:
} }
if (components.hasExtendCoorRef()) { if (components.hasExtendCoorRef()) {
auto eleBoxTy = fir::applyPathToType(load.getType(), iters.iterVec()); auto eleBoxTy = fir::applyPathToType(load.getType(), iters.iterVec());
if (!eleBoxTy || !eleBoxTy.isa<fir::BoxType>()) if (!eleBoxTy || !mlir::isa<fir::BoxType>(eleBoxTy))
TODO(loc, "assignment in a FORALL involving a designator with a " TODO(loc, "assignment in a FORALL involving a designator with a "
"POINTER or ALLOCATABLE component part-ref"); "POINTER or ALLOCATABLE component part-ref");
auto access = builder.create<fir::ArrayAccessOp>( auto access = builder.create<fir::ArrayAccessOp>(
@ -6897,7 +6903,7 @@ private:
} }
if (isPointerAssignment()) { if (isPointerAssignment()) {
auto eleTy = fir::applyPathToType(load.getType(), iters.iterVec()); auto eleTy = fir::applyPathToType(load.getType(), iters.iterVec());
if (!eleTy.isa<fir::BoxType>()) { if (!mlir::isa<fir::BoxType>(eleTy)) {
// Rhs is a regular expression that will need to be boxed before // Rhs is a regular expression that will need to be boxed before
// assigning to the boxed variable. // assigning to the boxed variable.
auto typeParams = fir::factory::getTypeParams(loc, builder, load); auto typeParams = fir::factory::getTypeParams(loc, builder, load);
@ -7615,7 +7621,7 @@ mlir::Value Fortran::lower::addCrayPointerInst(mlir::Location loc,
auto box = builder.create<fir::EmboxOp>(loc, boxTy, ptrVal, empty, empty, auto box = builder.create<fir::EmboxOp>(loc, boxTy, ptrVal, empty, empty,
emptyRange); emptyRange);
mlir::Value addrof = mlir::Value addrof =
(ptrTy.isa<fir::ReferenceType>()) (mlir::isa<fir::ReferenceType>(ptrTy))
? builder.create<fir::BoxAddrOp>(loc, ptrTy, box) ? builder.create<fir::BoxAddrOp>(loc, ptrTy, box)
: builder.create<fir::BoxAddrOp>(loc, builder.getRefType(ptrTy), box); : builder.create<fir::BoxAddrOp>(loc, builder.getRefType(ptrTy), box);

View File

@ -138,8 +138,8 @@ public:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
mlir::Type idxTy = builder.getIndexType(); mlir::Type idxTy = builder.getIndexType();
llvm::SmallVector<mlir::Value> extents; llvm::SmallVector<mlir::Value> extents;
auto seqTy = hlfir::getFortranElementOrSequenceType(fieldType) auto seqTy = mlir::cast<fir::SequenceType>(
.cast<fir::SequenceType>(); hlfir::getFortranElementOrSequenceType(fieldType));
for (auto extent : seqTy.getShape()) { for (auto extent : seqTy.getShape()) {
if (extent == fir::SequenceType::getUnknownExtent()) { if (extent == fir::SequenceType::getUnknownExtent()) {
// We have already generated invalid hlfir.declare // We have already generated invalid hlfir.declare
@ -199,7 +199,7 @@ private:
const T &designatorNode) { const T &designatorNode) {
// Get base's shape if its a sequence type with no previously computed // Get base's shape if its a sequence type with no previously computed
// result shape // result shape
if (partInfo.base && resultValueType.isa<fir::SequenceType>() && if (partInfo.base && mlir::isa<fir::SequenceType>(resultValueType) &&
!partInfo.resultShape) !partInfo.resultShape)
partInfo.resultShape = partInfo.resultShape =
hlfir::genShape(getLoc(), getBuilder(), *partInfo.base); hlfir::genShape(getLoc(), getBuilder(), *partInfo.base);
@ -209,7 +209,7 @@ private:
return fir::ClassType::get(resultValueType); return fir::ClassType::get(resultValueType);
// Character scalar with dynamic length needs a fir.boxchar to hold the // Character scalar with dynamic length needs a fir.boxchar to hold the
// designator length. // designator length.
auto charType = resultValueType.dyn_cast<fir::CharacterType>(); auto charType = mlir::dyn_cast<fir::CharacterType>(resultValueType);
if (charType && charType.hasDynamicLen()) if (charType && charType.hasDynamicLen())
return fir::BoxCharType::get(charType.getContext(), charType.getFKind()); return fir::BoxCharType::get(charType.getContext(), charType.getFKind());
// Arrays with non default lower bounds or dynamic length or dynamic extent // Arrays with non default lower bounds or dynamic length or dynamic extent
@ -218,7 +218,7 @@ private:
hasNonDefaultLowerBounds(partInfo)) hasNonDefaultLowerBounds(partInfo))
return fir::BoxType::get(resultValueType); return fir::BoxType::get(resultValueType);
// Non simply contiguous ref require a fir.box to carry the byte stride. // Non simply contiguous ref require a fir.box to carry the byte stride.
if (resultValueType.isa<fir::SequenceType>() && if (mlir::isa<fir::SequenceType>(resultValueType) &&
!Fortran::evaluate::IsSimplyContiguous( !Fortran::evaluate::IsSimplyContiguous(
designatorNode, getConverter().getFoldingContext())) designatorNode, getConverter().getFoldingContext()))
return fir::BoxType::get(resultValueType); return fir::BoxType::get(resultValueType);
@ -398,8 +398,8 @@ private:
partInfo.typeParams[0] = partInfo.typeParams[0] =
fir::factory::genMaxWithZero(builder, loc, rawLen); fir::factory::genMaxWithZero(builder, loc, rawLen);
} }
auto kind = hlfir::getFortranElementType(baseStringType) auto kind = mlir::cast<fir::CharacterType>(
.cast<fir::CharacterType>() hlfir::getFortranElementType(baseStringType))
.getFKind(); .getFKind();
auto newCharTy = fir::CharacterType::get( auto newCharTy = fir::CharacterType::get(
baseStringType.getContext(), kind, baseStringType.getContext(), kind,
@ -579,7 +579,7 @@ private:
return createVectorSubscriptElementAddrOp(partInfo, baseType, return createVectorSubscriptElementAddrOp(partInfo, baseType,
resultExtents); resultExtents);
mlir::Type resultType = baseType.cast<fir::SequenceType>().getEleTy(); mlir::Type resultType = mlir::cast<fir::SequenceType>(baseType).getEleTy();
if (!resultTypeShape.empty()) { if (!resultTypeShape.empty()) {
// Ranked array section. The result shape comes from the array section // Ranked array section. The result shape comes from the array section
// subscripts. // subscripts.
@ -612,8 +612,8 @@ private:
} }
static bool hasNonDefaultLowerBounds(const PartInfo &partInfo) { static bool hasNonDefaultLowerBounds(const PartInfo &partInfo) {
return partInfo.resultShape && return partInfo.resultShape &&
(partInfo.resultShape.getType().isa<fir::ShiftType>() || mlir::isa<fir::ShiftType, fir::ShapeShiftType>(
partInfo.resultShape.getType().isa<fir::ShapeShiftType>()); partInfo.resultShape.getType());
} }
mlir::Type visit(const Fortran::evaluate::Component &component, mlir::Type visit(const Fortran::evaluate::Component &component,
@ -705,7 +705,7 @@ private:
const Fortran::semantics::Symbol &componentSym = component.GetLastSymbol(); const Fortran::semantics::Symbol &componentSym = component.GetLastSymbol();
partInfo.componentName = converter.getRecordTypeFieldName(componentSym); partInfo.componentName = converter.getRecordTypeFieldName(componentSym);
auto recordType = auto recordType =
hlfir::getFortranElementType(baseType).cast<fir::RecordType>(); mlir::cast<fir::RecordType>(hlfir::getFortranElementType(baseType));
if (recordType.isDependentType()) if (recordType.isDependentType())
TODO(getLoc(), "Designate derived type with length parameters in HLFIR"); TODO(getLoc(), "Designate derived type with length parameters in HLFIR");
mlir::Type fieldType = recordType.getType(partInfo.componentName); mlir::Type fieldType = recordType.getType(partInfo.componentName);
@ -718,7 +718,7 @@ private:
if (fir::isRecordWithTypeParameters(fieldEleType)) if (fir::isRecordWithTypeParameters(fieldEleType))
TODO(loc, TODO(loc,
"lower a component that is a parameterized derived type to HLFIR"); "lower a component that is a parameterized derived type to HLFIR");
if (auto charTy = fieldEleType.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(fieldEleType)) {
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
mlir::Type idxTy = builder.getIndexType(); mlir::Type idxTy = builder.getIndexType();
if (charTy.hasConstantLen()) if (charTy.hasConstantLen())
@ -811,7 +811,7 @@ private:
} }
} }
builder.setInsertionPoint(elementalAddrOp); builder.setInsertionPoint(elementalAddrOp);
return baseType.cast<fir::SequenceType>().getEleTy(); return mlir::cast<fir::SequenceType>(baseType).getEleTy();
} }
/// Yield the designator for the final part-ref inside the /// Yield the designator for the final part-ref inside the
@ -1665,7 +1665,7 @@ private:
mlir::Location loc = getLoc(); mlir::Location loc = getLoc();
fir::FirOpBuilder &builder = getBuilder(); fir::FirOpBuilder &builder = getBuilder();
mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor)); mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor));
auto recTy = ty.cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(ty);
if (recTy.isDependentType()) if (recTy.isDependentType())
TODO(loc, "structure constructor for derived type with length parameters " TODO(loc, "structure constructor for derived type with length parameters "

View File

@ -107,11 +107,11 @@ static hlfir::EntityWithAttributes designateProcedurePointerComponent(
procComponentSym); procComponentSym);
/// Passed argument may be a descriptor. This is a scalar reference, so the /// Passed argument may be a descriptor. This is a scalar reference, so the
/// base address can be directly addressed. /// base address can be directly addressed.
if (base.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(base.getType()))
base = builder.create<fir::BoxAddrOp>(loc, base); base = builder.create<fir::BoxAddrOp>(loc, base);
std::string fieldName = converter.getRecordTypeFieldName(procComponentSym); std::string fieldName = converter.getRecordTypeFieldName(procComponentSym);
auto recordType = auto recordType =
hlfir::getFortranElementType(base.getType()).cast<fir::RecordType>(); mlir::cast<fir::RecordType>(hlfir::getFortranElementType(base.getType()));
mlir::Type fieldType = recordType.getType(fieldName); mlir::Type fieldType = recordType.getType(fieldName);
// Note: semantics turns x%p() into x%t%p() when the procedure pointer // Note: semantics turns x%p() into x%t%p() when the procedure pointer
// component is part of parent component t. // component is part of parent component t.
@ -164,7 +164,7 @@ hlfir::EntityWithAttributes Fortran::lower::convertProcedureDesignatorToHLFIR(
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Value funcAddr = fir::getBase(procExv); mlir::Value funcAddr = fir::getBase(procExv);
if (!funcAddr.getType().isa<fir::BoxProcType>()) { if (!mlir::isa<fir::BoxProcType>(funcAddr.getType())) {
mlir::Type boxTy = mlir::Type boxTy =
Fortran::lower::getUntypedBoxProcType(&converter.getMLIRContext()); Fortran::lower::getUntypedBoxProcType(&converter.getMLIRContext());
if (auto host = Fortran::lower::argumentHostAssocs(converter, funcAddr)) if (auto host = Fortran::lower::argumentHostAssocs(converter, funcAddr))

View File

@ -389,13 +389,13 @@ static mlir::Value genDefaultInitializerValue(
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type scalarType = symTy; mlir::Type scalarType = symTy;
fir::SequenceType sequenceType; fir::SequenceType sequenceType;
if (auto ty = symTy.dyn_cast<fir::SequenceType>()) { if (auto ty = mlir::dyn_cast<fir::SequenceType>(symTy)) {
sequenceType = ty; sequenceType = ty;
scalarType = ty.getEleTy(); scalarType = ty.getEleTy();
} }
// Build a scalar default value of the symbol type, looping through the // Build a scalar default value of the symbol type, looping through the
// components to build each component initial value. // components to build each component initial value.
auto recTy = scalarType.cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(scalarType);
mlir::Value initialValue = builder.create<fir::UndefOp>(loc, scalarType); mlir::Value initialValue = builder.create<fir::UndefOp>(loc, scalarType);
const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType(); const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType();
assert(declTy && "var with default initialization must have a type"); assert(declTy && "var with default initialization must have a type");
@ -493,9 +493,9 @@ static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter,
// with a tensor mlir type. This optimization currently only supports // with a tensor mlir type. This optimization currently only supports
// Fortran arrays of integer, real, complex, or logical. The tensor // Fortran arrays of integer, real, complex, or logical. The tensor
// type does not support nested structures. // type does not support nested structures.
if (symTy.isa<fir::SequenceType>() && if (mlir::isa<fir::SequenceType>(symTy) &&
!Fortran::semantics::IsAllocatableOrPointer(sym)) { !Fortran::semantics::IsAllocatableOrPointer(sym)) {
mlir::Type eleTy = symTy.cast<fir::SequenceType>().getEleTy(); mlir::Type eleTy = mlir::cast<fir::SequenceType>(symTy).getEleTy();
if (eleTy.isa<mlir::IntegerType, mlir::FloatType, fir::ComplexType, if (eleTy.isa<mlir::IntegerType, mlir::FloatType, fir::ComplexType,
fir::LogicalType>()) { fir::LogicalType>()) {
const auto *details = const auto *details =
@ -1292,7 +1292,7 @@ static void finalizeCommonBlockDefinition(
fir::GlobalOp global, fir::GlobalOp global,
const Fortran::semantics::MutableSymbolVector &cmnBlkMems) { const Fortran::semantics::MutableSymbolVector &cmnBlkMems) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::TupleType commonTy = global.getType().cast<mlir::TupleType>(); mlir::TupleType commonTy = mlir::cast<mlir::TupleType>(global.getType());
auto initFunc = [&](fir::FirOpBuilder &builder) { auto initFunc = [&](fir::FirOpBuilder &builder) {
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
mlir::Value cb = builder.create<fir::ZeroOp>(loc, commonTy); mlir::Value cb = builder.create<fir::ZeroOp>(loc, commonTy);
@ -1407,7 +1407,7 @@ static bool lowerToBoxValue(const Fortran::semantics::Symbol &sym,
mlir::Value dummyArg, mlir::Value dummyArg,
Fortran::lower::AbstractConverter &converter) { Fortran::lower::AbstractConverter &converter) {
// Only dummy arguments coming as fir.box can be tracked in an BoxValue. // Only dummy arguments coming as fir.box can be tracked in an BoxValue.
if (!dummyArg || !dummyArg.getType().isa<fir::BaseBoxType>()) if (!dummyArg || !mlir::isa<fir::BaseBoxType>(dummyArg.getType()))
return false; return false;
// Non contiguous arrays must be tracked in an BoxValue. // Non contiguous arrays must be tracked in an BoxValue.
if (sym.Rank() > 0 && !Fortran::evaluate::IsSimplyContiguous( if (sym.Rank() > 0 && !Fortran::evaluate::IsSimplyContiguous(
@ -1905,7 +1905,7 @@ void Fortran::lower::mapSymbolAttributes(
// Do not keep scalar characters as fir.box (even when optional). // Do not keep scalar characters as fir.box (even when optional).
// Lowering and FIR is not meant to deal with scalar characters as // Lowering and FIR is not meant to deal with scalar characters as
// fir.box outside of calls. // fir.box outside of calls.
auto boxTy = dummyArg.getType().dyn_cast<fir::BaseBoxType>(); auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(dummyArg.getType());
mlir::Type refTy = builder.getRefType(boxTy.getEleTy()); mlir::Type refTy = builder.getRefType(boxTy.getEleTy());
mlir::Type lenType = builder.getCharacterLengthType(); mlir::Type lenType = builder.getCharacterLengthType();
mlir::Value addr, len; mlir::Value addr, len;
@ -1984,8 +1984,8 @@ void Fortran::lower::mapSymbolAttributes(
// a non pointer/allocatable symbol to be mapped to a MutableBox. // a non pointer/allocatable symbol to be mapped to a MutableBox.
mlir::Type ty = converter.genType(var); mlir::Type ty = converter.genType(var);
bool isPolymorphic = false; bool isPolymorphic = false;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
isPolymorphic = ty.isa<fir::ClassType>(); isPolymorphic = mlir::isa<fir::ClassType>(ty);
ty = boxTy.getEleTy(); ty = boxTy.getEleTy();
} }
Fortran::lower::genDeclareSymbol( Fortran::lower::genDeclareSymbol(
@ -2092,7 +2092,7 @@ void Fortran::lower::mapSymbolAttributes(
mlir::Value addr = preAlloc; mlir::Value addr = preAlloc;
if (arg) if (arg)
if (auto boxTy = arg.getType().dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(arg.getType())) {
// Contiguous assumed shape that can be tracked without a fir.box. // Contiguous assumed shape that can be tracked without a fir.box.
mlir::Type refTy = builder.getRefType(boxTy.getEleTy()); mlir::Type refTy = builder.getRefType(boxTy.getEleTy());
addr = builder.create<fir::BoxAddrOp>(loc, refTy, arg); addr = builder.create<fir::BoxAddrOp>(loc, refTy, arg);
@ -2134,7 +2134,7 @@ void Fortran::lower::mapSymbolAttributes(
} else if (!len) { } else if (!len) {
// Assumed length fir.box (possible for contiguous assumed shapes). // Assumed length fir.box (possible for contiguous assumed shapes).
// Read length from box. // Read length from box.
assert(arg && arg.getType().isa<fir::BoxType>() && assert(arg && mlir::isa<fir::BoxType>(arg.getType()) &&
"must be character dummy fir.box"); "must be character dummy fir.box");
len = charHelp.readLengthFromBox(arg); len = charHelp.readLengthFromBox(arg);
} }

View File

@ -227,22 +227,23 @@ lowerIshftc(fir::FirOpBuilder &builder, mlir::Location loc,
args.push_back(getOperand(1, loadOperand)); args.push_back(getOperand(1, loadOperand));
auto iPC = isPresentCheck(2); auto iPC = isPresentCheck(2);
assert(iPC.has_value()); assert(iPC.has_value());
args.push_back(builder args.push_back(
.genIfOp(loc, {resultType}, *iPC, builder
/*withElseRegion=*/true) .genIfOp(loc, {resultType}, *iPC,
.genThen([&]() { /*withElseRegion=*/true)
fir::ExtendedValue sizeExv = getOperand(2, loadOperand); .genThen([&]() {
mlir::Value size = builder.createConvert( fir::ExtendedValue sizeExv = getOperand(2, loadOperand);
loc, resultType, fir::getBase(sizeExv)); mlir::Value size =
builder.create<fir::ResultOp>(loc, size); builder.createConvert(loc, resultType, fir::getBase(sizeExv));
}) builder.create<fir::ResultOp>(loc, size);
.genElse([&]() { })
mlir::Value bitSize = builder.createIntegerConstant( .genElse([&]() {
loc, resultType, mlir::Value bitSize = builder.createIntegerConstant(
resultType.cast<mlir::IntegerType>().getWidth()); loc, resultType,
builder.create<fir::ResultOp>(loc, bitSize); mlir::cast<mlir::IntegerType>(resultType).getWidth());
}) builder.create<fir::ResultOp>(loc, bitSize);
.getResults()[0]); })
.getResults()[0]);
return genIntrinsicCall(builder, loc, name, resultType, args, stmtCtx); return genIntrinsicCall(builder, loc, name, resultType, args, stmtCtx);
} }
@ -282,7 +283,7 @@ lowerAssociated(fir::FirOpBuilder &builder, mlir::Location loc,
builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), targetBase); builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), targetBase);
mlir::Type targetType = fir::unwrapRefType(targetBase.getType()); mlir::Type targetType = fir::unwrapRefType(targetBase.getType());
mlir::Type targetValueType = fir::unwrapPassByRefType(targetType); mlir::Type targetValueType = fir::unwrapPassByRefType(targetType);
mlir::Type boxType = targetType.isa<fir::BaseBoxType>() mlir::Type boxType = mlir::isa<fir::BaseBoxType>(targetType)
? targetType ? targetType
: fir::BoxType::get(targetValueType); : fir::BoxType::get(targetValueType);
fir::BoxValue targetBox = fir::BoxValue targetBox =

View File

@ -642,14 +642,14 @@ getDataOperandBaseAddr(Fortran::lower::AbstractConverter &converter,
isPresent = isPresent =
builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), rawInput); builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), rawInput);
if (auto boxTy = if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(
fir::unwrapRefType(symAddr.getType()).dyn_cast<fir::BaseBoxType>()) { fir::unwrapRefType(symAddr.getType()))) {
if (boxTy.getEleTy().isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(boxTy.getEleTy()))
TODO(loc, "derived type"); TODO(loc, "derived type");
// Load the box when baseAddr is a `fir.ref<fir.box<T>>` or a // Load the box when baseAddr is a `fir.ref<fir.box<T>>` or a
// `fir.ref<fir.class<T>>` type. // `fir.ref<fir.class<T>>` type.
if (symAddr.getType().isa<fir::ReferenceType>()) { if (mlir::isa<fir::ReferenceType>(symAddr.getType())) {
if (Fortran::semantics::IsOptional(sym)) { if (Fortran::semantics::IsOptional(sym)) {
mlir::Value addr = mlir::Value addr =
builder.genIfOp(loc, {boxTy}, isPresent, /*withElseRegion=*/true) builder.genIfOp(loc, {boxTy}, isPresent, /*withElseRegion=*/true)
@ -722,7 +722,7 @@ genBoundsOpsFromBox(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Type idxTy = builder.getIndexType(); mlir::Type idxTy = builder.getIndexType();
mlir::Type boundTy = builder.getType<BoundsType>(); mlir::Type boundTy = builder.getType<BoundsType>();
assert(info.addr.getType().isa<fir::BaseBoxType>() && assert(mlir::isa<fir::BaseBoxType>(info.addr.getType()) &&
"expect fir.box or fir.class"); "expect fir.box or fir.class");
if (info.isPresent) { if (info.isPresent) {
@ -909,7 +909,8 @@ genBoundsOps(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value stride = one; mlir::Value stride = one;
bool strideInBytes = false; bool strideInBytes = false;
if (fir::unwrapRefType(info.addr.getType()).isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(
fir::unwrapRefType(info.addr.getType()))) {
if (info.isPresent) { if (info.isPresent) {
stride = stride =
builder builder
@ -1020,8 +1021,8 @@ genBoundsOps(fir::FirOpBuilder &builder, mlir::Location loc,
} }
} }
if (info.isPresent && if (info.isPresent && mlir::isa<fir::BaseBoxType>(
fir::unwrapRefType(info.addr.getType()).isa<fir::BaseBoxType>()) { fir::unwrapRefType(info.addr.getType()))) {
extent = extent =
builder builder
.genIfOp(loc, idxTy, info.isPresent, /*withElseRegion=*/true) .genIfOp(loc, idxTy, info.isPresent, /*withElseRegion=*/true)
@ -1157,7 +1158,7 @@ AddrAndBoundsInfo gatherDataOperandAddrAndBounds(
converter.genExprAddr(operandLocation, designator, stmtCtx); converter.genExprAddr(operandLocation, designator, stmtCtx);
info.addr = fir::getBase(compExv); info.addr = fir::getBase(compExv);
info.rawInput = info.addr; info.rawInput = info.addr;
if (fir::unwrapRefType(info.addr.getType()).isa<fir::SequenceType>()) if (mlir::isa<fir::SequenceType>(fir::unwrapRefType(info.addr.getType())))
bounds = genBaseBoundsOps<BoundsOp, BoundsType>(builder, operandLocation, bounds = genBaseBoundsOps<BoundsOp, BoundsType>(builder, operandLocation,
converter, compExv, converter, compExv,
/*isAssumedSize=*/false); /*isAssumedSize=*/false);
@ -1199,13 +1200,14 @@ AddrAndBoundsInfo gatherDataOperandAddrAndBounds(
fir::ExtendedValue dataExv = converter.getSymbolExtendedValue(*symRef); fir::ExtendedValue dataExv = converter.getSymbolExtendedValue(*symRef);
info = info =
getDataOperandBaseAddr(converter, builder, *symRef, operandLocation); getDataOperandBaseAddr(converter, builder, *symRef, operandLocation);
if (fir::unwrapRefType(info.addr.getType()).isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(
fir::unwrapRefType(info.addr.getType()))) {
bounds = genBoundsOpsFromBox<BoundsOp, BoundsType>( bounds = genBoundsOpsFromBox<BoundsOp, BoundsType>(
builder, operandLocation, converter, dataExv, info); builder, operandLocation, converter, dataExv, info);
} }
bool dataExvIsAssumedSize = bool dataExvIsAssumedSize =
Fortran::semantics::IsAssumedSizeArray(symRef->get().GetUltimate()); Fortran::semantics::IsAssumedSizeArray(symRef->get().GetUltimate());
if (fir::unwrapRefType(info.addr.getType()).isa<fir::SequenceType>()) if (mlir::isa<fir::SequenceType>(fir::unwrapRefType(info.addr.getType())))
bounds = genBaseBoundsOps<BoundsOp, BoundsType>( bounds = genBaseBoundsOps<BoundsOp, BoundsType>(
builder, operandLocation, converter, dataExv, dataExvIsAssumedSize); builder, operandLocation, converter, dataExv, dataExvIsAssumedSize);
asFortran << symRef->get().name().ToString(); asFortran << symRef->get().name().ToString();

View File

@ -265,7 +265,7 @@ HlfirTransformationalIntrinsic::computeResultType(mlir::Value argArray,
mlir::Type stmtResultType) { mlir::Type stmtResultType) {
mlir::Type normalisedResult = mlir::Type normalisedResult =
hlfir::getFortranElementOrSequenceType(stmtResultType); hlfir::getFortranElementOrSequenceType(stmtResultType);
if (auto array = normalisedResult.dyn_cast<fir::SequenceType>()) { if (auto array = mlir::dyn_cast<fir::SequenceType>(normalisedResult)) {
hlfir::ExprType::Shape resultShape = hlfir::ExprType::Shape resultShape =
hlfir::ExprType::Shape{array.getShape()}; hlfir::ExprType::Shape{array.getShape()};
mlir::Type elementType = array.getEleTy(); mlir::Type elementType = array.getEleTy();
@ -341,7 +341,7 @@ mlir::Value HlfirTransposeLowering::lowerImpl(
hlfir::ExprType::Shape resultShape; hlfir::ExprType::Shape resultShape;
mlir::Type normalisedResult = mlir::Type normalisedResult =
hlfir::getFortranElementOrSequenceType(stmtResultType); hlfir::getFortranElementOrSequenceType(stmtResultType);
auto array = normalisedResult.cast<fir::SequenceType>(); auto array = mlir::cast<fir::SequenceType>(normalisedResult);
llvm::ArrayRef<int64_t> arrayShape = array.getShape(); llvm::ArrayRef<int64_t> arrayShape = array.getShape();
assert(arrayShape.size() == 2 && "arguments to transpose have a rank of 2"); assert(arrayShape.size() == 2 && "arguments to transpose have a rank of 2");
mlir::Type elementType = array.getEleTy(); mlir::Type elementType = array.getEleTy();

View File

@ -219,7 +219,7 @@ public:
static mlir::Type getType(Fortran::lower::AbstractConverter &converter, static mlir::Type getType(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) { const Fortran::semantics::Symbol &sym) {
fir::KindTy kind = fir::KindTy kind =
converter.genType(sym).cast<fir::CharacterType>().getFKind(); mlir::cast<fir::CharacterType>(converter.genType(sym)).getFKind();
return fir::BoxCharType::get(&converter.getMLIRContext(), kind); return fir::BoxCharType::get(&converter.getMLIRContext(), kind);
} }
@ -293,7 +293,7 @@ public:
mlir::Location loc = args.loc; mlir::Location loc = args.loc;
mlir::Value box = args.valueInTuple; mlir::Value box = args.valueInTuple;
if (Fortran::semantics::IsOptional(sym)) { if (Fortran::semantics::IsOptional(sym)) {
auto boxTy = box.getType().cast<fir::BaseBoxType>(); auto boxTy = mlir::cast<fir::BaseBoxType>(box.getType());
auto eleTy = boxTy.getEleTy(); auto eleTy = boxTy.getEleTy();
if (!fir::isa_ref_type(eleTy)) if (!fir::isa_ref_type(eleTy))
eleTy = builder.getRefType(eleTy); eleTy = builder.getRefType(eleTy);
@ -381,8 +381,8 @@ public:
const Fortran::semantics::Symbol &sym) { const Fortran::semantics::Symbol &sym) {
mlir::Type type = converter.genType(sym); mlir::Type type = converter.genType(sym);
bool isPolymorphic = Fortran::semantics::IsPolymorphic(sym); bool isPolymorphic = Fortran::semantics::IsPolymorphic(sym);
assert((type.isa<fir::SequenceType>() || assert((mlir::isa<fir::SequenceType>(type) ||
(isPolymorphic && type.isa<fir::ClassType>())) && (isPolymorphic && mlir::isa<fir::ClassType>(type))) &&
"must be a sequence type"); "must be a sequence type");
if (isPolymorphic) if (isPolymorphic)
return type; return type;
@ -459,7 +459,7 @@ public:
// (absent boxes are null descriptor addresses, not descriptors containing // (absent boxes are null descriptor addresses, not descriptors containing
// a null base address). // a null base address).
if (Fortran::semantics::IsOptional(sym)) { if (Fortran::semantics::IsOptional(sym)) {
auto boxTy = box.getType().cast<fir::BaseBoxType>(); auto boxTy = mlir::cast<fir::BaseBoxType>(box.getType());
auto eleTy = boxTy.getEleTy(); auto eleTy = boxTy.getEleTy();
if (!fir::isa_ref_type(eleTy)) if (!fir::isa_ref_type(eleTy))
eleTy = builder.getRefType(eleTy); eleTy = builder.getRefType(eleTy);
@ -527,7 +527,7 @@ walkCaptureCategories(T visitor, Fortran::lower::AbstractConverter &converter,
// `t` should be the result of getArgumentType, which has a type of // `t` should be the result of getArgumentType, which has a type of
// `!fir.ref<tuple<...>>`. // `!fir.ref<tuple<...>>`.
static mlir::TupleType unwrapTupleTy(mlir::Type t) { static mlir::TupleType unwrapTupleTy(mlir::Type t) {
return fir::dyn_cast_ptrEleTy(t).cast<mlir::TupleType>(); return mlir::cast<mlir::TupleType>(fir::dyn_cast_ptrEleTy(t));
} }
static mlir::Value genTupleCoor(fir::FirOpBuilder &builder, mlir::Location loc, static mlir::Value genTupleCoor(fir::FirOpBuilder &builder, mlir::Location loc,
@ -535,7 +535,7 @@ static mlir::Value genTupleCoor(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value offset) { mlir::Value offset) {
// fir.ref<fir.ref> and fir.ptr<fir.ref> are forbidden. Use // fir.ref<fir.ref> and fir.ptr<fir.ref> are forbidden. Use
// fir.llvm_ptr if needed. // fir.llvm_ptr if needed.
auto ty = varTy.isa<fir::ReferenceType>() auto ty = mlir::isa<fir::ReferenceType>(varTy)
? mlir::Type(fir::LLVMPointerType::get(varTy)) ? mlir::Type(fir::LLVMPointerType::get(varTy))
: mlir::Type(builder.getRefType(varTy)); : mlir::Type(builder.getRefType(varTy));
return builder.create<fir::CoordinateOp>(loc, ty, tupleArg, offset); return builder.create<fir::CoordinateOp>(loc, ty, tupleArg, offset);

View File

@ -168,7 +168,7 @@ static constexpr fir::runtime::FuncTypeBuilderFunc getTypeModel() {
} }
inline int64_t getLength(mlir::Type argTy) { inline int64_t getLength(mlir::Type argTy) {
return argTy.cast<fir::SequenceType>().getShape()[0]; return mlir::cast<fir::SequenceType>(argTy).getShape()[0];
} }
/// Get (or generate) the MLIR FuncOp for a given IO runtime function. /// Get (or generate) the MLIR FuncOp for a given IO runtime function.
@ -656,11 +656,11 @@ static void genNamelistIO(Fortran::lower::AbstractConverter &converter,
static mlir::func::FuncOp getOutputFunc(mlir::Location loc, static mlir::func::FuncOp getOutputFunc(mlir::Location loc,
fir::FirOpBuilder &builder, fir::FirOpBuilder &builder,
mlir::Type type, bool isFormatted) { mlir::Type type, bool isFormatted) {
if (fir::unwrapPassByRefType(type).isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(type)))
return getIORuntimeFunc<mkIOKey(OutputDerivedType)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputDerivedType)>(loc, builder);
if (!isFormatted) if (!isFormatted)
return getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc, builder);
if (auto ty = type.dyn_cast<mlir::IntegerType>()) { if (auto ty = mlir::dyn_cast<mlir::IntegerType>(type)) {
switch (ty.getWidth()) { switch (ty.getWidth()) {
case 1: case 1:
return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder);
@ -677,14 +677,14 @@ static mlir::func::FuncOp getOutputFunc(mlir::Location loc,
} }
llvm_unreachable("unknown OutputInteger kind"); llvm_unreachable("unknown OutputInteger kind");
} }
if (auto ty = type.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) {
if (auto width = ty.getWidth(); width == 32) if (auto width = ty.getWidth(); width == 32)
return getIORuntimeFunc<mkIOKey(OutputReal32)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputReal32)>(loc, builder);
else if (width == 64) else if (width == 64)
return getIORuntimeFunc<mkIOKey(OutputReal64)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputReal64)>(loc, builder);
} }
auto kindMap = fir::getKindMapping(builder.getModule()); auto kindMap = fir::getKindMapping(builder.getModule());
if (auto ty = type.dyn_cast<fir::ComplexType>()) { if (auto ty = mlir::dyn_cast<fir::ComplexType>(type)) {
// COMPLEX(KIND=k) corresponds to a pair of REAL(KIND=k). // COMPLEX(KIND=k) corresponds to a pair of REAL(KIND=k).
auto width = kindMap.getRealBitsize(ty.getFKind()); auto width = kindMap.getRealBitsize(ty.getFKind());
if (width == 32) if (width == 32)
@ -692,7 +692,7 @@ static mlir::func::FuncOp getOutputFunc(mlir::Location loc,
else if (width == 64) else if (width == 64)
return getIORuntimeFunc<mkIOKey(OutputComplex64)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputComplex64)>(loc, builder);
} }
if (type.isa<fir::LogicalType>()) if (mlir::isa<fir::LogicalType>(type))
return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder); return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder);
if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) { if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) {
// TODO: What would it mean if the default CHARACTER KIND is set to a wide // TODO: What would it mean if the default CHARACTER KIND is set to a wide
@ -731,14 +731,14 @@ static void genOutputItemList(
mlir::func::FuncOp outputFunc = mlir::func::FuncOp outputFunc =
getOutputFunc(loc, builder, itemTy, isFormatted); getOutputFunc(loc, builder, itemTy, isFormatted);
mlir::Type argType = outputFunc.getFunctionType().getInput(1); mlir::Type argType = outputFunc.getFunctionType().getInput(1);
assert((isFormatted || argType.isa<fir::BoxType>()) && assert((isFormatted || mlir::isa<fir::BoxType>(argType)) &&
"expect descriptor for unformatted IO runtime"); "expect descriptor for unformatted IO runtime");
llvm::SmallVector<mlir::Value> outputFuncArgs = {cookie}; llvm::SmallVector<mlir::Value> outputFuncArgs = {cookie};
fir::factory::CharacterExprHelper helper{builder, loc}; fir::factory::CharacterExprHelper helper{builder, loc};
if (argType.isa<fir::BoxType>()) { if (mlir::isa<fir::BoxType>(argType)) {
mlir::Value box = fir::getBase(converter.genExprBox(loc, *expr, stmtCtx)); mlir::Value box = fir::getBase(converter.genExprBox(loc, *expr, stmtCtx));
outputFuncArgs.push_back(builder.createConvert(loc, argType, box)); outputFuncArgs.push_back(builder.createConvert(loc, argType, box));
if (fir::unwrapPassByRefType(itemTy).isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(itemTy)))
outputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter)); outputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter));
} else if (helper.isCharacterScalar(itemTy)) { } else if (helper.isCharacterScalar(itemTy)) {
fir::ExtendedValue exv = converter.genExprAddr(loc, expr, stmtCtx); fir::ExtendedValue exv = converter.genExprAddr(loc, expr, stmtCtx);
@ -773,29 +773,29 @@ static void genOutputItemList(
static mlir::func::FuncOp getInputFunc(mlir::Location loc, static mlir::func::FuncOp getInputFunc(mlir::Location loc,
fir::FirOpBuilder &builder, fir::FirOpBuilder &builder,
mlir::Type type, bool isFormatted) { mlir::Type type, bool isFormatted) {
if (fir::unwrapPassByRefType(type).isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(type)))
return getIORuntimeFunc<mkIOKey(InputDerivedType)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputDerivedType)>(loc, builder);
if (!isFormatted) if (!isFormatted)
return getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc, builder);
if (auto ty = type.dyn_cast<mlir::IntegerType>()) if (auto ty = mlir::dyn_cast<mlir::IntegerType>(type))
return ty.getWidth() == 1 return ty.getWidth() == 1
? getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder) ? getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder)
: getIORuntimeFunc<mkIOKey(InputInteger)>(loc, builder); : getIORuntimeFunc<mkIOKey(InputInteger)>(loc, builder);
if (auto ty = type.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) {
if (auto width = ty.getWidth(); width == 32) if (auto width = ty.getWidth(); width == 32)
return getIORuntimeFunc<mkIOKey(InputReal32)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputReal32)>(loc, builder);
else if (width == 64) else if (width == 64)
return getIORuntimeFunc<mkIOKey(InputReal64)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputReal64)>(loc, builder);
} }
auto kindMap = fir::getKindMapping(builder.getModule()); auto kindMap = fir::getKindMapping(builder.getModule());
if (auto ty = type.dyn_cast<fir::ComplexType>()) { if (auto ty = mlir::dyn_cast<fir::ComplexType>(type)) {
auto width = kindMap.getRealBitsize(ty.getFKind()); auto width = kindMap.getRealBitsize(ty.getFKind());
if (width == 32) if (width == 32)
return getIORuntimeFunc<mkIOKey(InputComplex32)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputComplex32)>(loc, builder);
else if (width == 64) else if (width == 64)
return getIORuntimeFunc<mkIOKey(InputComplex64)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputComplex64)>(loc, builder);
} }
if (type.isa<fir::LogicalType>()) if (mlir::isa<fir::LogicalType>(type))
return getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder); return getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder);
if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) { if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) {
auto asciiKind = kindMap.defaultCharacterKind(); auto asciiKind = kindMap.defaultCharacterKind();
@ -830,12 +830,12 @@ createIoRuntimeCallForItem(Fortran::lower::AbstractConverter &converter,
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type argType = inputFunc.getFunctionType().getInput(1); mlir::Type argType = inputFunc.getFunctionType().getInput(1);
llvm::SmallVector<mlir::Value> inputFuncArgs = {cookie}; llvm::SmallVector<mlir::Value> inputFuncArgs = {cookie};
if (argType.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(argType)) {
mlir::Value box = fir::getBase(item); mlir::Value box = fir::getBase(item);
auto boxTy = box.getType().dyn_cast<fir::BaseBoxType>(); auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType());
assert(boxTy && "must be previously emboxed"); assert(boxTy && "must be previously emboxed");
inputFuncArgs.push_back(builder.createConvert(loc, argType, box)); inputFuncArgs.push_back(builder.createConvert(loc, argType, box));
if (fir::unwrapPassByRefType(boxTy).isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(boxTy)))
inputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter)); inputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter));
} else { } else {
mlir::Value itemAddr = fir::getBase(item); mlir::Value itemAddr = fir::getBase(item);
@ -846,16 +846,16 @@ createIoRuntimeCallForItem(Fortran::lower::AbstractConverter &converter,
mlir::Value len = fir::getLen(item); mlir::Value len = fir::getLen(item);
inputFuncArgs.push_back(builder.createConvert( inputFuncArgs.push_back(builder.createConvert(
loc, inputFunc.getFunctionType().getInput(2), len)); loc, inputFunc.getFunctionType().getInput(2), len));
} else if (itemTy.isa<mlir::IntegerType>()) { } else if (mlir::isa<mlir::IntegerType>(itemTy)) {
inputFuncArgs.push_back(builder.create<mlir::arith::ConstantOp>( inputFuncArgs.push_back(builder.create<mlir::arith::ConstantOp>(
loc, builder.getI32IntegerAttr( loc, builder.getI32IntegerAttr(
itemTy.cast<mlir::IntegerType>().getWidth() / 8))); mlir::cast<mlir::IntegerType>(itemTy).getWidth() / 8)));
} }
} }
auto call = builder.create<fir::CallOp>(loc, inputFunc, inputFuncArgs); auto call = builder.create<fir::CallOp>(loc, inputFunc, inputFuncArgs);
auto itemAddr = fir::getBase(item); auto itemAddr = fir::getBase(item);
auto itemTy = fir::unwrapRefType(itemAddr.getType()); auto itemTy = fir::unwrapRefType(itemAddr.getType());
if (itemTy.isa<fir::LogicalType>()) if (mlir::isa<fir::LogicalType>(itemTy))
boolRefToLogical(loc, builder, itemAddr); boolRefToLogical(loc, builder, itemAddr);
return call.getResult(0); return call.getResult(0);
} }
@ -886,7 +886,7 @@ static void genInputItemList(Fortran::lower::AbstractConverter &converter,
mlir::func::FuncOp inputFunc = getInputFunc( mlir::func::FuncOp inputFunc = getInputFunc(
loc, builder, vectorSubscriptBox.getElementType(), isFormatted); loc, builder, vectorSubscriptBox.getElementType(), isFormatted);
const bool mustBox = const bool mustBox =
inputFunc.getFunctionType().getInput(1).isa<fir::BoxType>(); mlir::isa<fir::BoxType>(inputFunc.getFunctionType().getInput(1));
if (!checkResult) { if (!checkResult) {
auto elementalGenerator = [&](const fir::ExtendedValue &element) { auto elementalGenerator = [&](const fir::ExtendedValue &element) {
createIoRuntimeCallForItem(converter, loc, inputFunc, cookie, createIoRuntimeCallForItem(converter, loc, inputFunc, cookie,
@ -911,9 +911,10 @@ static void genInputItemList(Fortran::lower::AbstractConverter &converter,
mlir::Type itemTy = converter.genType(*expr); mlir::Type itemTy = converter.genType(*expr);
mlir::func::FuncOp inputFunc = mlir::func::FuncOp inputFunc =
getInputFunc(loc, builder, itemTy, isFormatted); getInputFunc(loc, builder, itemTy, isFormatted);
auto itemExv = inputFunc.getFunctionType().getInput(1).isa<fir::BoxType>() auto itemExv =
? converter.genExprBox(loc, *expr, stmtCtx) mlir::isa<fir::BoxType>(inputFunc.getFunctionType().getInput(1))
: converter.genExprAddr(loc, expr, stmtCtx); ? converter.genExprBox(loc, *expr, stmtCtx)
: converter.genExprAddr(loc, expr, stmtCtx);
ok = createIoRuntimeCallForItem(converter, loc, inputFunc, cookie, itemExv); ok = createIoRuntimeCallForItem(converter, loc, inputFunc, cookie, itemExv);
} }
} }
@ -1772,8 +1773,8 @@ static mlir::Value genIOUnitNumber(Fortran::lower::AbstractConverter &converter,
auto &builder = converter.getFirOpBuilder(); auto &builder = converter.getFirOpBuilder();
auto rawUnit = fir::getBase(converter.genExprValue(loc, iounit, stmtCtx)); auto rawUnit = fir::getBase(converter.genExprValue(loc, iounit, stmtCtx));
unsigned rawUnitWidth = unsigned rawUnitWidth =
rawUnit.getType().cast<mlir::IntegerType>().getWidth(); mlir::cast<mlir::IntegerType>(rawUnit.getType()).getWidth();
unsigned runtimeArgWidth = ty.cast<mlir::IntegerType>().getWidth(); unsigned runtimeArgWidth = mlir::cast<mlir::IntegerType>(ty).getWidth();
// The IO runtime supports `int` unit numbers, if the unit number may // The IO runtime supports `int` unit numbers, if the unit number may
// overflow when passed to the IO runtime, check that the unit number is // overflow when passed to the IO runtime, check that the unit number is
// in range before calling the BeginXXX. // in range before calling the BeginXXX.
@ -2331,7 +2332,7 @@ mlir::Value genInquireSpec<Fortran::parser::InquireSpec::IntVar>(
if (!eleTy) if (!eleTy)
fir::emitFatalError(loc, fir::emitFatalError(loc,
"internal error: expected a memory reference type"); "internal error: expected a memory reference type");
auto width = eleTy.cast<mlir::IntegerType>().getWidth(); auto width = mlir::cast<mlir::IntegerType>(eleTy).getWidth();
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
mlir::Value kind = builder.createIntegerConstant(loc, idxTy, width / 8); mlir::Value kind = builder.createIntegerConstant(loc, idxTy, width / 8);
llvm::SmallVector<mlir::Value> args = { llvm::SmallVector<mlir::Value> args = {

View File

@ -65,7 +65,7 @@ static Op createDataEntryOp(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::acc::DataClause dataClause, mlir::Type retTy, mlir::acc::DataClause dataClause, mlir::Type retTy,
mlir::Value isPresent = {}) { mlir::Value isPresent = {}) {
mlir::Value varPtrPtr; mlir::Value varPtrPtr;
if (auto boxTy = baseAddr.getType().dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(baseAddr.getType())) {
if (isPresent) { if (isPresent) {
mlir::Type ifRetTy = boxTy.getEleTy(); mlir::Type ifRetTy = boxTy.getEleTy();
if (!fir::isa_ref_type(ifRetTy)) if (!fir::isa_ref_type(ifRetTy))
@ -2658,7 +2658,7 @@ genACCHostDataOp(Fortran::lower::AbstractConverter &converter,
if (ifCond) { if (ifCond) {
if (auto cst = if (auto cst =
mlir::dyn_cast<mlir::arith::ConstantOp>(ifCond.getDefiningOp())) mlir::dyn_cast<mlir::arith::ConstantOp>(ifCond.getDefiningOp()))
if (auto boolAttr = cst.getValue().dyn_cast<mlir::BoolAttr>()) { if (auto boolAttr = mlir::dyn_cast<mlir::BoolAttr>(cst.getValue())) {
if (boolAttr.getValue()) { if (boolAttr.getValue()) {
// get rid of the if condition if it is always true. // get rid of the if condition if it is always true.
ifCond = mlir::Value(); ifCond = mlir::Value();

View File

@ -23,10 +23,10 @@ namespace omp {
/// Check for unsupported map operand types. /// Check for unsupported map operand types.
static void checkMapType(mlir::Location location, mlir::Type type) { static void checkMapType(mlir::Location location, mlir::Type type) {
if (auto refType = type.dyn_cast<fir::ReferenceType>()) if (auto refType = mlir::dyn_cast<fir::ReferenceType>(type))
type = refType.getElementType(); type = refType.getElementType();
if (auto boxType = type.dyn_cast_or_null<fir::BoxType>()) if (auto boxType = mlir::dyn_cast_or_null<fir::BoxType>(type))
if (!boxType.getElementType().isa<fir::PointerType>()) if (!mlir::isa<fir::PointerType>(boxType.getElementType()))
TODO(location, "OMPD_target_data MapOperand BoxType"); TODO(location, "OMPD_target_data MapOperand BoxType");
} }
@ -814,7 +814,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location loc,
llvm::ArrayRef<mlir::Value> members, uint64_t mapType, llvm::ArrayRef<mlir::Value> members, uint64_t mapType,
mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type retTy, mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type retTy,
bool isVal) { bool isVal) {
if (auto boxTy = baseAddr.getType().dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(baseAddr.getType())) {
baseAddr = builder.create<fir::BoxAddrOp>(loc, baseAddr); baseAddr = builder.create<fir::BoxAddrOp>(loc, baseAddr);
retTy = baseAddr.getType(); retTy = baseAddr.getType();
} }

View File

@ -84,7 +84,7 @@ static fir::GlobalOp globalInitialization(
// Create default initialization for non-character scalar. // Create default initialization for non-character scalar.
if (Fortran::semantics::IsAllocatableOrObjectPointer(&sym)) { if (Fortran::semantics::IsAllocatableOrObjectPointer(&sym)) {
mlir::Type baseAddrType = ty.dyn_cast<fir::BoxType>().getEleTy(); mlir::Type baseAddrType = mlir::dyn_cast<fir::BoxType>(ty).getEleTy();
Fortran::lower::createGlobalInitialization( Fortran::lower::createGlobalInitialization(
firOpBuilder, global, [&](fir::FirOpBuilder &b) { firOpBuilder, global, [&](fir::FirOpBuilder &b) {
mlir::Value nullAddr = mlir::Value nullAddr =
@ -778,7 +778,7 @@ static void genBodyOfTargetDataOp(
for (auto [argIndex, argSymbol] : llvm::enumerate(useDeviceSymbols)) { for (auto [argIndex, argSymbol] : llvm::enumerate(useDeviceSymbols)) {
const mlir::BlockArgument &arg = region.front().getArgument(argIndex); const mlir::BlockArgument &arg = region.front().getArgument(argIndex);
fir::ExtendedValue extVal = converter.getSymbolExtendedValue(*argSymbol); fir::ExtendedValue extVal = converter.getSymbolExtendedValue(*argSymbol);
if (auto refType = arg.getType().dyn_cast<fir::ReferenceType>()) { if (auto refType = mlir::dyn_cast<fir::ReferenceType>(arg.getType())) {
if (fir::isa_builtin_cptr_type(refType.getElementType())) { if (fir::isa_builtin_cptr_type(refType.getElementType())) {
converter.bindSymbol(*argSymbol, arg); converter.bindSymbol(*argSymbol, arg);
} else { } else {
@ -1570,13 +1570,15 @@ genTargetOp(Fortran::lower::AbstractConverter &converter,
Fortran::lower::AddrAndBoundsInfo info = getDataOperandBaseAddr( Fortran::lower::AddrAndBoundsInfo info = getDataOperandBaseAddr(
converter, firOpBuilder, sym, converter.getCurrentLocation()); converter, firOpBuilder, sym, converter.getCurrentLocation());
if (fir::unwrapRefType(info.addr.getType()).isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(
fir::unwrapRefType(info.addr.getType())))
bounds = bounds =
Fortran::lower::genBoundsOpsFromBox<mlir::omp::MapBoundsOp, Fortran::lower::genBoundsOpsFromBox<mlir::omp::MapBoundsOp,
mlir::omp::MapBoundsType>( mlir::omp::MapBoundsType>(
firOpBuilder, converter.getCurrentLocation(), converter, firOpBuilder, converter.getCurrentLocation(), converter,
dataExv, info); dataExv, info);
if (fir::unwrapRefType(info.addr.getType()).isa<fir::SequenceType>()) { if (mlir::isa<fir::SequenceType>(
fir::unwrapRefType(info.addr.getType()))) {
bool dataExvIsAssumedSize = bool dataExvIsAssumedSize =
Fortran::semantics::IsAssumedSizeArray(sym.GetUltimate()); Fortran::semantics::IsAssumedSizeArray(sym.GetUltimate());
bounds = Fortran::lower::genBaseBoundsOps<mlir::omp::MapBoundsOp, bounds = Fortran::lower::genBaseBoundsOps<mlir::omp::MapBoundsOp,
@ -1591,7 +1593,7 @@ genTargetOp(Fortran::lower::AbstractConverter &converter,
mlir::omp::VariableCaptureKind::ByRef; mlir::omp::VariableCaptureKind::ByRef;
mlir::Type eleType = baseOp.getType(); mlir::Type eleType = baseOp.getType();
if (auto refType = baseOp.getType().dyn_cast<fir::ReferenceType>()) if (auto refType = mlir::dyn_cast<fir::ReferenceType>(baseOp.getType()))
eleType = refType.getElementType(); eleType = refType.getElementType();
// If a variable is specified in declare target link and if device // If a variable is specified in declare target link and if device

View File

@ -138,7 +138,7 @@ ReductionProcessor::getReductionInitValue(mlir::Location loc, mlir::Type type,
TODO(loc, "Reduction of some types is not supported"); TODO(loc, "Reduction of some types is not supported");
switch (redId) { switch (redId) {
case ReductionIdentifier::MAX: { case ReductionIdentifier::MAX: {
if (auto ty = type.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) {
const llvm::fltSemantics &sem = ty.getFloatSemantics(); const llvm::fltSemantics &sem = ty.getFloatSemantics();
return builder.createRealConstant( return builder.createRealConstant(
loc, type, llvm::APFloat::getLargest(sem, /*Negative=*/true)); loc, type, llvm::APFloat::getLargest(sem, /*Negative=*/true));
@ -148,7 +148,7 @@ ReductionProcessor::getReductionInitValue(mlir::Location loc, mlir::Type type,
return builder.createIntegerConstant(loc, type, minInt); return builder.createIntegerConstant(loc, type, minInt);
} }
case ReductionIdentifier::MIN: { case ReductionIdentifier::MIN: {
if (auto ty = type.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) {
const llvm::fltSemantics &sem = ty.getFloatSemantics(); const llvm::fltSemantics &sem = ty.getFloatSemantics();
return builder.createRealConstant( return builder.createRealConstant(
loc, type, llvm::APFloat::getLargest(sem, /*Negative=*/false)); loc, type, llvm::APFloat::getLargest(sem, /*Negative=*/false));
@ -188,12 +188,12 @@ ReductionProcessor::getReductionInitValue(mlir::Location loc, mlir::Type type,
return fir::factory::Complex{builder, loc}.createComplex(type, initRe, return fir::factory::Complex{builder, loc}.createComplex(type, initRe,
initIm); initIm);
} }
if (type.isa<mlir::FloatType>()) if (mlir::isa<mlir::FloatType>(type))
return builder.create<mlir::arith::ConstantOp>( return builder.create<mlir::arith::ConstantOp>(
loc, type, loc, type,
builder.getFloatAttr(type, (double)getOperationIdentity(redId, loc))); builder.getFloatAttr(type, (double)getOperationIdentity(redId, loc)));
if (type.isa<fir::LogicalType>()) { if (mlir::isa<fir::LogicalType>(type)) {
mlir::Value intConst = builder.create<mlir::arith::ConstantOp>( mlir::Value intConst = builder.create<mlir::arith::ConstantOp>(
loc, builder.getI1Type(), loc, builder.getI1Type(),
builder.getIntegerAttr(builder.getI1Type(), builder.getIntegerAttr(builder.getI1Type(),
@ -474,11 +474,11 @@ createReductionCleanupRegion(fir::FirOpBuilder &builder, mlir::Location loc,
// like fir::unwrapSeqOrBoxedSeqType except it also works for non-sequence boxes // like fir::unwrapSeqOrBoxedSeqType except it also works for non-sequence boxes
static mlir::Type unwrapSeqOrBoxedType(mlir::Type ty) { static mlir::Type unwrapSeqOrBoxedType(mlir::Type ty) {
if (auto seqTy = ty.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
return seqTy.getEleTy(); return seqTy.getEleTy();
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
auto eleTy = fir::unwrapRefType(boxTy.getEleTy()); auto eleTy = fir::unwrapRefType(boxTy.getEleTy());
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
return seqTy.getEleTy(); return seqTy.getEleTy();
return eleTy; return eleTy;
} }
@ -790,7 +790,7 @@ void ReductionProcessor::addDeclareReduction(
for (mlir::Value symVal : reductionVars) { for (mlir::Value symVal : reductionVars) {
auto redType = mlir::cast<fir::ReferenceType>(symVal.getType()); auto redType = mlir::cast<fir::ReferenceType>(symVal.getType());
const auto &kindMap = firOpBuilder.getKindMap(); const auto &kindMap = firOpBuilder.getKindMap();
if (redType.getEleTy().isa<fir::LogicalType>()) if (mlir::isa<fir::LogicalType>(redType.getEleTy()))
decl = createDeclareReduction(firOpBuilder, decl = createDeclareReduction(firOpBuilder,
getReductionName(intrinsicOp, kindMap, getReductionName(intrinsicOp, kindMap,
firOpBuilder.getI1Type(), firOpBuilder.getI1Type(),
@ -816,7 +816,7 @@ void ReductionProcessor::addDeclareReduction(
mlir::Value symVal = converter.getSymbolAddress(*symbol); mlir::Value symVal = converter.getSymbolAddress(*symbol);
if (auto declOp = symVal.getDefiningOp<hlfir::DeclareOp>()) if (auto declOp = symVal.getDefiningOp<hlfir::DeclareOp>())
symVal = declOp.getBase(); symVal = declOp.getBase();
auto redType = symVal.getType().cast<fir::ReferenceType>(); auto redType = mlir::cast<fir::ReferenceType>(symVal.getType());
if (!redType.getEleTy().isIntOrIndexOrFloat()) if (!redType.getEleTy().isIntOrIndexOrFloat())
TODO(currentLocation, "User Defined Reduction on non-trivial type"); TODO(currentLocation, "User Defined Reduction on non-trivial type");
decl = createDeclareReduction( decl = createDeclareReduction(

View File

@ -105,7 +105,7 @@ private:
} }
mlir::Type gen(const Fortran::evaluate::Component &component) { mlir::Type gen(const Fortran::evaluate::Component &component) {
auto recTy = gen(component.base()).cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(gen(component.base()));
const Fortran::semantics::Symbol &componentSymbol = const Fortran::semantics::Symbol &componentSymbol =
component.GetLastSymbol(); component.GetLastSymbol();
// Parent components will not be found here, they are not part // Parent components will not be found here, they are not part

View File

@ -68,7 +68,7 @@ bool AliasAnalysis::Source::isPointerReference(mlir::Type ty) {
if (!eleTy) if (!eleTy)
return false; return false;
return fir::isPointerType(eleTy) || eleTy.isa<fir::PointerType>(); return fir::isPointerType(eleTy) || mlir::isa<fir::PointerType>(eleTy);
} }
bool AliasAnalysis::Source::isTargetOrPointer() const { bool AliasAnalysis::Source::isTargetOrPointer() const {
@ -81,7 +81,7 @@ bool AliasAnalysis::Source::isRecordWithPointerComponent() const {
if (!eleTy) if (!eleTy)
return false; return false;
// TO DO: Look for pointer components // TO DO: Look for pointer components
return eleTy.isa<fir::RecordType>(); return mlir::isa<fir::RecordType>(eleTy);
} }
AliasResult AliasAnalysis::alias(Value lhs, Value rhs) { AliasResult AliasAnalysis::alias(Value lhs, Value rhs) {

View File

@ -191,7 +191,7 @@ bool fir::MutableBoxValue::verify() const {
mlir::Type type = fir::dyn_cast_ptrEleTy(getAddr().getType()); mlir::Type type = fir::dyn_cast_ptrEleTy(getAddr().getType());
if (!type) if (!type)
return false; return false;
auto box = type.dyn_cast<fir::BaseBoxType>(); auto box = mlir::dyn_cast<fir::BaseBoxType>(type);
if (!box) if (!box)
return false; return false;
// A boxed value always takes a memory reference, // A boxed value always takes a memory reference,
@ -210,7 +210,7 @@ bool fir::MutableBoxValue::verify() const {
/// Debug verifier for BoxValue ctor. There is no guarantee this will /// Debug verifier for BoxValue ctor. There is no guarantee this will
/// always be called. /// always be called.
bool fir::BoxValue::verify() const { bool fir::BoxValue::verify() const {
if (!addr.getType().isa<fir::BaseBoxType>()) if (!mlir::isa<fir::BaseBoxType>(addr.getType()))
return false; return false;
if (!lbounds.empty() && lbounds.size() != rank()) if (!lbounds.empty() && lbounds.size() != rank())
return false; return false;

View File

@ -26,11 +26,11 @@
/// Unwrap all the ref and box types and return the inner element type. /// Unwrap all the ref and box types and return the inner element type.
static mlir::Type unwrapBoxAndRef(mlir::Type type) { static mlir::Type unwrapBoxAndRef(mlir::Type type) {
if (auto boxType = type.dyn_cast<fir::BoxCharType>()) if (auto boxType = mlir::dyn_cast<fir::BoxCharType>(type))
return boxType.getEleTy(); return boxType.getEleTy();
while (true) { while (true) {
type = fir::unwrapRefType(type); type = fir::unwrapRefType(type);
if (auto boxTy = type.dyn_cast<fir::BoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BoxType>(type))
type = boxTy.getEleTy(); type = boxTy.getEleTy();
else else
break; break;
@ -41,19 +41,19 @@ static mlir::Type unwrapBoxAndRef(mlir::Type type) {
/// Unwrap base fir.char<kind,len> type. /// Unwrap base fir.char<kind,len> type.
static fir::CharacterType recoverCharacterType(mlir::Type type) { static fir::CharacterType recoverCharacterType(mlir::Type type) {
type = fir::unwrapSequenceType(unwrapBoxAndRef(type)); type = fir::unwrapSequenceType(unwrapBoxAndRef(type));
if (auto charTy = type.dyn_cast<fir::CharacterType>()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(type))
return charTy; return charTy;
llvm::report_fatal_error("expected a character type"); llvm::report_fatal_error("expected a character type");
} }
bool fir::factory::CharacterExprHelper::isCharacterScalar(mlir::Type type) { bool fir::factory::CharacterExprHelper::isCharacterScalar(mlir::Type type) {
type = unwrapBoxAndRef(type); type = unwrapBoxAndRef(type);
return !type.isa<fir::SequenceType>() && fir::isa_char(type); return !mlir::isa<fir::SequenceType>(type) && fir::isa_char(type);
} }
bool fir::factory::CharacterExprHelper::isArray(mlir::Type type) { bool fir::factory::CharacterExprHelper::isArray(mlir::Type type) {
type = unwrapBoxAndRef(type); type = unwrapBoxAndRef(type);
if (auto seqTy = type.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type))
return fir::isa_char(seqTy.getEleTy()); return fir::isa_char(seqTy.getEleTy());
return false; return false;
} }
@ -92,7 +92,8 @@ getCompileTimeLength(const fir::CharBoxValue &box) {
/// Detect the precondition that the value `str` does not reside in memory. Such /// Detect the precondition that the value `str` does not reside in memory. Such
/// values will have a type `!fir.array<...x!fir.char<N>>` or `!fir.char<N>`. /// values will have a type `!fir.array<...x!fir.char<N>>` or `!fir.char<N>`.
LLVM_ATTRIBUTE_UNUSED static bool needToMaterialize(mlir::Value str) { LLVM_ATTRIBUTE_UNUSED static bool needToMaterialize(mlir::Value str) {
return str.getType().isa<fir::SequenceType>() || fir::isa_char(str.getType()); return mlir::isa<fir::SequenceType>(str.getType()) ||
fir::isa_char(str.getType());
} }
/// This is called only if `str` does not reside in memory. Such a bare string /// This is called only if `str` does not reside in memory. Such a bare string
@ -103,7 +104,7 @@ fir::factory::CharacterExprHelper::materializeValue(mlir::Value str) {
assert(needToMaterialize(str)); assert(needToMaterialize(str));
auto ty = str.getType(); auto ty = str.getType();
assert(isCharacterScalar(ty) && "expected scalar character"); assert(isCharacterScalar(ty) && "expected scalar character");
auto charTy = ty.dyn_cast<fir::CharacterType>(); auto charTy = mlir::dyn_cast<fir::CharacterType>(ty);
if (!charTy || charTy.getLen() == fir::CharacterType::unknownLen()) { if (!charTy || charTy.getLen() == fir::CharacterType::unknownLen()) {
LLVM_DEBUG(llvm::dbgs() << "cannot materialize: " << str << '\n'); LLVM_DEBUG(llvm::dbgs() << "cannot materialize: " << str << '\n');
llvm_unreachable("must be a !fir.char<N> type"); llvm_unreachable("must be a !fir.char<N> type");
@ -129,7 +130,7 @@ fir::factory::CharacterExprHelper::toExtendedValue(mlir::Value character,
if (auto eleType = fir::dyn_cast_ptrEleTy(type)) if (auto eleType = fir::dyn_cast_ptrEleTy(type))
type = eleType; type = eleType;
if (auto arrayType = type.dyn_cast<fir::SequenceType>()) { if (auto arrayType = mlir::dyn_cast<fir::SequenceType>(type)) {
type = arrayType.getEleTy(); type = arrayType.getEleTy();
auto indexType = builder.getIndexType(); auto indexType = builder.getIndexType();
for (auto extent : arrayType.getShape()) { for (auto extent : arrayType.getShape()) {
@ -145,10 +146,10 @@ fir::factory::CharacterExprHelper::toExtendedValue(mlir::Value character,
mlir::emitError(loc, "cannot retrieve array extents from type"); mlir::emitError(loc, "cannot retrieve array extents from type");
} }
if (auto charTy = type.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(type)) {
if (!resultLen && charTy.getLen() != fir::CharacterType::unknownLen()) if (!resultLen && charTy.getLen() != fir::CharacterType::unknownLen())
resultLen = builder.createIntegerConstant(loc, lenType, charTy.getLen()); resultLen = builder.createIntegerConstant(loc, lenType, charTy.getLen());
} else if (auto boxCharType = type.dyn_cast<fir::BoxCharType>()) { } else if (auto boxCharType = mlir::dyn_cast<fir::BoxCharType>(type)) {
auto refType = builder.getRefType(boxCharType.getEleTy()); auto refType = builder.getRefType(boxCharType.getEleTy());
// If the embox is accessible, use its operand to avoid filling // If the embox is accessible, use its operand to avoid filling
// the generated fir with embox/unbox. // the generated fir with embox/unbox.
@ -168,7 +169,7 @@ fir::factory::CharacterExprHelper::toExtendedValue(mlir::Value character,
if (!resultLen) { if (!resultLen) {
resultLen = boxCharLen; resultLen = boxCharLen;
} }
} else if (type.isa<fir::BoxType>()) { } else if (mlir::isa<fir::BoxType>(type)) {
mlir::emitError(loc, "descriptor or derived type not yet handled"); mlir::emitError(loc, "descriptor or derived type not yet handled");
} else { } else {
llvm_unreachable("Cannot translate mlir::Value to character ExtendedValue"); llvm_unreachable("Cannot translate mlir::Value to character ExtendedValue");
@ -221,7 +222,7 @@ fir::factory::CharacterExprHelper::createEmbox(const fir::CharBoxValue &box) {
fir::CharBoxValue fir::factory::CharacterExprHelper::toScalarCharacter( fir::CharBoxValue fir::factory::CharacterExprHelper::toScalarCharacter(
const fir::CharArrayBoxValue &box) { const fir::CharArrayBoxValue &box) {
if (box.getBuffer().getType().isa<fir::PointerType>()) if (mlir::isa<fir::PointerType>(box.getBuffer().getType()))
TODO(loc, "concatenating non contiguous character array into a scalar"); TODO(loc, "concatenating non contiguous character array into a scalar");
// TODO: add a fast path multiplying new length at compile time if the info is // TODO: add a fast path multiplying new length at compile time if the info is
@ -655,7 +656,7 @@ fir::factory::CharacterExprHelper::createUnboxChar(mlir::Value boxChar) {
} }
bool fir::factory::CharacterExprHelper::isCharacterLiteral(mlir::Type type) { bool fir::factory::CharacterExprHelper::isCharacterLiteral(mlir::Type type) {
if (auto seqType = type.dyn_cast<fir::SequenceType>()) if (auto seqType = mlir::dyn_cast<fir::SequenceType>(type))
return (seqType.getShape().size() == 1) && return (seqType.getShape().size() == 1) &&
fir::isa_char(seqType.getEleTy()); fir::isa_char(seqType.getEleTy());
return false; return false;
@ -728,9 +729,9 @@ mlir::Value fir::factory::CharacterExprHelper::getLength(mlir::Value memref) {
if (charType.hasConstantLen()) if (charType.hasConstantLen())
return builder.createIntegerConstant(loc, builder.getCharacterLengthType(), return builder.createIntegerConstant(loc, builder.getCharacterLengthType(),
charType.getLen()); charType.getLen());
if (memrefType.isa<fir::BoxType>()) if (mlir::isa<fir::BoxType>(memrefType))
return readLengthFromBox(memref); return readLengthFromBox(memref);
if (memrefType.isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(memrefType))
return createUnboxChar(memref).second; return createUnboxChar(memref).second;
// Length cannot be deduced from memref. // Length cannot be deduced from memref.
@ -742,14 +743,14 @@ fir::factory::extractCharacterProcedureTuple(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Location loc,
mlir::Value tuple, mlir::Value tuple,
bool openBoxProc) { bool openBoxProc) {
mlir::TupleType tupleType = tuple.getType().cast<mlir::TupleType>(); mlir::TupleType tupleType = mlir::cast<mlir::TupleType>(tuple.getType());
mlir::Value addr = builder.create<fir::ExtractValueOp>( mlir::Value addr = builder.create<fir::ExtractValueOp>(
loc, tupleType.getType(0), tuple, loc, tupleType.getType(0), tuple,
builder.getArrayAttr( builder.getArrayAttr(
{builder.getIntegerAttr(builder.getIndexType(), 0)})); {builder.getIntegerAttr(builder.getIndexType(), 0)}));
mlir::Value proc = [&]() -> mlir::Value { mlir::Value proc = [&]() -> mlir::Value {
if (openBoxProc) if (openBoxProc)
if (auto addrTy = addr.getType().dyn_cast<fir::BoxProcType>()) if (auto addrTy = mlir::dyn_cast<fir::BoxProcType>(addr.getType()))
return builder.create<fir::BoxAddrOp>(loc, addrTy.getEleTy(), addr); return builder.create<fir::BoxAddrOp>(loc, addrTy.getEleTy(), addr);
return addr; return addr;
}(); }();
@ -763,7 +764,7 @@ fir::factory::extractCharacterProcedureTuple(fir::FirOpBuilder &builder,
mlir::Value fir::factory::createCharacterProcedureTuple( mlir::Value fir::factory::createCharacterProcedureTuple(
fir::FirOpBuilder &builder, mlir::Location loc, mlir::Type argTy, fir::FirOpBuilder &builder, mlir::Location loc, mlir::Type argTy,
mlir::Value addr, mlir::Value len) { mlir::Value addr, mlir::Value len) {
mlir::TupleType tupleType = argTy.cast<mlir::TupleType>(); mlir::TupleType tupleType = mlir::cast<mlir::TupleType>(argTy);
addr = builder.createConvert(loc, tupleType.getType(0), addr); addr = builder.createConvert(loc, tupleType.getType(0), addr);
if (len) if (len)
len = builder.createConvert(loc, tupleType.getType(1), len); len = builder.createConvert(loc, tupleType.getType(1), len);
@ -866,7 +867,7 @@ fir::factory::convertCharacterKind(fir::FirOpBuilder &builder,
auto kindMap = builder.getKindMap(); auto kindMap = builder.getKindMap();
mlir::Value boxCharAddr = srcBoxChar.getAddr(); mlir::Value boxCharAddr = srcBoxChar.getAddr();
auto fromTy = boxCharAddr.getType(); auto fromTy = boxCharAddr.getType();
if (auto charTy = fromTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(fromTy)) {
// boxchar is a value, not a variable. Turn it into a temporary. // boxchar is a value, not a variable. Turn it into a temporary.
// As a value, it ought to have a constant LEN value. // As a value, it ought to have a constant LEN value.
assert(charTy.hasConstantLen() && "must have constant length"); assert(charTy.hasConstantLen() && "must have constant length");
@ -875,7 +876,7 @@ fir::factory::convertCharacterKind(fir::FirOpBuilder &builder,
boxCharAddr = tmp; boxCharAddr = tmp;
} }
auto fromBits = kindMap.getCharacterBitsize( auto fromBits = kindMap.getCharacterBitsize(
fir::unwrapRefType(fromTy).cast<fir::CharacterType>().getFKind()); mlir::cast<fir::CharacterType>(fir::unwrapRefType(fromTy)).getFKind());
auto toBits = kindMap.getCharacterBitsize(toKind); auto toBits = kindMap.getCharacterBitsize(toKind);
if (toBits < fromBits) { if (toBits < fromBits) {
// Scale by relative ratio to give a buffer of the same length. // Scale by relative ratio to give a buffer of the same length.

View File

@ -14,7 +14,8 @@
mlir::Type mlir::Type
fir::factory::Complex::getComplexPartType(mlir::Type complexType) const { fir::factory::Complex::getComplexPartType(mlir::Type complexType) const {
return builder.getRealType(complexType.cast<fir::ComplexType>().getFKind()); return builder.getRealType(
mlir::cast<fir::ComplexType>(complexType).getFKind());
} }
mlir::Type fir::factory::Complex::getComplexPartType(mlir::Value cplx) const { mlir::Type fir::factory::Complex::getComplexPartType(mlir::Value cplx) const {

View File

@ -90,7 +90,7 @@ fir::FirOpBuilder::getNamedGlobal(mlir::ModuleOp modOp,
} }
mlir::Type fir::FirOpBuilder::getRefType(mlir::Type eleTy) { mlir::Type fir::FirOpBuilder::getRefType(mlir::Type eleTy) {
assert(!eleTy.isa<fir::ReferenceType>() && "cannot be a reference type"); assert(!mlir::isa<fir::ReferenceType>(eleTy) && "cannot be a reference type");
return fir::ReferenceType::get(eleTy); return fir::ReferenceType::get(eleTy);
} }
@ -147,7 +147,7 @@ mlir::Value
fir::FirOpBuilder::createRealConstant(mlir::Location loc, mlir::Type fltTy, fir::FirOpBuilder::createRealConstant(mlir::Location loc, mlir::Type fltTy,
llvm::APFloat::integerPart val) { llvm::APFloat::integerPart val) {
auto apf = [&]() -> llvm::APFloat { auto apf = [&]() -> llvm::APFloat {
if (auto ty = fltTy.dyn_cast<fir::RealType>()) if (auto ty = mlir::dyn_cast<fir::RealType>(fltTy))
return llvm::APFloat(kindMap.getFloatSemantics(ty.getFKind()), val); return llvm::APFloat(kindMap.getFloatSemantics(ty.getFKind()), val);
if (fltTy.isF16()) if (fltTy.isF16())
return llvm::APFloat(llvm::APFloat::IEEEhalf(), val); return llvm::APFloat(llvm::APFloat::IEEEhalf(), val);
@ -169,7 +169,7 @@ fir::FirOpBuilder::createRealConstant(mlir::Location loc, mlir::Type fltTy,
mlir::Value fir::FirOpBuilder::createRealConstant(mlir::Location loc, mlir::Value fir::FirOpBuilder::createRealConstant(mlir::Location loc,
mlir::Type fltTy, mlir::Type fltTy,
const llvm::APFloat &value) { const llvm::APFloat &value) {
if (fltTy.isa<mlir::FloatType>()) { if (mlir::isa<mlir::FloatType>(fltTy)) {
auto attr = getFloatAttr(fltTy, value); auto attr = getFloatAttr(fltTy, value);
return create<mlir::arith::ConstantOp>(loc, fltTy, attr); return create<mlir::arith::ConstantOp>(loc, fltTy, attr);
} }
@ -178,7 +178,7 @@ mlir::Value fir::FirOpBuilder::createRealConstant(mlir::Location loc,
static llvm::SmallVector<mlir::Value> static llvm::SmallVector<mlir::Value>
elideExtentsAlreadyInType(mlir::Type type, mlir::ValueRange shape) { elideExtentsAlreadyInType(mlir::Type type, mlir::ValueRange shape) {
auto arrTy = type.dyn_cast<fir::SequenceType>(); auto arrTy = mlir::dyn_cast<fir::SequenceType>(type);
if (shape.empty() || !arrTy) if (shape.empty() || !arrTy)
return {}; return {};
// elide the constant dimensions before construction // elide the constant dimensions before construction
@ -195,7 +195,7 @@ static llvm::SmallVector<mlir::Value>
elideLengthsAlreadyInType(mlir::Type type, mlir::ValueRange lenParams) { elideLengthsAlreadyInType(mlir::Type type, mlir::ValueRange lenParams) {
if (lenParams.empty()) if (lenParams.empty())
return {}; return {};
if (auto arrTy = type.dyn_cast<fir::SequenceType>()) if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(type))
type = arrTy.getEleTy(); type = arrTy.getEleTy();
if (fir::hasDynamicSize(type)) if (fir::hasDynamicSize(type))
return lenParams; return lenParams;
@ -264,7 +264,7 @@ mlir::Value fir::FirOpBuilder::createTemporaryAlloc(
mlir::Location loc, mlir::Type type, llvm::StringRef name, mlir::Location loc, mlir::Type type, llvm::StringRef name,
mlir::ValueRange lenParams, mlir::ValueRange shape, mlir::ValueRange lenParams, mlir::ValueRange shape,
llvm::ArrayRef<mlir::NamedAttribute> attrs) { llvm::ArrayRef<mlir::NamedAttribute> attrs) {
assert(!type.isa<fir::ReferenceType>() && "cannot be a reference"); assert(!mlir::isa<fir::ReferenceType>(type) && "cannot be a reference");
// If the alloca is inside an OpenMP Op which will be outlined then pin // If the alloca is inside an OpenMP Op which will be outlined then pin
// the alloca here. // the alloca here.
const bool pinned = const bool pinned =
@ -310,7 +310,7 @@ mlir::Value fir::FirOpBuilder::createHeapTemporary(
llvm::SmallVector<mlir::Value> dynamicLength = llvm::SmallVector<mlir::Value> dynamicLength =
elideLengthsAlreadyInType(type, lenParams); elideLengthsAlreadyInType(type, lenParams);
assert(!type.isa<fir::ReferenceType>() && "cannot be a reference"); assert(!mlir::isa<fir::ReferenceType>(type) && "cannot be a reference");
return create<fir::AllocMemOp>(loc, type, /*unique_name=*/llvm::StringRef{}, return create<fir::AllocMemOp>(loc, type, /*unique_name=*/llvm::StringRef{},
name, dynamicLength, dynamicShape, attrs); name, dynamicLength, dynamicShape, attrs);
} }
@ -376,8 +376,9 @@ mlir::Value fir::FirOpBuilder::convertWithSemantics(
// imaginary part is zero // imaginary part is zero
auto eleTy = helper.getComplexPartType(toTy); auto eleTy = helper.getComplexPartType(toTy);
auto cast = createConvert(loc, eleTy, val); auto cast = createConvert(loc, eleTy, val);
llvm::APFloat zero{ llvm::APFloat zero{kindMap.getFloatSemantics(
kindMap.getFloatSemantics(toTy.cast<fir::ComplexType>().getFKind()), 0}; mlir::cast<fir::ComplexType>(toTy).getFKind()),
0};
auto imag = createRealConstant(loc, eleTy, zero); auto imag = createRealConstant(loc, eleTy, zero);
return helper.createComplex(toTy, cast, imag); return helper.createComplex(toTy, cast, imag);
} }
@ -388,14 +389,14 @@ mlir::Value fir::FirOpBuilder::convertWithSemantics(
return createConvert(loc, toTy, rp); return createConvert(loc, toTy, rp);
} }
if (allowCharacterConversion) { if (allowCharacterConversion) {
if (fromTy.isa<fir::BoxCharType>()) { if (mlir::isa<fir::BoxCharType>(fromTy)) {
// Extract the address of the character string and pass it // Extract the address of the character string and pass it
fir::factory::CharacterExprHelper charHelper{*this, loc}; fir::factory::CharacterExprHelper charHelper{*this, loc};
std::pair<mlir::Value, mlir::Value> unboxchar = std::pair<mlir::Value, mlir::Value> unboxchar =
charHelper.createUnboxChar(val); charHelper.createUnboxChar(val);
return createConvert(loc, toTy, unboxchar.first); return createConvert(loc, toTy, unboxchar.first);
} }
if (auto boxType = toTy.dyn_cast<fir::BoxCharType>()) { if (auto boxType = mlir::dyn_cast<fir::BoxCharType>(toTy)) {
// Extract the address of the actual argument and create a boxed // Extract the address of the actual argument and create a boxed
// character value with an undefined length // character value with an undefined length
// TODO: We should really calculate the total size of the actual // TODO: We should really calculate the total size of the actual
@ -415,10 +416,10 @@ mlir::Value fir::FirOpBuilder::convertWithSemantics(
"element types expected to match")); "element types expected to match"));
return create<fir::BoxAddrOp>(loc, toTy, val); return create<fir::BoxAddrOp>(loc, toTy, val);
} }
if (fir::isa_ref_type(fromTy) && toTy.isa<fir::BoxProcType>()) { if (fir::isa_ref_type(fromTy) && mlir::isa<fir::BoxProcType>(toTy)) {
// Call is expecting a boxed procedure, not a reference to other data type. // Call is expecting a boxed procedure, not a reference to other data type.
// Convert the reference to a procedure and embox it. // Convert the reference to a procedure and embox it.
mlir::Type procTy = toTy.cast<fir::BoxProcType>().getEleTy(); mlir::Type procTy = mlir::cast<fir::BoxProcType>(toTy).getEleTy();
mlir::Value proc = createConvert(loc, procTy, val); mlir::Value proc = createConvert(loc, procTy, val);
return create<fir::EmboxProcOp>(loc, toTy, proc); return create<fir::EmboxProcOp>(loc, toTy, proc);
} }
@ -428,7 +429,7 @@ mlir::Value fir::FirOpBuilder::convertWithSemantics(
if (((fir::isPolymorphicType(fromTy) && if (((fir::isPolymorphicType(fromTy) &&
(fir::isAllocatableType(fromTy) || fir::isPointerType(fromTy)) && (fir::isAllocatableType(fromTy) || fir::isPointerType(fromTy)) &&
fir::isPolymorphicType(toTy)) || fir::isPolymorphicType(toTy)) ||
(fir::isPolymorphicType(fromTy) && toTy.isa<fir::BoxType>())) && (fir::isPolymorphicType(fromTy) && mlir::isa<fir::BoxType>(toTy))) &&
!(fir::isUnlimitedPolymorphicType(fromTy) && fir::isAssumedType(toTy))) !(fir::isUnlimitedPolymorphicType(fromTy) && fir::isAssumedType(toTy)))
return create<fir::ReboxOp>(loc, toTy, val, mlir::Value{}, return create<fir::ReboxOp>(loc, toTy, val, mlir::Value{},
/*slice=*/mlir::Value{}); /*slice=*/mlir::Value{});
@ -581,7 +582,7 @@ mlir::Value fir::FirOpBuilder::createBox(mlir::Location loc,
bool isPolymorphic, bool isPolymorphic,
bool isAssumedType) { bool isAssumedType) {
mlir::Value itemAddr = fir::getBase(exv); mlir::Value itemAddr = fir::getBase(exv);
if (itemAddr.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(itemAddr.getType()))
return itemAddr; return itemAddr;
auto elementType = fir::dyn_cast_ptrEleTy(itemAddr.getType()); auto elementType = fir::dyn_cast_ptrEleTy(itemAddr.getType());
if (!elementType) { if (!elementType) {
@ -592,7 +593,7 @@ mlir::Value fir::FirOpBuilder::createBox(mlir::Location loc,
mlir::Type boxTy; mlir::Type boxTy;
mlir::Value tdesc; mlir::Value tdesc;
// Avoid to wrap a box/class with box/class. // Avoid to wrap a box/class with box/class.
if (elementType.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(elementType)) {
boxTy = elementType; boxTy = elementType;
} else { } else {
boxTy = fir::BoxType::get(elementType); boxTy = fir::BoxType::get(elementType);
@ -709,7 +710,7 @@ mlir::Value fir::FirOpBuilder::genAbsentOp(mlir::Location loc,
return create<fir::AbsentOp>(loc, argTy); return create<fir::AbsentOp>(loc, argTy);
auto boxProc = auto boxProc =
create<fir::AbsentOp>(loc, argTy.cast<mlir::TupleType>().getType(0)); create<fir::AbsentOp>(loc, mlir::cast<mlir::TupleType>(argTy).getType(0));
mlir::Value charLen = create<fir::UndefOp>(loc, getCharacterLengthType()); mlir::Value charLen = create<fir::UndefOp>(loc, getCharacterLengthType());
return fir::factory::createCharacterProcedureTuple(*this, loc, argTy, boxProc, return fir::factory::createCharacterProcedureTuple(*this, loc, argTy, boxProc,
charLen); charLen);
@ -958,14 +959,14 @@ static llvm::SmallVector<mlir::Value> getFromBox(mlir::Location loc,
fir::FirOpBuilder &builder, fir::FirOpBuilder &builder,
mlir::Type valTy, mlir::Type valTy,
mlir::Value boxVal) { mlir::Value boxVal) {
if (auto boxTy = valTy.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(valTy)) {
auto eleTy = fir::unwrapAllRefAndSeqType(boxTy.getEleTy()); auto eleTy = fir::unwrapAllRefAndSeqType(boxTy.getEleTy());
if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) { if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy)) {
if (recTy.getNumLenParams() > 0) { if (recTy.getNumLenParams() > 0) {
// Walk each type parameter in the record and get the value. // Walk each type parameter in the record and get the value.
TODO(loc, "generate code to get LEN type parameters"); TODO(loc, "generate code to get LEN type parameters");
} }
} else if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { } else if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
if (charTy.hasDynamicLen()) { if (charTy.hasDynamicLen()) {
auto idxTy = builder.getIndexType(); auto idxTy = builder.getIndexType();
auto eleSz = builder.create<fir::BoxEleSizeOp>(loc, idxTy, boxVal); auto eleSz = builder.create<fir::BoxEleSizeOp>(loc, idxTy, boxVal);
@ -1012,7 +1013,7 @@ llvm::SmallVector<mlir::Value>
fir::factory::getTypeParams(mlir::Location loc, fir::FirOpBuilder &builder, fir::factory::getTypeParams(mlir::Location loc, fir::FirOpBuilder &builder,
fir::ArrayLoadOp load) { fir::ArrayLoadOp load) {
mlir::Type memTy = load.getMemref().getType(); mlir::Type memTy = load.getMemref().getType();
if (auto boxTy = memTy.dyn_cast<fir::BaseBoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(memTy))
return getFromBox(loc, builder, boxTy, load.getMemref()); return getFromBox(loc, builder, boxTy, load.getMemref());
return load.getTypeparams(); return load.getTypeparams();
} }
@ -1039,7 +1040,7 @@ std::string fir::factory::uniqueCGIdent(llvm::StringRef prefix,
mlir::Value fir::factory::locationToFilename(fir::FirOpBuilder &builder, mlir::Value fir::factory::locationToFilename(fir::FirOpBuilder &builder,
mlir::Location loc) { mlir::Location loc) {
if (auto flc = loc.dyn_cast<mlir::FileLineColLoc>()) { if (auto flc = mlir::dyn_cast<mlir::FileLineColLoc>(loc)) {
// must be encoded as asciiz, C string // must be encoded as asciiz, C string
auto fn = flc.getFilename().str() + '\0'; auto fn = flc.getFilename().str() + '\0';
return fir::getBase(createStringLiteral(builder, loc, fn)); return fir::getBase(createStringLiteral(builder, loc, fn));
@ -1050,7 +1051,7 @@ mlir::Value fir::factory::locationToFilename(fir::FirOpBuilder &builder,
mlir::Value fir::factory::locationToLineNo(fir::FirOpBuilder &builder, mlir::Value fir::factory::locationToLineNo(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Location loc,
mlir::Type type) { mlir::Type type) {
if (auto flc = loc.dyn_cast<mlir::FileLineColLoc>()) if (auto flc = mlir::dyn_cast<mlir::FileLineColLoc>(loc))
return builder.createIntegerConstant(loc, type, flc.getLine()); return builder.createIntegerConstant(loc, type, flc.getLine());
return builder.createIntegerConstant(loc, type, 0); return builder.createIntegerConstant(loc, type, 0);
} }
@ -1108,10 +1109,10 @@ fir::ExtendedValue fir::factory::componentToExtendedValue(
auto fieldTy = component.getType(); auto fieldTy = component.getType();
if (auto ty = fir::dyn_cast_ptrEleTy(fieldTy)) if (auto ty = fir::dyn_cast_ptrEleTy(fieldTy))
fieldTy = ty; fieldTy = ty;
if (fieldTy.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(fieldTy)) {
llvm::SmallVector<mlir::Value> nonDeferredTypeParams; llvm::SmallVector<mlir::Value> nonDeferredTypeParams;
auto eleTy = fir::unwrapSequenceType(fir::dyn_cast_ptrOrBoxEleTy(fieldTy)); auto eleTy = fir::unwrapSequenceType(fir::dyn_cast_ptrOrBoxEleTy(fieldTy));
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
auto lenTy = builder.getCharacterLengthType(); auto lenTy = builder.getCharacterLengthType();
if (charTy.hasConstantLen()) if (charTy.hasConstantLen())
nonDeferredTypeParams.emplace_back( nonDeferredTypeParams.emplace_back(
@ -1120,7 +1121,7 @@ fir::ExtendedValue fir::factory::componentToExtendedValue(
// on a PDT length parameter. There is no way to make a difference with // on a PDT length parameter. There is no way to make a difference with
// deferred length here yet. // deferred length here yet.
} }
if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy))
if (recTy.getNumLenParams() > 0) if (recTy.getNumLenParams() > 0)
TODO(loc, "allocatable and pointer components non deferred length " TODO(loc, "allocatable and pointer components non deferred length "
"parameters"); "parameters");
@ -1129,7 +1130,7 @@ fir::ExtendedValue fir::factory::componentToExtendedValue(
/*mutableProperties=*/{}); /*mutableProperties=*/{});
} }
llvm::SmallVector<mlir::Value> extents; llvm::SmallVector<mlir::Value> extents;
if (auto seqTy = fieldTy.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(fieldTy)) {
fieldTy = seqTy.getEleTy(); fieldTy = seqTy.getEleTy();
auto idxTy = builder.getIndexType(); auto idxTy = builder.getIndexType();
for (auto extent : seqTy.getShape()) { for (auto extent : seqTy.getShape()) {
@ -1138,7 +1139,7 @@ fir::ExtendedValue fir::factory::componentToExtendedValue(
extents.emplace_back(builder.createIntegerConstant(loc, idxTy, extent)); extents.emplace_back(builder.createIntegerConstant(loc, idxTy, extent));
} }
} }
if (auto charTy = fieldTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(fieldTy)) {
auto cstLen = charTy.getLen(); auto cstLen = charTy.getLen();
if (cstLen == fir::CharacterType::unknownLen()) if (cstLen == fir::CharacterType::unknownLen())
TODO(loc, "get character component length from length type parameters"); TODO(loc, "get character component length from length type parameters");
@ -1148,7 +1149,7 @@ fir::ExtendedValue fir::factory::componentToExtendedValue(
return fir::CharArrayBoxValue{component, len, extents}; return fir::CharArrayBoxValue{component, len, extents};
return fir::CharBoxValue{component, len}; return fir::CharBoxValue{component, len};
} }
if (auto recordTy = fieldTy.dyn_cast<fir::RecordType>()) if (auto recordTy = mlir::dyn_cast<fir::RecordType>(fieldTy))
if (recordTy.getNumLenParams() != 0) if (recordTy.getNumLenParams() != 0)
TODO(loc, TODO(loc,
"lower component ref that is a derived type with length parameter"); "lower component ref that is a derived type with length parameter");
@ -1211,14 +1212,14 @@ void fir::factory::genScalarAssignment(fir::FirOpBuilder &builder,
assert(lhs.rank() == 0 && rhs.rank() == 0 && "must be scalars"); assert(lhs.rank() == 0 && rhs.rank() == 0 && "must be scalars");
auto type = fir::unwrapSequenceType( auto type = fir::unwrapSequenceType(
fir::unwrapPassByRefType(fir::getBase(lhs).getType())); fir::unwrapPassByRefType(fir::getBase(lhs).getType()));
if (type.isa<fir::CharacterType>()) { if (mlir::isa<fir::CharacterType>(type)) {
const fir::CharBoxValue *toChar = lhs.getCharBox(); const fir::CharBoxValue *toChar = lhs.getCharBox();
const fir::CharBoxValue *fromChar = rhs.getCharBox(); const fir::CharBoxValue *fromChar = rhs.getCharBox();
assert(toChar && fromChar); assert(toChar && fromChar);
fir::factory::CharacterExprHelper helper{builder, loc}; fir::factory::CharacterExprHelper helper{builder, loc};
helper.createAssign(fir::ExtendedValue{*toChar}, helper.createAssign(fir::ExtendedValue{*toChar},
fir::ExtendedValue{*fromChar}); fir::ExtendedValue{*fromChar});
} else if (type.isa<fir::RecordType>()) { } else if (mlir::isa<fir::RecordType>(type)) {
fir::factory::genRecordAssignment(builder, loc, lhs, rhs, needFinalization, fir::factory::genRecordAssignment(builder, loc, lhs, rhs, needFinalization,
isTemporaryLHS); isTemporaryLHS);
} else { } else {
@ -1239,10 +1240,10 @@ static void genComponentByComponentAssignment(fir::FirOpBuilder &builder,
const fir::ExtendedValue &rhs, const fir::ExtendedValue &rhs,
bool isTemporaryLHS) { bool isTemporaryLHS) {
auto lbaseType = fir::unwrapPassByRefType(fir::getBase(lhs).getType()); auto lbaseType = fir::unwrapPassByRefType(fir::getBase(lhs).getType());
auto lhsType = lbaseType.dyn_cast<fir::RecordType>(); auto lhsType = mlir::dyn_cast<fir::RecordType>(lbaseType);
assert(lhsType && "lhs must be a scalar record type"); assert(lhsType && "lhs must be a scalar record type");
auto rbaseType = fir::unwrapPassByRefType(fir::getBase(rhs).getType()); auto rbaseType = fir::unwrapPassByRefType(fir::getBase(rhs).getType());
auto rhsType = rbaseType.dyn_cast<fir::RecordType>(); auto rhsType = mlir::dyn_cast<fir::RecordType>(rbaseType);
assert(rhsType && "rhs must be a scalar record type"); assert(rhsType && "rhs must be a scalar record type");
auto fieldIndexType = fir::FieldType::get(lhsType.getContext()); auto fieldIndexType = fir::FieldType::get(lhsType.getContext());
for (auto [lhsPair, rhsPair] : for (auto [lhsPair, rhsPair] :
@ -1261,7 +1262,7 @@ static void genComponentByComponentAssignment(fir::FirOpBuilder &builder,
mlir::Value toCoor = builder.create<fir::CoordinateOp>( mlir::Value toCoor = builder.create<fir::CoordinateOp>(
loc, fieldRefType, fir::getBase(lhs), field); loc, fieldRefType, fir::getBase(lhs), field);
std::optional<fir::DoLoopOp> outerLoop; std::optional<fir::DoLoopOp> outerLoop;
if (auto sequenceType = lFieldTy.dyn_cast<fir::SequenceType>()) { if (auto sequenceType = mlir::dyn_cast<fir::SequenceType>(lFieldTy)) {
// Create loops to assign array components elements by elements. // Create loops to assign array components elements by elements.
// Note that, since these are components, they either do not overlap, // Note that, since these are components, they either do not overlap,
// or are the same and exactly overlap. They also have compile time // or are the same and exactly overlap. They also have compile time
@ -1288,10 +1289,9 @@ static void genComponentByComponentAssignment(fir::FirOpBuilder &builder,
fromCoor, indices); fromCoor, indices);
} }
if (auto fieldEleTy = fir::unwrapSequenceType(lFieldTy); if (auto fieldEleTy = fir::unwrapSequenceType(lFieldTy);
fieldEleTy.isa<fir::BaseBoxType>()) { mlir::isa<fir::BaseBoxType>(fieldEleTy)) {
assert(fieldEleTy.cast<fir::BaseBoxType>() assert(mlir::isa<fir::PointerType>(
.getEleTy() mlir::cast<fir::BaseBoxType>(fieldEleTy).getEleTy()) &&
.isa<fir::PointerType>() &&
"allocatable members require deep copy"); "allocatable members require deep copy");
auto fromPointerValue = builder.create<fir::LoadOp>(loc, fromCoor); auto fromPointerValue = builder.create<fir::LoadOp>(loc, fromCoor);
auto castTo = builder.createConvert(loc, fieldEleTy, fromPointerValue); auto castTo = builder.createConvert(loc, fieldEleTy, fromPointerValue);
@ -1320,11 +1320,11 @@ static bool recordTypeCanBeMemCopied(fir::RecordType recordType) {
for (auto [_, fieldType] : recordType.getTypeList()) { for (auto [_, fieldType] : recordType.getTypeList()) {
// Derived type component may have user assignment (so far, we cannot tell // Derived type component may have user assignment (so far, we cannot tell
// in FIR, so assume it is always the case, TODO: get the actual info). // in FIR, so assume it is always the case, TODO: get the actual info).
if (fir::unwrapSequenceType(fieldType).isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(fir::unwrapSequenceType(fieldType)))
return false; return false;
// Allocatable components need deep copy. // Allocatable components need deep copy.
if (auto boxType = fieldType.dyn_cast<fir::BaseBoxType>()) if (auto boxType = mlir::dyn_cast<fir::BaseBoxType>(fieldType))
if (boxType.getEleTy().isa<fir::HeapType>()) if (mlir::isa<fir::HeapType>(boxType.getEleTy()))
return false; return false;
} }
// Constant size components without user defined assignment and pointers can // Constant size components without user defined assignment and pointers can
@ -1353,9 +1353,10 @@ void fir::factory::genRecordAssignment(fir::FirOpBuilder &builder,
// Box operands may be polymorphic, it is not entirely clear from 10.2.1.3 // Box operands may be polymorphic, it is not entirely clear from 10.2.1.3
// if the assignment is performed on the dynamic of declared type. Use the // if the assignment is performed on the dynamic of declared type. Use the
// runtime assuming it is performed on the dynamic type. // runtime assuming it is performed on the dynamic type.
bool hasBoxOperands = fir::getBase(lhs).getType().isa<fir::BaseBoxType>() || bool hasBoxOperands =
fir::getBase(rhs).getType().isa<fir::BaseBoxType>(); mlir::isa<fir::BaseBoxType>(fir::getBase(lhs).getType()) ||
auto recTy = baseTy.dyn_cast<fir::RecordType>(); mlir::isa<fir::BaseBoxType>(fir::getBase(rhs).getType());
auto recTy = mlir::dyn_cast<fir::RecordType>(baseTy);
assert(recTy && "must be a record type"); assert(recTy && "must be a record type");
if ((needFinalization && mayHaveFinalizer(recTy, builder)) || if ((needFinalization && mayHaveFinalizer(recTy, builder)) ||
hasBoxOperands || !recordTypeCanBeMemCopied(recTy)) { hasBoxOperands || !recordTypeCanBeMemCopied(recTy)) {
@ -1401,7 +1402,7 @@ mlir::Value fir::factory::genLenOfCharacter(
llvm::ArrayRef<mlir::Value> path, llvm::ArrayRef<mlir::Value> substring) { llvm::ArrayRef<mlir::Value> path, llvm::ArrayRef<mlir::Value> substring) {
llvm::SmallVector<mlir::Value> typeParams(arrLoad.getTypeparams()); llvm::SmallVector<mlir::Value> typeParams(arrLoad.getTypeparams());
return genLenOfCharacter(builder, loc, return genLenOfCharacter(builder, loc,
arrLoad.getType().cast<fir::SequenceType>(), mlir::cast<fir::SequenceType>(arrLoad.getType()),
arrLoad.getMemref(), typeParams, path, substring); arrLoad.getMemref(), typeParams, path, substring);
} }
@ -1429,7 +1430,7 @@ mlir::Value fir::factory::genLenOfCharacter(
lower = builder.createConvert(loc, idxTy, substring.front()); lower = builder.createConvert(loc, idxTy, substring.front());
auto eleTy = fir::applyPathToType(seqTy, path); auto eleTy = fir::applyPathToType(seqTy, path);
if (!fir::hasDynamicSize(eleTy)) { if (!fir::hasDynamicSize(eleTy)) {
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
// Use LEN from the type. // Use LEN from the type.
return builder.createIntegerConstant(loc, idxTy, charTy.getLen()); return builder.createIntegerConstant(loc, idxTy, charTy.getLen());
} }
@ -1438,9 +1439,9 @@ mlir::Value fir::factory::genLenOfCharacter(
"application of path did not result in a !fir.char"); "application of path did not result in a !fir.char");
} }
if (fir::isa_box_type(memref.getType())) { if (fir::isa_box_type(memref.getType())) {
if (memref.getType().isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(memref.getType()))
return builder.create<fir::BoxCharLenOp>(loc, idxTy, memref); return builder.create<fir::BoxCharLenOp>(loc, idxTy, memref);
if (memref.getType().isa<fir::BoxType>()) if (mlir::isa<fir::BoxType>(memref.getType()))
return CharacterExprHelper(builder, loc).readLengthFromBox(memref); return CharacterExprHelper(builder, loc).readLengthFromBox(memref);
fir::emitFatalError(loc, "memref has wrong type"); fir::emitFatalError(loc, "memref has wrong type");
} }
@ -1457,7 +1458,7 @@ mlir::Value fir::factory::genLenOfCharacter(
mlir::Value fir::factory::createZeroValue(fir::FirOpBuilder &builder, mlir::Value fir::factory::createZeroValue(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Type type) { mlir::Location loc, mlir::Type type) {
mlir::Type i1 = builder.getIntegerType(1); mlir::Type i1 = builder.getIntegerType(1);
if (type.isa<fir::LogicalType>() || type == i1) if (mlir::isa<fir::LogicalType>(type) || type == i1)
return builder.createConvert(loc, type, builder.createBool(loc, false)); return builder.createConvert(loc, type, builder.createBool(loc, false));
if (fir::isa_integer(type)) if (fir::isa_integer(type))
return builder.createIntegerConstant(loc, type, 0); return builder.createIntegerConstant(loc, type, 0);
@ -1507,7 +1508,7 @@ mlir::Value fir::factory::genMaxWithZero(fir::FirOpBuilder &builder,
mlir::Value zero = builder.createIntegerConstant(loc, value.getType(), 0); mlir::Value zero = builder.createIntegerConstant(loc, value.getType(), 0);
if (mlir::Operation *definingOp = value.getDefiningOp()) if (mlir::Operation *definingOp = value.getDefiningOp())
if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp)) if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp))
if (auto intAttr = cst.getValue().dyn_cast<mlir::IntegerAttr>()) if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(cst.getValue()))
return intAttr.getInt() > 0 ? value : zero; return intAttr.getInt() > 0 ? value : zero;
mlir::Value valueIsGreater = builder.create<mlir::arith::CmpIOp>( mlir::Value valueIsGreater = builder.create<mlir::arith::CmpIOp>(
loc, mlir::arith::CmpIPredicate::sgt, value, zero); loc, mlir::arith::CmpIPredicate::sgt, value, zero);
@ -1519,8 +1520,8 @@ mlir::Value fir::factory::genCPtrOrCFunptrAddr(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Location loc,
mlir::Value cPtr, mlir::Value cPtr,
mlir::Type ty) { mlir::Type ty) {
assert(ty.isa<fir::RecordType>()); assert(mlir::isa<fir::RecordType>(ty));
auto recTy = ty.dyn_cast<fir::RecordType>(); auto recTy = mlir::dyn_cast<fir::RecordType>(ty);
assert(recTy.getTypeList().size() == 1); assert(recTy.getTypeList().size() == 1);
auto fieldName = recTy.getTypeList()[0].first; auto fieldName = recTy.getTypeList()[0].first;
mlir::Type fieldTy = recTy.getTypeList()[0].second; mlir::Type fieldTy = recTy.getTypeList()[0].second;
@ -1582,7 +1583,7 @@ mlir::Value fir::factory::genCPtrOrCFunptrValue(fir::FirOpBuilder &builder,
mlir::Value fir::factory::createNullBoxProc(fir::FirOpBuilder &builder, mlir::Value fir::factory::createNullBoxProc(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Location loc,
mlir::Type boxType) { mlir::Type boxType) {
auto boxTy{boxType.dyn_cast<fir::BoxProcType>()}; auto boxTy{mlir::dyn_cast<fir::BoxProcType>(boxType)};
if (!boxTy) if (!boxTy)
fir::emitFatalError(loc, "Procedure pointer must be of BoxProcType"); fir::emitFatalError(loc, "Procedure pointer must be of BoxProcType");
auto boxEleTy{fir::unwrapRefType(boxTy.getEleTy())}; auto boxEleTy{fir::unwrapRefType(boxTy.getEleTy())};

View File

@ -38,10 +38,10 @@ hlfir::getExplicitExtentsFromShape(mlir::Value shape,
} else if (mlir::dyn_cast_or_null<fir::ShiftOp>(shapeOp)) { } else if (mlir::dyn_cast_or_null<fir::ShiftOp>(shapeOp)) {
return {}; return {};
} else if (auto s = mlir::dyn_cast_or_null<hlfir::ShapeOfOp>(shapeOp)) { } else if (auto s = mlir::dyn_cast_or_null<hlfir::ShapeOfOp>(shapeOp)) {
hlfir::ExprType expr = s.getExpr().getType().cast<hlfir::ExprType>(); hlfir::ExprType expr = mlir::cast<hlfir::ExprType>(s.getExpr().getType());
llvm::ArrayRef<int64_t> exprShape = expr.getShape(); llvm::ArrayRef<int64_t> exprShape = expr.getShape();
mlir::Type indexTy = builder.getIndexType(); mlir::Type indexTy = builder.getIndexType();
fir::ShapeType shapeTy = shape.getType().cast<fir::ShapeType>(); fir::ShapeType shapeTy = mlir::cast<fir::ShapeType>(shape.getType());
result.reserve(shapeTy.getRank()); result.reserve(shapeTy.getRank());
for (unsigned i = 0; i < shapeTy.getRank(); ++i) { for (unsigned i = 0; i < shapeTy.getRank(); ++i) {
int64_t extent = exprShape[i]; int64_t extent = exprShape[i];
@ -99,7 +99,7 @@ genLboundsAndExtentsFromBox(mlir::Location loc, fir::FirOpBuilder &builder,
hlfir::Entity boxEntity, hlfir::Entity boxEntity,
llvm::SmallVectorImpl<mlir::Value> &lbounds, llvm::SmallVectorImpl<mlir::Value> &lbounds,
llvm::SmallVectorImpl<mlir::Value> *extents) { llvm::SmallVectorImpl<mlir::Value> *extents) {
assert(boxEntity.getType().isa<fir::BaseBoxType>() && "must be a box"); assert(mlir::isa<fir::BaseBoxType>(boxEntity.getType()) && "must be a box");
mlir::Type idxTy = builder.getIndexType(); mlir::Type idxTy = builder.getIndexType();
const int rank = boxEntity.getRank(); const int rank = boxEntity.getRank();
for (int i = 0; i < rank; ++i) { for (int i = 0; i < rank; ++i) {
@ -154,7 +154,7 @@ static mlir::Value genCharacterVariableLength(mlir::Location loc,
hlfir::Entity var) { hlfir::Entity var) {
if (mlir::Value len = tryGettingNonDeferredCharLen(var)) if (mlir::Value len = tryGettingNonDeferredCharLen(var))
return len; return len;
auto charType = var.getFortranElementType().cast<fir::CharacterType>(); auto charType = mlir::cast<fir::CharacterType>(var.getFortranElementType());
if (charType.hasConstantLen()) if (charType.hasConstantLen())
return builder.createIntegerConstant(loc, builder.getIndexType(), return builder.createIntegerConstant(loc, builder.getIndexType(),
charType.getLen()); charType.getLen());
@ -172,7 +172,7 @@ static fir::CharBoxValue genUnboxChar(mlir::Location loc,
if (auto emboxChar = boxChar.getDefiningOp<fir::EmboxCharOp>()) if (auto emboxChar = boxChar.getDefiningOp<fir::EmboxCharOp>())
return {emboxChar.getMemref(), emboxChar.getLen()}; return {emboxChar.getMemref(), emboxChar.getLen()};
mlir::Type refType = fir::ReferenceType::get( mlir::Type refType = fir::ReferenceType::get(
boxChar.getType().cast<fir::BoxCharType>().getEleTy()); mlir::cast<fir::BoxCharType>(boxChar.getType()).getEleTy());
auto unboxed = builder.create<fir::UnboxCharOp>( auto unboxed = builder.create<fir::UnboxCharOp>(
loc, refType, builder.getIndexType(), boxChar); loc, refType, builder.getIndexType(), boxChar);
mlir::Value addr = unboxed.getResult(0); mlir::Value addr = unboxed.getResult(0);
@ -252,8 +252,8 @@ hlfir::genAssociateExpr(mlir::Location loc, fir::FirOpBuilder &builder,
// and the other static). // and the other static).
mlir::Type varEleTy = getFortranElementType(variableType); mlir::Type varEleTy = getFortranElementType(variableType);
mlir::Type valueEleTy = getFortranElementType(value.getType()); mlir::Type valueEleTy = getFortranElementType(value.getType());
if (varEleTy != valueEleTy && !(valueEleTy.isa<fir::CharacterType>() && if (varEleTy != valueEleTy && !(mlir::isa<fir::CharacterType>(valueEleTy) &&
varEleTy.isa<fir::CharacterType>())) { mlir::isa<fir::CharacterType>(varEleTy))) {
assert(value.isScalar() && fir::isa_trivial(value.getType())); assert(value.isScalar() && fir::isa_trivial(value.getType()));
source = builder.createConvert(loc, fir::unwrapPassByRefType(variableType), source = builder.createConvert(loc, fir::unwrapPassByRefType(variableType),
value); value);
@ -278,9 +278,9 @@ mlir::Value hlfir::genVariableRawAddress(mlir::Location loc,
if (var.isMutableBox()) if (var.isMutableBox())
baseAddr = builder.create<fir::LoadOp>(loc, baseAddr); baseAddr = builder.create<fir::LoadOp>(loc, baseAddr);
// Get raw address. // Get raw address.
if (var.getType().isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(var.getType()))
baseAddr = genUnboxChar(loc, builder, var.getBase()).getAddr(); baseAddr = genUnboxChar(loc, builder, var.getBase()).getAddr();
if (baseAddr.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(baseAddr.getType()))
baseAddr = builder.create<fir::BoxAddrOp>(loc, baseAddr); baseAddr = builder.create<fir::BoxAddrOp>(loc, baseAddr);
return baseAddr; return baseAddr;
} }
@ -289,13 +289,13 @@ mlir::Value hlfir::genVariableBoxChar(mlir::Location loc,
fir::FirOpBuilder &builder, fir::FirOpBuilder &builder,
hlfir::Entity var) { hlfir::Entity var) {
assert(var.isVariable() && "only address of variables can be taken"); assert(var.isVariable() && "only address of variables can be taken");
if (var.getType().isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(var.getType()))
return var; return var;
mlir::Value addr = genVariableRawAddress(loc, builder, var); mlir::Value addr = genVariableRawAddress(loc, builder, var);
llvm::SmallVector<mlir::Value> lengths; llvm::SmallVector<mlir::Value> lengths;
genLengthParameters(loc, builder, var, lengths); genLengthParameters(loc, builder, var, lengths);
assert(lengths.size() == 1); assert(lengths.size() == 1);
auto charType = var.getFortranElementType().cast<fir::CharacterType>(); auto charType = mlir::cast<fir::CharacterType>(var.getFortranElementType());
auto boxCharType = auto boxCharType =
fir::BoxCharType::get(builder.getContext(), charType.getFKind()); fir::BoxCharType::get(builder.getContext(), charType.getFKind());
auto scalarAddr = auto scalarAddr =
@ -309,7 +309,7 @@ hlfir::Entity hlfir::genVariableBox(mlir::Location loc,
hlfir::Entity var) { hlfir::Entity var) {
assert(var.isVariable() && "must be a variable"); assert(var.isVariable() && "must be a variable");
var = hlfir::derefPointersAndAllocatables(loc, builder, var); var = hlfir::derefPointersAndAllocatables(loc, builder, var);
if (var.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(var.getType()))
return var; return var;
// Note: if the var is not a fir.box/fir.class at that point, it has default // Note: if the var is not a fir.box/fir.class at that point, it has default
// lower bounds and is not polymorphic. // lower bounds and is not polymorphic.
@ -317,11 +317,11 @@ hlfir::Entity hlfir::genVariableBox(mlir::Location loc,
var.isArray() ? hlfir::genShape(loc, builder, var) : mlir::Value{}; var.isArray() ? hlfir::genShape(loc, builder, var) : mlir::Value{};
llvm::SmallVector<mlir::Value> typeParams; llvm::SmallVector<mlir::Value> typeParams;
auto maybeCharType = auto maybeCharType =
var.getFortranElementType().dyn_cast<fir::CharacterType>(); mlir::dyn_cast<fir::CharacterType>(var.getFortranElementType());
if (!maybeCharType || maybeCharType.hasDynamicLen()) if (!maybeCharType || maybeCharType.hasDynamicLen())
hlfir::genLengthParameters(loc, builder, var, typeParams); hlfir::genLengthParameters(loc, builder, var, typeParams);
mlir::Value addr = var.getBase(); mlir::Value addr = var.getBase();
if (var.getType().isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(var.getType()))
addr = genVariableRawAddress(loc, builder, var); addr = genVariableRawAddress(loc, builder, var);
mlir::Type boxType = fir::BoxType::get(var.getElementOrSequenceType()); mlir::Type boxType = fir::BoxType::get(var.getElementOrSequenceType());
auto embox = auto embox =
@ -348,7 +348,7 @@ hlfir::Entity hlfir::getElementAt(mlir::Location loc,
return entity; return entity;
llvm::SmallVector<mlir::Value> lenParams; llvm::SmallVector<mlir::Value> lenParams;
genLengthParameters(loc, builder, entity, lenParams); genLengthParameters(loc, builder, entity, lenParams);
if (entity.getType().isa<hlfir::ExprType>()) if (mlir::isa<hlfir::ExprType>(entity.getType()))
return hlfir::Entity{builder.create<hlfir::ApplyOp>( return hlfir::Entity{builder.create<hlfir::ApplyOp>(
loc, entity, oneBasedIndices, lenParams)}; loc, entity, oneBasedIndices, lenParams)};
// Build hlfir.designate. The lower bounds may need to be added to // Build hlfir.designate. The lower bounds may need to be added to
@ -394,7 +394,7 @@ static mlir::Value genUBound(mlir::Location loc, fir::FirOpBuilder &builder,
llvm::SmallVector<std::pair<mlir::Value, mlir::Value>> llvm::SmallVector<std::pair<mlir::Value, mlir::Value>>
hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder, hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder,
Entity entity) { Entity entity) {
if (entity.getType().isa<hlfir::ExprType>()) if (mlir::isa<hlfir::ExprType>(entity.getType()))
TODO(loc, "bounds of expressions in hlfir"); TODO(loc, "bounds of expressions in hlfir");
auto [exv, cleanup] = translateToExtendedValue(loc, builder, entity); auto [exv, cleanup] = translateToExtendedValue(loc, builder, entity);
assert(!cleanup && "translation of entity should not yield cleanup"); assert(!cleanup && "translation of entity should not yield cleanup");
@ -415,8 +415,8 @@ hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder,
llvm::SmallVector<std::pair<mlir::Value, mlir::Value>> llvm::SmallVector<std::pair<mlir::Value, mlir::Value>>
hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder, hlfir::genBounds(mlir::Location loc, fir::FirOpBuilder &builder,
mlir::Value shape) { mlir::Value shape) {
assert((shape.getType().isa<fir::ShapeShiftType>() || assert((mlir::isa<fir::ShapeShiftType>(shape.getType()) ||
shape.getType().isa<fir::ShapeType>()) && mlir::isa<fir::ShapeType>(shape.getType())) &&
"shape must contain extents"); "shape must contain extents");
auto extents = hlfir::getExplicitExtentsFromShape(shape, builder); auto extents = hlfir::getExplicitExtentsFromShape(shape, builder);
auto lowers = getExplicitLboundsFromShape(shape); auto lowers = getExplicitLboundsFromShape(shape);
@ -474,7 +474,7 @@ static mlir::Value computeVariableExtent(mlir::Location loc,
if (typeExtent != fir::SequenceType::getUnknownExtent()) if (typeExtent != fir::SequenceType::getUnknownExtent())
return builder.createIntegerConstant(loc, idxTy, typeExtent); return builder.createIntegerConstant(loc, idxTy, typeExtent);
} }
assert(variable.getType().isa<fir::BaseBoxType>() && assert(mlir::isa<fir::BaseBoxType>(variable.getType()) &&
"array variable with dynamic extent must be boxed"); "array variable with dynamic extent must be boxed");
mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim); mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim);
auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy,
@ -496,9 +496,8 @@ llvm::SmallVector<mlir::Value> getVariableExtents(mlir::Location loc,
variable = hlfir::derefPointersAndAllocatables(loc, builder, variable); variable = hlfir::derefPointersAndAllocatables(loc, builder, variable);
// Use the type shape information, and/or the fir.box/fir.class shape // Use the type shape information, and/or the fir.box/fir.class shape
// information if any extents are not static. // information if any extents are not static.
fir::SequenceType seqTy = fir::SequenceType seqTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(variable.getType()) hlfir::getFortranElementOrSequenceType(variable.getType()));
.cast<fir::SequenceType>();
unsigned rank = seqTy.getShape().size(); unsigned rank = seqTy.getShape().size();
for (unsigned dim = 0; dim < rank; ++dim) for (unsigned dim = 0; dim < rank; ++dim)
extents.push_back( extents.push_back(
@ -507,7 +506,7 @@ llvm::SmallVector<mlir::Value> getVariableExtents(mlir::Location loc,
} }
static mlir::Value tryRetrievingShapeOrShift(hlfir::Entity entity) { static mlir::Value tryRetrievingShapeOrShift(hlfir::Entity entity) {
if (entity.getType().isa<hlfir::ExprType>()) { if (mlir::isa<hlfir::ExprType>(entity.getType())) {
if (auto elemental = entity.getDefiningOp<hlfir::ElementalOp>()) if (auto elemental = entity.getDefiningOp<hlfir::ElementalOp>())
return elemental.getShape(); return elemental.getShape();
return mlir::Value{}; return mlir::Value{};
@ -523,13 +522,13 @@ mlir::Value hlfir::genShape(mlir::Location loc, fir::FirOpBuilder &builder,
entity = followShapeInducingSource(entity); entity = followShapeInducingSource(entity);
assert(entity && "what?"); assert(entity && "what?");
if (auto shape = tryRetrievingShapeOrShift(entity)) { if (auto shape = tryRetrievingShapeOrShift(entity)) {
if (shape.getType().isa<fir::ShapeType>()) if (mlir::isa<fir::ShapeType>(shape.getType()))
return shape; return shape;
if (shape.getType().isa<fir::ShapeShiftType>()) if (mlir::isa<fir::ShapeShiftType>(shape.getType()))
if (auto s = shape.getDefiningOp<fir::ShapeShiftOp>()) if (auto s = shape.getDefiningOp<fir::ShapeShiftOp>())
return builder.create<fir::ShapeOp>(loc, s.getExtents()); return builder.create<fir::ShapeOp>(loc, s.getExtents());
} }
if (entity.getType().isa<hlfir::ExprType>()) if (mlir::isa<hlfir::ExprType>(entity.getType()))
return builder.create<hlfir::ShapeOfOp>(loc, entity.getBase()); return builder.create<hlfir::ShapeOfOp>(loc, entity.getBase());
// There is no shape lying around for this entity. Retrieve the extents and // There is no shape lying around for this entity. Retrieve the extents and
// build a new fir.shape. // build a new fir.shape.
@ -563,9 +562,8 @@ mlir::Value hlfir::genExtent(mlir::Location loc, fir::FirOpBuilder &builder,
entity = hlfir::derefPointersAndAllocatables(loc, builder, entity); entity = hlfir::derefPointersAndAllocatables(loc, builder, entity);
// Use the type shape information, and/or the fir.box/fir.class shape // Use the type shape information, and/or the fir.box/fir.class shape
// information if any extents are not static. // information if any extents are not static.
fir::SequenceType seqTy = fir::SequenceType seqTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(entity.getType()) hlfir::getFortranElementOrSequenceType(entity.getType()));
.cast<fir::SequenceType>();
return computeVariableExtent(loc, builder, entity, seqTy, dim); return computeVariableExtent(loc, builder, entity, seqTy, dim);
} }
TODO(loc, "get extent from HLFIR expr without producer holding the shape"); TODO(loc, "get extent from HLFIR expr without producer holding the shape");
@ -584,7 +582,7 @@ mlir::Value hlfir::genLBound(mlir::Location loc, fir::FirOpBuilder &builder,
} }
if (entity.isMutableBox()) if (entity.isMutableBox())
entity = hlfir::derefPointersAndAllocatables(loc, builder, entity); entity = hlfir::derefPointersAndAllocatables(loc, builder, entity);
assert(entity.getType().isa<fir::BaseBoxType>() && "must be a box"); assert(mlir::isa<fir::BaseBoxType>(entity.getType()) && "must be a box");
mlir::Type idxTy = builder.getIndexType(); mlir::Type idxTy = builder.getIndexType();
mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim); mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim);
auto dimInfo = auto dimInfo =
@ -597,7 +595,7 @@ void hlfir::genLengthParameters(mlir::Location loc, fir::FirOpBuilder &builder,
llvm::SmallVectorImpl<mlir::Value> &result) { llvm::SmallVectorImpl<mlir::Value> &result) {
if (!entity.hasLengthParameters()) if (!entity.hasLengthParameters())
return; return;
if (entity.getType().isa<hlfir::ExprType>()) { if (mlir::isa<hlfir::ExprType>(entity.getType())) {
mlir::Value expr = entity; mlir::Value expr = entity;
if (auto reassoc = expr.getDefiningOp<hlfir::NoReassocOp>()) if (auto reassoc = expr.getDefiningOp<hlfir::NoReassocOp>())
expr = reassoc.getVal(); expr = reassoc.getVal();
@ -654,8 +652,8 @@ static mlir::Value asEmboxShape(mlir::Location loc, fir::FirOpBuilder &builder,
// fir.shape_shift) since this information is already in the input fir.box, // fir.shape_shift) since this information is already in the input fir.box,
// it only accepts fir.shift because local lower bounds may not be reflected // it only accepts fir.shift because local lower bounds may not be reflected
// in the fir.box. // in the fir.box.
if (fir::getBase(exv).getType().isa<fir::BaseBoxType>() && if (mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType()) &&
!shape.getType().isa<fir::ShiftType>()) !mlir::isa<fir::ShiftType>(shape.getType()))
return builder.createShape(loc, exv); return builder.createShape(loc, exv);
return shape; return shape;
} }
@ -686,7 +684,7 @@ hlfir::Entity hlfir::derefPointersAndAllocatables(mlir::Location loc,
if (!entity.isPolymorphic() && !entity.hasLengthParameters()) if (!entity.isPolymorphic() && !entity.hasLengthParameters())
return hlfir::Entity{builder.create<fir::BoxAddrOp>(loc, boxLoad)}; return hlfir::Entity{builder.create<fir::BoxAddrOp>(loc, boxLoad)};
mlir::Type elementType = boxLoad.getFortranElementType(); mlir::Type elementType = boxLoad.getFortranElementType();
if (auto charType = elementType.dyn_cast<fir::CharacterType>()) { if (auto charType = mlir::dyn_cast<fir::CharacterType>(elementType)) {
mlir::Value base = builder.create<fir::BoxAddrOp>(loc, boxLoad); mlir::Value base = builder.create<fir::BoxAddrOp>(loc, boxLoad);
if (charType.hasConstantLen()) if (charType.hasConstantLen())
return hlfir::Entity{base}; return hlfir::Entity{base};
@ -716,7 +714,7 @@ mlir::Type hlfir::getVariableElementType(hlfir::Entity variable) {
mlir::Type eleTy = variable.getFortranElementType(); mlir::Type eleTy = variable.getFortranElementType();
if (variable.isPolymorphic()) if (variable.isPolymorphic())
return fir::ClassType::get(eleTy); return fir::ClassType::get(eleTy);
if (auto charType = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charType = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
if (charType.hasDynamicLen()) if (charType.hasDynamicLen())
return fir::BoxCharType::get(charType.getContext(), charType.getFKind()); return fir::BoxCharType::get(charType.getContext(), charType.getFKind());
} else if (fir::isRecordWithTypeParameters(eleTy)) { } else if (fir::isRecordWithTypeParameters(eleTy)) {
@ -737,7 +735,7 @@ mlir::Type hlfir::getEntityElementType(hlfir::Entity entity) {
static hlfir::ExprType getArrayExprType(mlir::Type elementType, static hlfir::ExprType getArrayExprType(mlir::Type elementType,
mlir::Value shape, bool isPolymorphic) { mlir::Value shape, bool isPolymorphic) {
unsigned rank = shape.getType().cast<fir::ShapeType>().getRank(); unsigned rank = mlir::cast<fir::ShapeType>(shape.getType()).getRank();
hlfir::ExprType::Shape typeShape(rank, hlfir::ExprType::getUnknownExtent()); hlfir::ExprType::Shape typeShape(rank, hlfir::ExprType::getUnknownExtent());
if (auto shapeOp = shape.getDefiningOp<fir::ShapeOp>()) if (auto shapeOp = shape.getDefiningOp<fir::ShapeOp>())
for (auto extent : llvm::enumerate(shapeOp.getExtents())) for (auto extent : llvm::enumerate(shapeOp.getExtents()))
@ -859,7 +857,7 @@ translateVariableToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
return fir::MutableBoxValue(base, getExplicitTypeParams(variable), return fir::MutableBoxValue(base, getExplicitTypeParams(variable),
fir::MutableProperties{}); fir::MutableProperties{});
if (base.getType().isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(base.getType())) {
if (!variable.isSimplyContiguous() || variable.isPolymorphic() || if (!variable.isSimplyContiguous() || variable.isPolymorphic() ||
variable.isDerivedWithLengthParameters() || variable.isOptional()) { variable.isDerivedWithLengthParameters() || variable.isOptional()) {
llvm::SmallVector<mlir::Value> nonDefaultLbounds = llvm::SmallVector<mlir::Value> nonDefaultLbounds =
@ -874,7 +872,7 @@ translateVariableToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
if (variable.isScalar()) { if (variable.isScalar()) {
if (variable.isCharacter()) { if (variable.isCharacter()) {
if (base.getType().isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(base.getType()))
return genUnboxChar(loc, builder, base); return genUnboxChar(loc, builder, base);
mlir::Value len = genCharacterVariableLength(loc, builder, variable); mlir::Value len = genCharacterVariableLength(loc, builder, variable);
return fir::CharBoxValue{base, len}; return fir::CharBoxValue{base, len};
@ -883,7 +881,7 @@ translateVariableToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
} }
llvm::SmallVector<mlir::Value> extents; llvm::SmallVector<mlir::Value> extents;
llvm::SmallVector<mlir::Value> nonDefaultLbounds; llvm::SmallVector<mlir::Value> nonDefaultLbounds;
if (variable.getType().isa<fir::BaseBoxType>() && if (mlir::isa<fir::BaseBoxType>(variable.getType()) &&
!variable.getIfVariableInterface()) { !variable.getIfVariableInterface()) {
// This special case avoids generating two sets of identical // This special case avoids generating two sets of identical
// fir.box_dim to get both the lower bounds and extents. // fir.box_dim to get both the lower bounds and extents.
@ -923,7 +921,7 @@ hlfir::translateToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
return {static_cast<mlir::Value>(entity), std::nullopt}; return {static_cast<mlir::Value>(entity), std::nullopt};
} }
if (entity.getType().isa<hlfir::ExprType>()) { if (mlir::isa<hlfir::ExprType>(entity.getType())) {
mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder); mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
hlfir::AssociateOp associate = hlfir::genAssociateExpr( hlfir::AssociateOp associate = hlfir::genAssociateExpr(
loc, builder, entity, entity.getType(), "", byRefAttr); loc, builder, entity, entity.getType(), "", byRefAttr);

View File

@ -786,7 +786,7 @@ mlir::Value genLibSplitComplexArgsCall(fir::FirOpBuilder &builder,
auto getSplitComplexArgsType = [&builder, &args]() -> mlir::FunctionType { auto getSplitComplexArgsType = [&builder, &args]() -> mlir::FunctionType {
mlir::Type ctype = args[0].getType(); mlir::Type ctype = args[0].getType();
auto fKind = ctype.cast<fir::ComplexType>().getFKind(); auto fKind = mlir::cast<fir::ComplexType>(ctype).getFKind();
mlir::Type ftype; mlir::Type ftype;
if (fKind == 2) if (fKind == 2)
@ -894,8 +894,8 @@ mlir::Value genComplexMathOp(fir::FirOpBuilder &builder, mlir::Location loc,
LLVM_DEBUG(llvm::dbgs() << "Generating '" << mathLibFuncName LLVM_DEBUG(llvm::dbgs() << "Generating '" << mathLibFuncName
<< "' operation with type "; << "' operation with type ";
mathLibFuncType.dump(); llvm::dbgs() << "\n"); mathLibFuncType.dump(); llvm::dbgs() << "\n");
auto type = mathLibFuncType.getInput(0).cast<fir::ComplexType>(); auto type = mlir::cast<fir::ComplexType>(mathLibFuncType.getInput(0));
auto kind = type.getElementType().cast<fir::RealType>().getFKind(); auto kind = mlir::cast<fir::RealType>(type.getElementType()).getFKind();
auto realTy = builder.getRealType(kind); auto realTy = builder.getRealType(kind);
auto mComplexTy = mlir::ComplexType::get(realTy); auto mComplexTy = mlir::ComplexType::get(realTy);
@ -1394,14 +1394,14 @@ private:
// Floating point can be mlir::FloatType or fir::real // Floating point can be mlir::FloatType or fir::real
static unsigned getFloatingPointWidth(mlir::Type t) { static unsigned getFloatingPointWidth(mlir::Type t) {
if (auto f{t.dyn_cast<mlir::FloatType>()}) if (auto f{mlir::dyn_cast<mlir::FloatType>(t)})
return f.getWidth(); return f.getWidth();
// FIXME: Get width another way for fir.real/complex // FIXME: Get width another way for fir.real/complex
// - use fir/KindMapping.h and llvm::Type // - use fir/KindMapping.h and llvm::Type
// - or use evaluate/type.h // - or use evaluate/type.h
if (auto r{t.dyn_cast<fir::RealType>()}) if (auto r{mlir::dyn_cast<fir::RealType>(t)})
return r.getFKind() * 4; return r.getFKind() * 4;
if (auto cplx{t.dyn_cast<fir::ComplexType>()}) if (auto cplx{mlir::dyn_cast<fir::ComplexType>(t)})
return cplx.getFKind() * 4; return cplx.getFKind() * 4;
llvm_unreachable("not a floating-point type"); llvm_unreachable("not a floating-point type");
} }
@ -1410,8 +1410,8 @@ private:
if (from == to) if (from == to)
return Conversion::None; return Conversion::None;
if (auto fromIntTy{from.dyn_cast<mlir::IntegerType>()}) { if (auto fromIntTy{mlir::dyn_cast<mlir::IntegerType>(from)}) {
if (auto toIntTy{to.dyn_cast<mlir::IntegerType>()}) { if (auto toIntTy{mlir::dyn_cast<mlir::IntegerType>(to)}) {
return fromIntTy.getWidth() > toIntTy.getWidth() ? Conversion::Narrow return fromIntTy.getWidth() > toIntTy.getWidth() ? Conversion::Narrow
: Conversion::Extend; : Conversion::Extend;
} }
@ -1423,8 +1423,8 @@ private:
: Conversion::Extend; : Conversion::Extend;
} }
if (auto fromCplxTy{from.dyn_cast<fir::ComplexType>()}) { if (auto fromCplxTy{mlir::dyn_cast<fir::ComplexType>(from)}) {
if (auto toCplxTy{to.dyn_cast<fir::ComplexType>()}) { if (auto toCplxTy{mlir::dyn_cast<fir::ComplexType>(to)}) {
return getFloatingPointWidth(fromCplxTy) > return getFloatingPointWidth(fromCplxTy) >
getFloatingPointWidth(toCplxTy) getFloatingPointWidth(toCplxTy)
? Conversion::Narrow ? Conversion::Narrow
@ -1550,10 +1550,10 @@ fir::ExtendedValue toExtendedValue(mlir::Value val, fir::FirOpBuilder &builder,
if (charHelper.isCharacterScalar(type)) if (charHelper.isCharacterScalar(type))
return charHelper.toExtendedValue(val); return charHelper.toExtendedValue(val);
if (auto refType = type.dyn_cast<fir::ReferenceType>()) if (auto refType = mlir::dyn_cast<fir::ReferenceType>(type))
type = refType.getEleTy(); type = refType.getEleTy();
if (auto arrayType = type.dyn_cast<fir::SequenceType>()) { if (auto arrayType = mlir::dyn_cast<fir::SequenceType>(type)) {
type = arrayType.getEleTy(); type = arrayType.getEleTy();
for (fir::SequenceType::Extent extent : arrayType.getShape()) { for (fir::SequenceType::Extent extent : arrayType.getShape()) {
if (extent == fir::SequenceType::getUnknownExtent()) if (extent == fir::SequenceType::getUnknownExtent())
@ -1566,7 +1566,8 @@ fir::ExtendedValue toExtendedValue(mlir::Value val, fir::FirOpBuilder &builder,
// have been used in the interface). // have been used in the interface).
if (extents.size() + 1 < arrayType.getShape().size()) if (extents.size() + 1 < arrayType.getShape().size())
mlir::emitError(loc, "cannot retrieve array extents from type"); mlir::emitError(loc, "cannot retrieve array extents from type");
} else if (type.isa<fir::BoxType>() || type.isa<fir::RecordType>()) { } else if (mlir::isa<fir::BoxType>(type) ||
mlir::isa<fir::RecordType>(type)) {
fir::emitFatalError(loc, "not yet implemented: descriptor or derived type"); fir::emitFatalError(loc, "not yet implemented: descriptor or derived type");
} }
@ -1580,10 +1581,10 @@ mlir::Value toValue(const fir::ExtendedValue &val, fir::FirOpBuilder &builder,
if (const fir::CharBoxValue *charBox = val.getCharBox()) { if (const fir::CharBoxValue *charBox = val.getCharBox()) {
mlir::Value buffer = charBox->getBuffer(); mlir::Value buffer = charBox->getBuffer();
auto buffTy = buffer.getType(); auto buffTy = buffer.getType();
if (buffTy.isa<mlir::FunctionType>()) if (mlir::isa<mlir::FunctionType>(buffTy))
fir::emitFatalError( fir::emitFatalError(
loc, "A character's buffer type cannot be a function type."); loc, "A character's buffer type cannot be a function type.");
if (buffTy.isa<fir::BoxCharType>()) if (mlir::isa<fir::BoxCharType>(buffTy))
return buffer; return buffer;
return fir::factory::CharacterExprHelper{builder, loc}.createEmboxChar( return fir::factory::CharacterExprHelper{builder, loc}.createEmboxChar(
buffer, charBox->getLen()); buffer, charBox->getLen());
@ -1827,27 +1828,27 @@ IntrinsicLibrary::invokeGenerator(SubroutineGenerator generator,
/// Note: mlir has Type::dump(ostream) methods but it may add "!" that is not /// Note: mlir has Type::dump(ostream) methods but it may add "!" that is not
/// suitable for function names. /// suitable for function names.
static std::string typeToString(mlir::Type t) { static std::string typeToString(mlir::Type t) {
if (auto refT{t.dyn_cast<fir::ReferenceType>()}) if (auto refT{mlir::dyn_cast<fir::ReferenceType>(t)})
return "ref_" + typeToString(refT.getEleTy()); return "ref_" + typeToString(refT.getEleTy());
if (auto i{t.dyn_cast<mlir::IntegerType>()}) { if (auto i{mlir::dyn_cast<mlir::IntegerType>(t)}) {
return "i" + std::to_string(i.getWidth()); return "i" + std::to_string(i.getWidth());
} }
if (auto cplx{t.dyn_cast<fir::ComplexType>()}) { if (auto cplx{mlir::dyn_cast<fir::ComplexType>(t)}) {
return "z" + std::to_string(cplx.getFKind()); return "z" + std::to_string(cplx.getFKind());
} }
if (auto real{t.dyn_cast<fir::RealType>()}) { if (auto real{mlir::dyn_cast<fir::RealType>(t)}) {
return "r" + std::to_string(real.getFKind()); return "r" + std::to_string(real.getFKind());
} }
if (auto f{t.dyn_cast<mlir::FloatType>()}) { if (auto f{mlir::dyn_cast<mlir::FloatType>(t)}) {
return "f" + std::to_string(f.getWidth()); return "f" + std::to_string(f.getWidth());
} }
if (auto logical{t.dyn_cast<fir::LogicalType>()}) { if (auto logical{mlir::dyn_cast<fir::LogicalType>(t)}) {
return "l" + std::to_string(logical.getFKind()); return "l" + std::to_string(logical.getFKind());
} }
if (auto character{t.dyn_cast<fir::CharacterType>()}) { if (auto character{mlir::dyn_cast<fir::CharacterType>(t)}) {
return "c" + std::to_string(character.getFKind()); return "c" + std::to_string(character.getFKind());
} }
if (auto boxCharacter{t.dyn_cast<fir::BoxCharType>()}) { if (auto boxCharacter{mlir::dyn_cast<fir::BoxCharType>(t)}) {
return "bc" + std::to_string(boxCharacter.getEleTy().getFKind()); return "bc" + std::to_string(boxCharacter.getEleTy().getFKind());
} }
llvm_unreachable("no mangling for type"); llvm_unreachable("no mangling for type");
@ -1907,7 +1908,7 @@ mlir::func::FuncOp IntrinsicLibrary::getWrapper(GeneratorType generator,
mlir::Location localLoc = localBuilder->getUnknownLoc(); mlir::Location localLoc = localBuilder->getUnknownLoc();
llvm::SmallVector<mlir::Value> localArguments; llvm::SmallVector<mlir::Value> localArguments;
for (mlir::BlockArgument bArg : function.front().getArguments()) { for (mlir::BlockArgument bArg : function.front().getArguments()) {
auto refType = bArg.getType().dyn_cast<fir::ReferenceType>(); auto refType = mlir::dyn_cast<fir::ReferenceType>(bArg.getType());
if (loadRefArguments && refType) { if (loadRefArguments && refType) {
auto loaded = localBuilder->create<fir::LoadOp>(localLoc, bArg); auto loaded = localBuilder->create<fir::LoadOp>(localLoc, bArg);
localArguments.push_back(loaded); localArguments.push_back(loaded);
@ -2060,7 +2061,7 @@ mlir::SymbolRefAttr IntrinsicLibrary::getUnrestrictedIntrinsicSymbolRefAttr(
if (!funcOp) { if (!funcOp) {
llvm::SmallVector<mlir::Type> argTypes; llvm::SmallVector<mlir::Type> argTypes;
for (mlir::Type type : signature.getInputs()) { for (mlir::Type type : signature.getInputs()) {
if (auto refType = type.dyn_cast<fir::ReferenceType>()) if (auto refType = mlir::dyn_cast<fir::ReferenceType>(type))
argTypes.push_back(refType.getEleTy()); argTypes.push_back(refType.getEleTy());
else else
argTypes.push_back(type); argTypes.push_back(type);
@ -2145,7 +2146,7 @@ mlir::Value IntrinsicLibrary::genAbs(mlir::Type resultType,
// math::AbsFOp but it does not support all fir floating point types. // math::AbsFOp but it does not support all fir floating point types.
return genRuntimeCall("abs", resultType, args); return genRuntimeCall("abs", resultType, args);
} }
if (auto intType = type.dyn_cast<mlir::IntegerType>()) { if (auto intType = mlir::dyn_cast<mlir::IntegerType>(type)) {
// At the time of this implementation there is no abs op in mlir. // At the time of this implementation there is no abs op in mlir.
// So, implement abs here without branching. // So, implement abs here without branching.
mlir::Value shift = mlir::Value shift =
@ -2379,8 +2380,8 @@ IntrinsicLibrary::genAssociated(mlir::Type resultType,
llvm::ArrayRef<fir::ExtendedValue> args) { llvm::ArrayRef<fir::ExtendedValue> args) {
assert(args.size() == 2); assert(args.size() == 2);
mlir::Type ptrTy = fir::getBase(args[0]).getType(); mlir::Type ptrTy = fir::getBase(args[0]).getType();
if (ptrTy && if (ptrTy && (fir::isBoxProcAddressType(ptrTy) ||
(fir::isBoxProcAddressType(ptrTy) || ptrTy.isa<fir::BoxProcType>())) { mlir::isa<fir::BoxProcType>(ptrTy))) {
mlir::Value pointerBoxProc = mlir::Value pointerBoxProc =
fir::isBoxProcAddressType(ptrTy) fir::isBoxProcAddressType(ptrTy)
? builder.create<fir::LoadOp>(loc, fir::getBase(args[0])) ? builder.create<fir::LoadOp>(loc, fir::getBase(args[0]))
@ -2392,7 +2393,7 @@ IntrinsicLibrary::genAssociated(mlir::Type resultType,
mlir::Value target = fir::getBase(args[1]); mlir::Value target = fir::getBase(args[1]);
if (fir::isBoxProcAddressType(target.getType())) if (fir::isBoxProcAddressType(target.getType()))
target = builder.create<fir::LoadOp>(loc, target); target = builder.create<fir::LoadOp>(loc, target);
if (target.getType().isa<fir::BoxProcType>()) if (mlir::isa<fir::BoxProcType>(target.getType()))
target = builder.create<fir::BoxAddrOp>(loc, target); target = builder.create<fir::BoxAddrOp>(loc, target);
mlir::Type intPtrTy = builder.getIntPtrType(); mlir::Type intPtrTy = builder.getIntPtrType();
mlir::Value pointerInt = mlir::Value pointerInt =
@ -2649,7 +2650,7 @@ static mlir::Value getAddrFromBox(fir::FirOpBuilder &builder,
mlir::Value argValue = fir::getBase(arg); mlir::Value argValue = fir::getBase(arg);
mlir::Value addr{nullptr}; mlir::Value addr{nullptr};
if (isFunc) { if (isFunc) {
auto funcTy = argValue.getType().cast<fir::BoxProcType>().getEleTy(); auto funcTy = mlir::cast<fir::BoxProcType>(argValue.getType()).getEleTy();
addr = builder.create<fir::BoxAddrOp>(loc, funcTy, argValue); addr = builder.create<fir::BoxAddrOp>(loc, funcTy, argValue);
} else { } else {
const auto *box = arg.getBoxOf<fir::BoxValue>(); const auto *box = arg.getBoxOf<fir::BoxValue>();
@ -3029,7 +3030,7 @@ void IntrinsicLibrary::genDateAndTime(llvm::ArrayRef<fir::ExtendedValue> args) {
mlir::Value IntrinsicLibrary::genDim(mlir::Type resultType, mlir::Value IntrinsicLibrary::genDim(mlir::Type resultType,
llvm::ArrayRef<mlir::Value> args) { llvm::ArrayRef<mlir::Value> args) {
assert(args.size() == 2); assert(args.size() == 2);
if (resultType.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(resultType)) {
mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0); mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
auto diff = builder.create<mlir::arith::SubIOp>(loc, args[0], args[1]); auto diff = builder.create<mlir::arith::SubIOp>(loc, args[0], args[1]);
auto cmp = builder.create<mlir::arith::CmpIOp>( auto cmp = builder.create<mlir::arith::CmpIOp>(
@ -3574,7 +3575,7 @@ IntrinsicLibrary::genReduction(FN func, FD funcDim, llvm::StringRef errMsg,
if (absentDim || rank == 1) { if (absentDim || rank == 1) {
mlir::Type ty = array.getType(); mlir::Type ty = array.getType();
mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
if (fir::isa_complex(eleTy)) { if (fir::isa_complex(eleTy)) {
mlir::Value result = builder.createTemporary(loc, eleTy); mlir::Value result = builder.createTemporary(loc, eleTy);
func(builder, loc, array, mask, result); func(builder, loc, array, mask, result);
@ -3646,7 +3647,7 @@ mlir::Value IntrinsicLibrary::genIbits(mlir::Type resultType,
mlir::Value pos = builder.createConvert(loc, resultType, args[1]); mlir::Value pos = builder.createConvert(loc, resultType, args[1]);
mlir::Value len = builder.createConvert(loc, resultType, args[2]); mlir::Value len = builder.createConvert(loc, resultType, args[2]);
mlir::Value bitSize = builder.createIntegerConstant( mlir::Value bitSize = builder.createIntegerConstant(
loc, resultType, resultType.cast<mlir::IntegerType>().getWidth()); loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
auto shiftCount = builder.create<mlir::arith::SubIOp>(loc, bitSize, len); auto shiftCount = builder.create<mlir::arith::SubIOp>(loc, bitSize, len);
mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0); mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
mlir::Value ones = builder.createAllOnesInteger(loc, resultType); mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
@ -3686,7 +3687,7 @@ IntrinsicLibrary::genIchar(mlir::Type resultType,
mlir::Value buffer = charBox->getBuffer(); mlir::Value buffer = charBox->getBuffer();
mlir::Type bufferTy = buffer.getType(); mlir::Type bufferTy = buffer.getType();
mlir::Value charVal; mlir::Value charVal;
if (auto charTy = bufferTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(bufferTy)) {
assert(charTy.singleton()); assert(charTy.singleton());
charVal = buffer; charVal = buffer;
} else { } else {
@ -3759,7 +3760,7 @@ void IntrinsicLibrary::genRaiseExcept(int except, mlir::Value cond) {
static std::pair<mlir::Value, mlir::Type> static std::pair<mlir::Value, mlir::Type>
getFieldRef(fir::FirOpBuilder &builder, mlir::Location loc, mlir::Value rec) { getFieldRef(fir::FirOpBuilder &builder, mlir::Location loc, mlir::Value rec) {
auto recType = auto recType =
fir::unwrapPassByRefType(rec.getType()).dyn_cast<fir::RecordType>(); mlir::dyn_cast<fir::RecordType>(fir::unwrapPassByRefType(rec.getType()));
assert(recType.getTypeList().size() == 1 && "expected exactly one component"); assert(recType.getTypeList().size() == 1 && "expected exactly one component");
auto [fieldName, fieldTy] = recType.getTypeList().front(); auto [fieldName, fieldTy] = recType.getTypeList().front();
mlir::Value field = builder.create<fir::FieldIndexOp>( mlir::Value field = builder.create<fir::FieldIndexOp>(
@ -3808,7 +3809,7 @@ mlir::Value IntrinsicLibrary::genIeeeClass(mlir::Type resultType,
assert(args.size() == 1); assert(args.size() == 1);
mlir::Value realVal = args[0]; mlir::Value realVal = args[0];
mlir::FloatType realType = realVal.getType().dyn_cast<mlir::FloatType>(); mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(realVal.getType());
const unsigned intWidth = realType.getWidth(); const unsigned intWidth = realType.getWidth();
mlir::Type intType = builder.getIntegerType(intWidth); mlir::Type intType = builder.getIntegerType(intWidth);
mlir::Value intVal = mlir::Value intVal =
@ -4056,8 +4057,10 @@ IntrinsicLibrary::genIeeeCopySign(mlir::Type resultType,
assert(args.size() == 2); assert(args.size() == 2);
mlir::Value xRealVal = args[0]; mlir::Value xRealVal = args[0];
mlir::Value yRealVal = args[1]; mlir::Value yRealVal = args[1];
mlir::FloatType xRealType = xRealVal.getType().dyn_cast<mlir::FloatType>(); mlir::FloatType xRealType =
mlir::FloatType yRealType = yRealVal.getType().dyn_cast<mlir::FloatType>(); mlir::dyn_cast<mlir::FloatType>(xRealVal.getType());
mlir::FloatType yRealType =
mlir::dyn_cast<mlir::FloatType>(yRealVal.getType());
if (yRealType == mlir::FloatType::getBF16(builder.getContext())) { if (yRealType == mlir::FloatType::getBF16(builder.getContext())) {
// Workaround: CopySignOp and BitcastOp don't work for kind 3 arg Y. // Workaround: CopySignOp and BitcastOp don't work for kind 3 arg Y.
@ -4106,7 +4109,7 @@ void IntrinsicLibrary::genIeeeGetFlag(llvm::ArrayRef<fir::ExtendedValue> args) {
mlir::Value flag = fir::getBase(args[0]); mlir::Value flag = fir::getBase(args[0]);
mlir::Value flagValue = fir::getBase(args[1]); mlir::Value flagValue = fir::getBase(args[1]);
mlir::Type resultTy = mlir::Type resultTy =
flagValue.getType().dyn_cast<fir::ReferenceType>().getEleTy(); mlir::dyn_cast<fir::ReferenceType>(flagValue.getType()).getEleTy();
mlir::Type i32Ty = builder.getIntegerType(32); mlir::Type i32Ty = builder.getIntegerType(32);
mlir::Value zero = builder.createIntegerConstant(loc, i32Ty, 0); mlir::Value zero = builder.createIntegerConstant(loc, i32Ty, 0);
auto [fieldRef, ignore] = getFieldRef(builder, loc, flag); auto [fieldRef, ignore] = getFieldRef(builder, loc, flag);
@ -4130,7 +4133,7 @@ void IntrinsicLibrary::genIeeeGetHaltingMode(
mlir::Value flag = fir::getBase(args[0]); mlir::Value flag = fir::getBase(args[0]);
mlir::Value halting = fir::getBase(args[1]); mlir::Value halting = fir::getBase(args[1]);
mlir::Type resultTy = mlir::Type resultTy =
halting.getType().dyn_cast<fir::ReferenceType>().getEleTy(); mlir::dyn_cast<fir::ReferenceType>(halting.getType()).getEleTy();
mlir::Type i32Ty = builder.getIntegerType(32); mlir::Type i32Ty = builder.getIntegerType(32);
mlir::Value zero = builder.createIntegerConstant(loc, i32Ty, 0); mlir::Value zero = builder.createIntegerConstant(loc, i32Ty, 0);
auto [fieldRef, ignore] = getFieldRef(builder, loc, flag); auto [fieldRef, ignore] = getFieldRef(builder, loc, flag);
@ -4248,7 +4251,7 @@ mlir::Value IntrinsicLibrary::genIeeeLogb(mlir::Type resultType,
// : ieee_copy_sign(X, 1.0) // +infinity or NaN // : ieee_copy_sign(X, 1.0) // +infinity or NaN
assert(args.size() == 1); assert(args.size() == 1);
mlir::Value realVal = args[0]; mlir::Value realVal = args[0];
mlir::FloatType realType = realVal.getType().dyn_cast<mlir::FloatType>(); mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(realVal.getType());
int bitWidth = realType.getWidth(); int bitWidth = realType.getWidth();
mlir::Type intType = builder.getIntegerType(realType.getWidth()); mlir::Type intType = builder.getIntegerType(realType.getWidth());
mlir::Value intVal = mlir::Value intVal =
@ -4545,7 +4548,7 @@ mlir::Value IntrinsicLibrary::genIeeeSignbit(mlir::Type resultType,
// Check if the sign bit of arg X is set. // Check if the sign bit of arg X is set.
assert(args.size() == 1); assert(args.size() == 1);
mlir::Value realVal = args[0]; mlir::Value realVal = args[0];
mlir::FloatType realType = realVal.getType().dyn_cast<mlir::FloatType>(); mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(realVal.getType());
int bitWidth = realType.getWidth(); int bitWidth = realType.getWidth();
if (realType == mlir::FloatType::getBF16(builder.getContext())) { if (realType == mlir::FloatType::getBF16(builder.getContext())) {
// Workaround: can't bitcast or convert real(3) to integer(2) or real(2). // Workaround: can't bitcast or convert real(3) to integer(2) or real(2).
@ -4642,7 +4645,7 @@ mlir::Value IntrinsicLibrary::genIeeeValue(mlir::Type resultType,
// A compiler generated call has one argument: // A compiler generated call has one argument:
// - arg[0] is an index constant // - arg[0] is an index constant
assert(args.size() == 1 || args.size() == 2); assert(args.size() == 1 || args.size() == 2);
mlir::FloatType realType = resultType.dyn_cast<mlir::FloatType>(); mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(resultType);
int bitWidth = realType.getWidth(); int bitWidth = realType.getWidth();
mlir::Type intType = builder.getIntegerType(bitWidth); mlir::Type intType = builder.getIntegerType(bitWidth);
mlir::Type valueTy = bitWidth <= 64 ? intType : builder.getIntegerType(64); mlir::Type valueTy = bitWidth <= 64 ? intType : builder.getIntegerType(64);
@ -4884,7 +4887,7 @@ mlir::Value IntrinsicLibrary::genIshft(mlir::Type resultType,
// : I << abs(SHIFT) // : I << abs(SHIFT)
assert(args.size() == 2); assert(args.size() == 2);
mlir::Value bitSize = builder.createIntegerConstant( mlir::Value bitSize = builder.createIntegerConstant(
loc, resultType, resultType.cast<mlir::IntegerType>().getWidth()); loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0); mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
mlir::Value shift = builder.createConvert(loc, resultType, args[1]); mlir::Value shift = builder.createConvert(loc, resultType, args[1]);
mlir::Value absShift = genAbs(resultType, {shift}); mlir::Value absShift = genAbs(resultType, {shift});
@ -4920,7 +4923,7 @@ mlir::Value IntrinsicLibrary::genIshftc(mlir::Type resultType,
// Return: SHIFT == 0 || SIZE == abs(SHIFT) ? I : (unchanged | left | right) // Return: SHIFT == 0 || SIZE == abs(SHIFT) ? I : (unchanged | left | right)
assert(args.size() == 3); assert(args.size() == 3);
mlir::Value bitSize = builder.createIntegerConstant( mlir::Value bitSize = builder.createIntegerConstant(
loc, resultType, resultType.cast<mlir::IntegerType>().getWidth()); loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
mlir::Value I = args[0]; mlir::Value I = args[0];
mlir::Value shift = builder.createConvert(loc, resultType, args[1]); mlir::Value shift = builder.createConvert(loc, resultType, args[1]);
mlir::Value size = mlir::Value size =
@ -5027,7 +5030,7 @@ IntrinsicLibrary::genLoc(mlir::Type resultType,
mlir::Value box = fir::getBase(args[0]); mlir::Value box = fir::getBase(args[0]);
assert(fir::isa_box_type(box.getType()) && assert(fir::isa_box_type(box.getType()) &&
"argument must have been lowered to box type"); "argument must have been lowered to box type");
bool isFunc = box.getType().isa<fir::BoxProcType>(); bool isFunc = mlir::isa<fir::BoxProcType>(box.getType());
if (!isOptional(box)) { if (!isOptional(box)) {
mlir::Value argAddr = getAddrFromBox(builder, loc, args[0], isFunc); mlir::Value argAddr = getAddrFromBox(builder, loc, args[0], isFunc);
return builder.createConvert(loc, resultType, argAddr); return builder.createConvert(loc, resultType, argAddr);
@ -5156,7 +5159,7 @@ IntrinsicLibrary::genMerge(mlir::Type,
auto convertToStaticType = [&](mlir::Value polymorphic, auto convertToStaticType = [&](mlir::Value polymorphic,
mlir::Value other) -> mlir::Value { mlir::Value other) -> mlir::Value {
mlir::Type otherType = other.getType(); mlir::Type otherType = other.getType();
if (otherType.isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(otherType))
return builder.create<fir::ReboxOp>(loc, otherType, polymorphic, return builder.create<fir::ReboxOp>(loc, otherType, polymorphic,
/*shape*/ mlir::Value{}, /*shape*/ mlir::Value{},
/*slice=*/mlir::Value{}); /*slice=*/mlir::Value{});
@ -5209,7 +5212,7 @@ mlir::Value IntrinsicLibrary::genMergeBits(mlir::Type resultType,
mlir::Value IntrinsicLibrary::genMod(mlir::Type resultType, mlir::Value IntrinsicLibrary::genMod(mlir::Type resultType,
llvm::ArrayRef<mlir::Value> args) { llvm::ArrayRef<mlir::Value> args) {
assert(args.size() == 2); assert(args.size() == 2);
if (resultType.isa<mlir::IntegerType>()) if (mlir::isa<mlir::IntegerType>(resultType))
return builder.create<mlir::arith::RemSIOp>(loc, args[0], args[1]); return builder.create<mlir::arith::RemSIOp>(loc, args[0], args[1]);
// Use runtime. // Use runtime.
@ -5231,7 +5234,7 @@ mlir::Value IntrinsicLibrary::genModulo(mlir::Type resultType,
// - Otherwise, when A/P < 0 and MOD(A,P) !=0, then MODULO(A, P) = // - Otherwise, when A/P < 0 and MOD(A,P) !=0, then MODULO(A, P) =
// A-FLOOR(A/P)*P = A-(INT(A/P)-1)*P = A-INT(A/P)*P+P = MOD(A,P)+P // A-FLOOR(A/P)*P = A-(INT(A/P)-1)*P = A-INT(A/P)*P+P = MOD(A,P)+P
// Note that A/P < 0 if and only if A and P signs are different. // Note that A/P < 0 if and only if A and P signs are different.
if (resultType.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(resultType)) {
auto remainder = auto remainder =
builder.create<mlir::arith::RemSIOp>(loc, args[0], args[1]); builder.create<mlir::arith::RemSIOp>(loc, args[0], args[1]);
auto argXor = builder.create<mlir::arith::XOrIOp>(loc, args[0], args[1]); auto argXor = builder.create<mlir::arith::XOrIOp>(loc, args[0], args[1]);
@ -5344,7 +5347,7 @@ void IntrinsicLibrary::genMvbits(llvm::ArrayRef<fir::ExtendedValue> args) {
mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0); mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
mlir::Value ones = builder.createAllOnesInteger(loc, resultType); mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
mlir::Value bitSize = builder.createIntegerConstant( mlir::Value bitSize = builder.createIntegerConstant(
loc, resultType, resultType.cast<mlir::IntegerType>().getWidth()); loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
auto shiftCount = builder.create<mlir::arith::SubIOp>(loc, bitSize, len); auto shiftCount = builder.create<mlir::arith::SubIOp>(loc, bitSize, len);
auto mask = builder.create<mlir::arith::ShRUIOp>(loc, ones, shiftCount); auto mask = builder.create<mlir::arith::ShRUIOp>(loc, ones, shiftCount);
auto unchangedTmp1 = builder.create<mlir::arith::ShLIOp>(loc, mask, topos); auto unchangedTmp1 = builder.create<mlir::arith::ShLIOp>(loc, mask, topos);
@ -5628,7 +5631,7 @@ IntrinsicLibrary::genReshape(mlir::Type resultType,
assert(fir::BoxValue(shape).rank() == 1); assert(fir::BoxValue(shape).rank() == 1);
mlir::Type shapeTy = shape.getType(); mlir::Type shapeTy = shape.getType();
mlir::Type shapeArrTy = fir::dyn_cast_ptrOrBoxEleTy(shapeTy); mlir::Type shapeArrTy = fir::dyn_cast_ptrOrBoxEleTy(shapeTy);
auto resultRank = shapeArrTy.cast<fir::SequenceType>().getShape()[0]; auto resultRank = mlir::cast<fir::SequenceType>(shapeArrTy).getShape()[0];
if (resultRank == fir::SequenceType::getUnknownExtent()) if (resultRank == fir::SequenceType::getUnknownExtent())
TODO(loc, "intrinsic: reshape requires computing rank of result"); TODO(loc, "intrinsic: reshape requires computing rank of result");
@ -5921,7 +5924,7 @@ void IntrinsicLibrary::genSignalSubroutine(
mlir::Value IntrinsicLibrary::genSign(mlir::Type resultType, mlir::Value IntrinsicLibrary::genSign(mlir::Type resultType,
llvm::ArrayRef<mlir::Value> args) { llvm::ArrayRef<mlir::Value> args) {
assert(args.size() == 2); assert(args.size() == 2);
if (resultType.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(resultType)) {
mlir::Value abs = genAbs(resultType, {args[0]}); mlir::Value abs = genAbs(resultType, {args[0]});
mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0); mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
auto neg = builder.create<mlir::arith::SubIOp>(loc, zero, abs); auto neg = builder.create<mlir::arith::SubIOp>(loc, zero, abs);

View File

@ -28,7 +28,7 @@ createNewFirBox(fir::FirOpBuilder &builder, mlir::Location loc,
const fir::MutableBoxValue &box, mlir::Value addr, const fir::MutableBoxValue &box, mlir::Value addr,
mlir::ValueRange lbounds, mlir::ValueRange extents, mlir::ValueRange lbounds, mlir::ValueRange extents,
mlir::ValueRange lengths, mlir::Value tdesc = {}) { mlir::ValueRange lengths, mlir::Value tdesc = {}) {
if (addr.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(addr.getType()))
// The entity is already boxed. // The entity is already boxed.
return builder.createConvert(loc, box.getBoxTy(), addr); return builder.createConvert(loc, box.getBoxTy(), addr);
@ -53,20 +53,21 @@ createNewFirBox(fir::FirOpBuilder &builder, mlir::Location loc,
// error in the embox). // error in the embox).
llvm::SmallVector<mlir::Value> cleanedLengths; llvm::SmallVector<mlir::Value> cleanedLengths;
auto cleanedAddr = addr; auto cleanedAddr = addr;
if (auto charTy = box.getEleTy().dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(box.getEleTy())) {
// Cast address to box type so that both input and output type have // Cast address to box type so that both input and output type have
// unknown or constant lengths. // unknown or constant lengths.
auto bt = box.getBaseTy(); auto bt = box.getBaseTy();
auto addrTy = addr.getType(); auto addrTy = addr.getType();
auto type = addrTy.isa<fir::HeapType>() ? fir::HeapType::get(bt) auto type = mlir::isa<fir::HeapType>(addrTy) ? fir::HeapType::get(bt)
: addrTy.isa<fir::PointerType>() ? fir::PointerType::get(bt) : mlir::isa<fir::PointerType>(addrTy)
: builder.getRefType(bt); ? fir::PointerType::get(bt)
: builder.getRefType(bt);
cleanedAddr = builder.createConvert(loc, type, addr); cleanedAddr = builder.createConvert(loc, type, addr);
if (charTy.getLen() == fir::CharacterType::unknownLen()) if (charTy.getLen() == fir::CharacterType::unknownLen())
cleanedLengths.append(lengths.begin(), lengths.end()); cleanedLengths.append(lengths.begin(), lengths.end());
} else if (fir::isUnlimitedPolymorphicType(box.getBoxTy())) { } else if (fir::isUnlimitedPolymorphicType(box.getBoxTy())) {
if (auto charTy = fir::dyn_cast_ptrEleTy(addr.getType()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(
.dyn_cast<fir::CharacterType>()) { fir::dyn_cast_ptrEleTy(addr.getType()))) {
if (charTy.getLen() == fir::CharacterType::unknownLen()) if (charTy.getLen() == fir::CharacterType::unknownLen())
cleanedLengths.append(lengths.begin(), lengths.end()); cleanedLengths.append(lengths.begin(), lengths.end());
} }
@ -328,18 +329,18 @@ private:
mlir::Value fir::factory::createUnallocatedBox( mlir::Value fir::factory::createUnallocatedBox(
fir::FirOpBuilder &builder, mlir::Location loc, mlir::Type boxType, fir::FirOpBuilder &builder, mlir::Location loc, mlir::Type boxType,
mlir::ValueRange nonDeferredParams, mlir::Value typeSourceBox) { mlir::ValueRange nonDeferredParams, mlir::Value typeSourceBox) {
auto baseAddrType = boxType.dyn_cast<fir::BaseBoxType>().getEleTy(); auto baseAddrType = mlir::dyn_cast<fir::BaseBoxType>(boxType).getEleTy();
if (!fir::isa_ref_type(baseAddrType)) if (!fir::isa_ref_type(baseAddrType))
baseAddrType = builder.getRefType(baseAddrType); baseAddrType = builder.getRefType(baseAddrType);
auto type = fir::unwrapRefType(baseAddrType); auto type = fir::unwrapRefType(baseAddrType);
auto eleTy = fir::unwrapSequenceType(type); auto eleTy = fir::unwrapSequenceType(type);
if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy))
if (recTy.getNumLenParams() > 0) if (recTy.getNumLenParams() > 0)
TODO(loc, "creating unallocated fir.box of derived type with length " TODO(loc, "creating unallocated fir.box of derived type with length "
"parameters"); "parameters");
auto nullAddr = builder.createNullConstant(loc, baseAddrType); auto nullAddr = builder.createNullConstant(loc, baseAddrType);
mlir::Value shape; mlir::Value shape;
if (auto seqTy = type.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(type)) {
auto zero = builder.createIntegerConstant(loc, builder.getIndexType(), 0); auto zero = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), zero); llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), zero);
shape = builder.createShape( shape = builder.createShape(
@ -348,7 +349,7 @@ mlir::Value fir::factory::createUnallocatedBox(
// Provide dummy length parameters if they are dynamic. If a length parameter // Provide dummy length parameters if they are dynamic. If a length parameter
// is deferred. It is set to zero here and will be set on allocation. // is deferred. It is set to zero here and will be set on allocation.
llvm::SmallVector<mlir::Value> lenParams; llvm::SmallVector<mlir::Value> lenParams;
if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
if (charTy.getLen() == fir::CharacterType::unknownLen()) { if (charTy.getLen() == fir::CharacterType::unknownLen()) {
if (!nonDeferredParams.empty()) { if (!nonDeferredParams.empty()) {
lenParams.push_back(nonDeferredParams[0]); lenParams.push_back(nonDeferredParams[0]);
@ -592,7 +593,7 @@ void fir::factory::associateMutableBoxWithRemap(
auto cast = [&](mlir::Value addr) -> mlir::Value { auto cast = [&](mlir::Value addr) -> mlir::Value {
// Cast base addr to new sequence type. // Cast base addr to new sequence type.
auto ty = fir::dyn_cast_ptrEleTy(addr.getType()); auto ty = fir::dyn_cast_ptrEleTy(addr.getType());
if (auto seqTy = ty.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty)) {
fir::SequenceType::Shape shape(newRank, fir::SequenceType::Shape shape(newRank,
fir::SequenceType::getUnknownExtent()); fir::SequenceType::getUnknownExtent());
ty = fir::SequenceType::get(shape, seqTy.getEleTy()); ty = fir::SequenceType::get(shape, seqTy.getEleTy());
@ -673,10 +674,10 @@ void fir::factory::disassociateMutableBox(fir::FirOpBuilder &builder,
if (box.isPolymorphic() && polymorphicSetType) { if (box.isPolymorphic() && polymorphicSetType) {
// 7.3.2.3 point 7. The dynamic type of a disassociated pointer is the // 7.3.2.3 point 7. The dynamic type of a disassociated pointer is the
// same as its declared type. // same as its declared type.
auto boxTy = box.getBoxTy().dyn_cast<fir::BaseBoxType>(); auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getBoxTy());
auto eleTy = fir::unwrapPassByRefType(boxTy.getEleTy()); auto eleTy = fir::unwrapPassByRefType(boxTy.getEleTy());
mlir::Type derivedType = fir::getDerivedType(eleTy); mlir::Type derivedType = fir::getDerivedType(eleTy);
if (auto recTy = derivedType.dyn_cast<fir::RecordType>()) { if (auto recTy = mlir::dyn_cast<fir::RecordType>(derivedType)) {
fir::runtime::genNullifyDerivedType(builder, loc, box.getAddr(), recTy, fir::runtime::genNullifyDerivedType(builder, loc, box.getAddr(), recTy,
box.rank()); box.rank());
return; return;
@ -690,7 +691,7 @@ getNewLengths(fir::FirOpBuilder &builder, mlir::Location loc,
const fir::MutableBoxValue &box, mlir::ValueRange lenParams) { const fir::MutableBoxValue &box, mlir::ValueRange lenParams) {
llvm::SmallVector<mlir::Value> lengths; llvm::SmallVector<mlir::Value> lengths;
auto idxTy = builder.getIndexType(); auto idxTy = builder.getIndexType();
if (auto charTy = box.getEleTy().dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(box.getEleTy())) {
if (charTy.getLen() == fir::CharacterType::unknownLen()) { if (charTy.getLen() == fir::CharacterType::unknownLen()) {
if (box.hasNonDeferredLenParams()) { if (box.hasNonDeferredLenParams()) {
lengths.emplace_back( lengths.emplace_back(
@ -717,7 +718,7 @@ static mlir::Value allocateAndInitNewStorage(fir::FirOpBuilder &builder,
auto lengths = getNewLengths(builder, loc, box, lenParams); auto lengths = getNewLengths(builder, loc, box, lenParams);
auto newStorage = builder.create<fir::AllocMemOp>( auto newStorage = builder.create<fir::AllocMemOp>(
loc, box.getBaseTy(), allocName, lengths, extents); loc, box.getBaseTy(), allocName, lengths, extents);
if (box.getEleTy().isa<fir::RecordType>()) { if (mlir::isa<fir::RecordType>(box.getEleTy())) {
// TODO: skip runtime initialization if this is not required. Currently, // TODO: skip runtime initialization if this is not required. Currently,
// there is no way to know here if a derived type needs it or not. But the // there is no way to know here if a derived type needs it or not. But the
// information is available at compile time and could be reflected here // information is available at compile time and could be reflected here
@ -742,7 +743,7 @@ void fir::factory::genInlinedAllocation(
lengths, safeExtents); lengths, safeExtents);
MutablePropertyWriter{builder, loc, box}.updateMutableBox( MutablePropertyWriter{builder, loc, box}.updateMutableBox(
heap, lbounds, safeExtents, lengths); heap, lbounds, safeExtents, lengths);
if (box.getEleTy().isa<fir::RecordType>()) { if (mlir::isa<fir::RecordType>(box.getEleTy())) {
// TODO: skip runtime initialization if this is not required. Currently, // TODO: skip runtime initialization if this is not required. Currently,
// there is no way to know here if a derived type needs it or not. But the // there is no way to know here if a derived type needs it or not. But the
// information is available at compile time and could be reflected here // information is available at compile time and could be reflected here

View File

@ -1119,7 +1119,7 @@ PPCIntrinsicLibrary::genVecAbs(mlir::Type resultType,
funcOp = builder.createFunction(loc, fname, ftype); funcOp = builder.createFunction(loc, fname, ftype);
auto callOp{builder.create<fir::CallOp>(loc, funcOp, argBases[0])}; auto callOp{builder.create<fir::CallOp>(loc, funcOp, argBases[0])};
return callOp.getResult(0); return callOp.getResult(0);
} else if (auto eleTy = vTypeInfo.eleTy.dyn_cast<mlir::IntegerType>()) { } else if (auto eleTy = mlir::dyn_cast<mlir::IntegerType>(vTypeInfo.eleTy)) {
// vec_abs(arg1) = max(0 - arg1, arg1) // vec_abs(arg1) = max(0 - arg1, arg1)
auto newVecTy{mlir::VectorType::get(vTypeInfo.len, eleTy)}; auto newVecTy{mlir::VectorType::get(vTypeInfo.len, eleTy)};
@ -1173,12 +1173,13 @@ fir::ExtendedValue PPCIntrinsicLibrary::genVecAddAndMulSubXor(
assert(args.size() == 2); assert(args.size() == 2);
auto argBases{getBasesForArgs(args)}; auto argBases{getBasesForArgs(args)};
auto argsTy{getTypesForArgs(argBases)}; auto argsTy{getTypesForArgs(argBases)};
assert(argsTy[0].isa<fir::VectorType>() && argsTy[1].isa<fir::VectorType>()); assert(mlir::isa<fir::VectorType>(argsTy[0]) &&
mlir::isa<fir::VectorType>(argsTy[1]));
auto vecTyInfo{getVecTypeFromFir(argBases[0])}; auto vecTyInfo{getVecTypeFromFir(argBases[0])};
const auto isInteger{vecTyInfo.eleTy.isa<mlir::IntegerType>()}; const auto isInteger{mlir::isa<mlir::IntegerType>(vecTyInfo.eleTy)};
const auto isFloat{vecTyInfo.eleTy.isa<mlir::FloatType>()}; const auto isFloat{mlir::isa<mlir::FloatType>(vecTyInfo.eleTy)};
assert((isInteger || isFloat) && "unknown vector type"); assert((isInteger || isFloat) && "unknown vector type");
auto vargs{convertVecArgs(builder, loc, vecTyInfo, argBases)}; auto vargs{convertVecArgs(builder, loc, vecTyInfo, argBases)};
@ -1212,7 +1213,7 @@ fir::ExtendedValue PPCIntrinsicLibrary::genVecAddAndMulSubXor(
arg2 = vargs[1]; arg2 = vargs[1];
} else if (isFloat) { } else if (isFloat) {
// bitcast the arguments to integer // bitcast the arguments to integer
auto wd{vecTyInfo.eleTy.dyn_cast<mlir::FloatType>().getWidth()}; auto wd{mlir::dyn_cast<mlir::FloatType>(vecTyInfo.eleTy).getWidth()};
auto ftype{builder.getIntegerType(wd)}; auto ftype{builder.getIntegerType(wd)};
auto bcVecTy{mlir::VectorType::get(vecTyInfo.len, ftype)}; auto bcVecTy{mlir::VectorType::get(vecTyInfo.len, ftype)};
arg1 = builder.create<mlir::vector::BitCastOp>(loc, bcVecTy, vargs[0]); arg1 = builder.create<mlir::vector::BitCastOp>(loc, bcVecTy, vargs[0]);
@ -1450,7 +1451,7 @@ PPCIntrinsicLibrary::genVecCmp(mlir::Type resultType,
mlir::Value res{nullptr}; mlir::Value res{nullptr};
if (auto eTy = vecTyInfo.eleTy.dyn_cast<mlir::IntegerType>()) { if (auto eTy = mlir::dyn_cast<mlir::IntegerType>(vecTyInfo.eleTy)) {
constexpr int firstArg{0}; constexpr int firstArg{0};
constexpr int secondArg{1}; constexpr int secondArg{1};
std::map<VecOp, std::array<int, 2>> argOrder{ std::map<VecOp, std::array<int, 2>> argOrder{
@ -1559,7 +1560,7 @@ PPCIntrinsicLibrary::genVecConvert(mlir::Type resultType,
case VecOp::Ctf: { case VecOp::Ctf: {
assert(args.size() == 2); assert(args.size() == 2);
auto convArg{builder.createConvert(loc, i32Ty, argBases[1])}; auto convArg{builder.createConvert(loc, i32Ty, argBases[1])};
auto eTy{vecTyInfo.eleTy.dyn_cast<mlir::IntegerType>()}; auto eTy{mlir::dyn_cast<mlir::IntegerType>(vecTyInfo.eleTy)};
assert(eTy && "Unsupported vector type"); assert(eTy && "Unsupported vector type");
const auto isUnsigned{eTy.isUnsignedInteger()}; const auto isUnsigned{eTy.isUnsignedInteger()};
const auto width{eTy.getWidth()}; const auto width{eTy.getWidth()};
@ -1587,10 +1588,9 @@ PPCIntrinsicLibrary::genVecConvert(mlir::Type resultType,
: builder.create<mlir::LLVM::SIToFPOp>(loc, ty, vArg1)}; : builder.create<mlir::LLVM::SIToFPOp>(loc, ty, vArg1)};
// construct vector<1./(1<<arg1), 1.0/(1<<arg1)> // construct vector<1./(1<<arg1), 1.0/(1<<arg1)>
auto constInt{ auto constInt{mlir::dyn_cast_or_null<mlir::IntegerAttr>(
mlir::dyn_cast<mlir::arith::ConstantOp>(argBases[1].getDefiningOp()) mlir::dyn_cast<mlir::arith::ConstantOp>(argBases[1].getDefiningOp())
.getValue() .getValue())};
.dyn_cast_or_null<mlir::IntegerAttr>()};
assert(constInt && "expected integer constant argument"); assert(constInt && "expected integer constant argument");
double f{1.0 / (1 << constInt.getInt())}; double f{1.0 / (1 << constInt.getInt())};
llvm::SmallVector<double> vals{f, f}; llvm::SmallVector<double> vals{f, f};
@ -1815,7 +1815,7 @@ static mlir::Value addOffsetToAddress(fir::FirOpBuilder &builder,
static mlir::Value reverseVectorElements(fir::FirOpBuilder &builder, static mlir::Value reverseVectorElements(fir::FirOpBuilder &builder,
mlir::Location loc, mlir::Value v, mlir::Location loc, mlir::Value v,
int64_t len) { int64_t len) {
assert(v.getType().isa<mlir::VectorType>()); assert(mlir::isa<mlir::VectorType>(v.getType()));
assert(len > 0); assert(len > 0);
llvm::SmallVector<int64_t, 16> mask; llvm::SmallVector<int64_t, 16> mask;
for (int64_t i = 0; i < len; ++i) { for (int64_t i = 0; i < len; ++i) {
@ -2144,10 +2144,9 @@ PPCIntrinsicLibrary::genVecPerm(mlir::Type resultType,
} }
case VecOp::Permi: { case VecOp::Permi: {
// arg3 is a constant // arg3 is a constant
auto constIntOp{ auto constIntOp{mlir::dyn_cast_or_null<mlir::IntegerAttr>(
mlir::dyn_cast<mlir::arith::ConstantOp>(argBases[2].getDefiningOp()) mlir::dyn_cast<mlir::arith::ConstantOp>(argBases[2].getDefiningOp())
.getValue() .getValue())};
.dyn_cast_or_null<mlir::IntegerAttr>()};
assert(constIntOp && "expected integer constant argument"); assert(constIntOp && "expected integer constant argument");
auto constInt{constIntOp.getInt()}; auto constInt{constIntOp.getInt()};
// arg1, arg2, and result type share same VecTypeInfo // arg1, arg2, and result type share same VecTypeInfo
@ -2321,10 +2320,9 @@ PPCIntrinsicLibrary::genVecShift(mlir::Type resultType,
} }
} else if (vop == VecOp::Sld || vop == VecOp::Sldw) { } else if (vop == VecOp::Sld || vop == VecOp::Sldw) {
assert(args.size() == 3); assert(args.size() == 3);
auto constIntOp = auto constIntOp = mlir::dyn_cast_or_null<mlir::IntegerAttr>(
mlir::dyn_cast<mlir::arith::ConstantOp>(argBases[2].getDefiningOp()) mlir::dyn_cast<mlir::arith::ConstantOp>(argBases[2].getDefiningOp())
.getValue() .getValue());
.dyn_cast_or_null<mlir::IntegerAttr>();
assert(constIntOp && "expected integer constant argument"); assert(constIntOp && "expected integer constant argument");
// Bitcast to vector<16xi8> // Bitcast to vector<16xi8>
@ -2797,16 +2795,16 @@ void PPCIntrinsicLibrary::genMmaIntr(llvm::ArrayRef<fir::ExtendedValue> args) {
auto vType{v.getType()}; auto vType{v.getType()};
mlir::Type targetType{intrFuncType.getInput(j)}; mlir::Type targetType{intrFuncType.getInput(j)};
if (vType != targetType) { if (vType != targetType) {
if (targetType.isa<mlir::VectorType>()) { if (mlir::isa<mlir::VectorType>(targetType)) {
// Perform vector type conversion for arguments passed by value. // Perform vector type conversion for arguments passed by value.
auto eleTy{vType.dyn_cast<fir::VectorType>().getEleTy()}; auto eleTy{mlir::dyn_cast<fir::VectorType>(vType).getEleTy()};
auto len{vType.dyn_cast<fir::VectorType>().getLen()}; auto len{mlir::dyn_cast<fir::VectorType>(vType).getLen()};
mlir::VectorType mlirType = mlir::VectorType::get(len, eleTy); mlir::VectorType mlirType = mlir::VectorType::get(len, eleTy);
auto v0{builder.createConvert(loc, mlirType, v)}; auto v0{builder.createConvert(loc, mlirType, v)};
auto v1{builder.create<mlir::vector::BitCastOp>(loc, targetType, v0)}; auto v1{builder.create<mlir::vector::BitCastOp>(loc, targetType, v0)};
intrArgs.push_back(v1); intrArgs.push_back(v1);
} else if (targetType.isa<mlir::IntegerType>() && } else if (mlir::isa<mlir::IntegerType>(targetType) &&
vType.isa<mlir::IntegerType>()) { mlir::isa<mlir::IntegerType>(vType)) {
auto v0{builder.createConvert(loc, targetType, v)}; auto v0{builder.createConvert(loc, targetType, v)};
intrArgs.push_back(v0); intrArgs.push_back(v0);
} else { } else {
@ -2861,7 +2859,7 @@ void PPCIntrinsicLibrary::genVecStore(llvm::ArrayRef<fir::ExtendedValue> args) {
if (arg1TyInfo.isFloat32()) { if (arg1TyInfo.isFloat32()) {
stTy = mlir::VectorType::get(len, i32ty); stTy = mlir::VectorType::get(len, i32ty);
fname = "llvm.ppc.altivec.stvewx"; fname = "llvm.ppc.altivec.stvewx";
} else if (arg1TyInfo.eleTy.isa<mlir::IntegerType>()) { } else if (mlir::isa<mlir::IntegerType>(arg1TyInfo.eleTy)) {
stTy = mlir::VectorType::get(len, mlir::IntegerType::get(context, width)); stTy = mlir::VectorType::get(len, mlir::IntegerType::get(context, width));
switch (width) { switch (width) {

View File

@ -27,7 +27,7 @@ mlir::Value fir::runtime::genMoveAlloc(fir::FirOpBuilder &builder,
if (fir::isPolymorphicType(from.getType()) && if (fir::isPolymorphicType(from.getType()) &&
!fir::isUnlimitedPolymorphicType(from.getType())) { !fir::isUnlimitedPolymorphicType(from.getType())) {
fir::ClassType clTy = fir::ClassType clTy =
fir::dyn_cast_ptrEleTy(from.getType()).dyn_cast<fir::ClassType>(); mlir::dyn_cast<fir::ClassType>(fir::dyn_cast_ptrEleTy(from.getType()));
mlir::Type derivedType = fir::unwrapInnerType(clTy.getEleTy()); mlir::Type derivedType = fir::unwrapInnerType(clTy.getEleTy());
declaredTypeDesc = declaredTypeDesc =
builder.create<fir::TypeDescOp>(loc, mlir::TypeAttr::get(derivedType)); builder.create<fir::TypeDescOp>(loc, mlir::TypeAttr::get(derivedType));

View File

@ -39,15 +39,15 @@ static void genCharacterSearch(FN func, fir::FirOpBuilder &builder,
/// Helper function to recover the KIND from the FIR type. /// Helper function to recover the KIND from the FIR type.
static int discoverKind(mlir::Type ty) { static int discoverKind(mlir::Type ty) {
if (auto charTy = ty.dyn_cast<fir::CharacterType>()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(ty))
return charTy.getFKind(); return charTy.getFKind();
if (auto eleTy = fir::dyn_cast_ptrEleTy(ty)) if (auto eleTy = fir::dyn_cast_ptrEleTy(ty))
return discoverKind(eleTy); return discoverKind(eleTy);
if (auto arrTy = ty.dyn_cast<fir::SequenceType>()) if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(ty))
return discoverKind(arrTy.getEleTy()); return discoverKind(arrTy.getEleTy());
if (auto boxTy = ty.dyn_cast<fir::BoxCharType>()) if (auto boxTy = mlir::dyn_cast<fir::BoxCharType>(ty))
return discoverKind(boxTy.getEleTy()); return discoverKind(boxTy.getEleTy());
if (auto boxTy = ty.dyn_cast<fir::BoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BoxType>(ty))
return discoverKind(boxTy.getEleTy()); return discoverKind(boxTy.getEleTy());
llvm_unreachable("unexpected character type"); llvm_unreachable("unexpected character type");
} }

View File

@ -228,7 +228,8 @@ void fir::runtime::genSystemClock(fir::FirOpBuilder &builder,
fir::IfOp ifOp{}; fir::IfOp ifOp{};
const bool isOptionalArg = const bool isOptionalArg =
fir::valueHasFirAttribute(arg, fir::getOptionalAttrName()); fir::valueHasFirAttribute(arg, fir::getOptionalAttrName());
if (type.dyn_cast<fir::PointerType>() || type.dyn_cast<fir::HeapType>()) { if (mlir::dyn_cast<fir::PointerType>(type) ||
mlir::dyn_cast<fir::HeapType>(type)) {
// Check for a disassociated pointer or an unallocated allocatable. // Check for a disassociated pointer or an unallocated allocatable.
assert(!isOptionalArg && "invalid optional argument"); assert(!isOptionalArg && "invalid optional argument");
ifOp = builder.create<fir::IfOp>(loc, builder.genIsNotNullAddr(loc, arg), ifOp = builder.create<fir::IfOp>(loc, builder.genIsNotNullAddr(loc, arg),
@ -242,7 +243,8 @@ void fir::runtime::genSystemClock(fir::FirOpBuilder &builder,
builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
mlir::Type kindTy = func.getFunctionType().getInput(0); mlir::Type kindTy = func.getFunctionType().getInput(0);
int integerKind = 8; int integerKind = 8;
if (auto intType = fir::unwrapRefType(type).dyn_cast<mlir::IntegerType>()) if (auto intType =
mlir::dyn_cast<mlir::IntegerType>(fir::unwrapRefType(type)))
integerKind = intType.getWidth() / 8; integerKind = intType.getWidth() / 8;
mlir::Value kind = builder.createIntegerConstant(loc, kindTy, integerKind); mlir::Value kind = builder.createIntegerConstant(loc, kindTy, integerKind);
mlir::Value res = mlir::Value res =

View File

@ -32,7 +32,8 @@ void fir::runtime::genRaggedArrayAllocate(mlir::Location loc,
// Position of the bufferPointer in the header struct. // Position of the bufferPointer in the header struct.
auto one = builder.createIntegerConstant(loc, i32Ty, 1); auto one = builder.createIntegerConstant(loc, i32Ty, 1);
auto eleTy = fir::unwrapSequenceType(fir::unwrapRefType(header.getType())); auto eleTy = fir::unwrapSequenceType(fir::unwrapRefType(header.getType()));
auto ptrTy = builder.getRefType(eleTy.cast<mlir::TupleType>().getType(1)); auto ptrTy =
builder.getRefType(mlir::cast<mlir::TupleType>(eleTy).getType(1));
auto ptr = builder.create<fir::CoordinateOp>(loc, ptrTy, header, one); auto ptr = builder.create<fir::CoordinateOp>(loc, ptrTy, header, one);
auto heap = builder.create<fir::LoadOp>(loc, ptr); auto heap = builder.create<fir::LoadOp>(loc, ptr);
auto cmp = builder.genIsNullAddr(loc, heap); auto cmp = builder.genIsNullAddr(loc, heap);

View File

@ -666,7 +666,7 @@ void fir::runtime::genMaxloc(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
fir::factory::CharacterExprHelper charHelper{builder, loc}; fir::factory::CharacterExprHelper charHelper{builder, loc};
if (eleTy.isF32()) if (eleTy.isF32())
func = fir::runtime::getRuntimeFunc<mkRTKey(MaxlocReal4)>(loc, builder); func = fir::runtime::getRuntimeFunc<mkRTKey(MaxlocReal4)>(loc, builder);
@ -713,7 +713,7 @@ mlir::Value fir::runtime::genMaxval(fir::FirOpBuilder &builder,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
if (eleTy.isF32()) if (eleTy.isF32())
@ -781,7 +781,7 @@ void fir::runtime::genMinloc(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
fir::factory::CharacterExprHelper charHelper{builder, loc}; fir::factory::CharacterExprHelper charHelper{builder, loc};
if (eleTy.isF32()) if (eleTy.isF32())
func = fir::runtime::getRuntimeFunc<mkRTKey(MinlocReal4)>(loc, builder); func = fir::runtime::getRuntimeFunc<mkRTKey(MinlocReal4)>(loc, builder);
@ -853,7 +853,7 @@ mlir::Value fir::runtime::genMinval(fir::FirOpBuilder &builder,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
if (eleTy.isF32()) if (eleTy.isF32())
@ -895,7 +895,7 @@ void fir::runtime::genNorm2Dim(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
if (eleTy.isF128()) if (eleTy.isF128())
func = fir::runtime::getRuntimeFunc<ForcedNorm2DimReal16>(loc, builder); func = fir::runtime::getRuntimeFunc<ForcedNorm2DimReal16>(loc, builder);
else else
@ -917,7 +917,7 @@ mlir::Value fir::runtime::genNorm2(fir::FirOpBuilder &builder,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
if (eleTy.isF32()) if (eleTy.isF32())
@ -968,7 +968,7 @@ mlir::Value fir::runtime::genProduct(fir::FirOpBuilder &builder,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
if (eleTy.isF32()) if (eleTy.isF32())
@ -1069,7 +1069,7 @@ mlir::Value fir::runtime::genDotProduct(fir::FirOpBuilder &builder,
else if (eleTy.isInteger(builder.getKindMap().getIntegerBitsize(16))) else if (eleTy.isInteger(builder.getKindMap().getIntegerBitsize(16)))
func = func =
fir::runtime::getRuntimeFunc<ForcedDotProductInteger16>(loc, builder); fir::runtime::getRuntimeFunc<ForcedDotProductInteger16>(loc, builder);
else if (eleTy.isa<fir::LogicalType>()) else if (mlir::isa<fir::LogicalType>(eleTy))
func = func =
fir::runtime::getRuntimeFunc<mkRTKey(DotProductLogical)>(loc, builder); fir::runtime::getRuntimeFunc<mkRTKey(DotProductLogical)>(loc, builder);
else else
@ -1111,7 +1111,7 @@ mlir::Value fir::runtime::genSum(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::func::FuncOp func; mlir::func::FuncOp func;
auto ty = arrayBox.getType(); auto ty = arrayBox.getType();
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0);
if (eleTy.isF32()) if (eleTy.isF32())
@ -1173,7 +1173,7 @@ mlir::Value fir::runtime::genSum(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::func::FuncOp func; \ mlir::func::FuncOp func; \
auto ty = arrayBox.getType(); \ auto ty = arrayBox.getType(); \
auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); \ auto arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty); \
auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); \ auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy(); \
auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); \ auto dim = builder.createIntegerConstant(loc, builder.getIndexType(), 0); \
\ \
if (eleTy.isInteger(builder.getKindMap().getIntegerBitsize(1))) \ if (eleTy.isInteger(builder.getKindMap().getIntegerBitsize(1))) \

View File

@ -51,9 +51,9 @@ public:
/// not at all depending on the implementation target's characteristics and /// not at all depending on the implementation target's characteristics and
/// preference. /// preference.
bool needsConversion(mlir::Type ty) { bool needsConversion(mlir::Type ty) {
if (ty.isa<BoxProcType>()) if (mlir::isa<BoxProcType>(ty))
return true; return true;
if (auto funcTy = ty.dyn_cast<mlir::FunctionType>()) { if (auto funcTy = mlir::dyn_cast<mlir::FunctionType>(ty)) {
for (auto t : funcTy.getInputs()) for (auto t : funcTy.getInputs())
if (needsConversion(t)) if (needsConversion(t))
return true; return true;
@ -62,13 +62,13 @@ public:
return true; return true;
return false; return false;
} }
if (auto tupleTy = ty.dyn_cast<mlir::TupleType>()) { if (auto tupleTy = mlir::dyn_cast<mlir::TupleType>(ty)) {
for (auto t : tupleTy.getTypes()) for (auto t : tupleTy.getTypes())
if (needsConversion(t)) if (needsConversion(t))
return true; return true;
return false; return false;
} }
if (auto recTy = ty.dyn_cast<RecordType>()) { if (auto recTy = mlir::dyn_cast<RecordType>(ty)) {
auto visited = visitedTypes.find(ty); auto visited = visitedTypes.find(ty);
if (visited != visitedTypes.end()) if (visited != visitedTypes.end())
return visited->second; return visited->second;
@ -97,11 +97,11 @@ public:
visitedTypes.find(ty)->second = result; visitedTypes.find(ty)->second = result;
return result; return result;
} }
if (auto boxTy = ty.dyn_cast<BaseBoxType>()) if (auto boxTy = mlir::dyn_cast<BaseBoxType>(ty))
return needsConversion(boxTy.getEleTy()); return needsConversion(boxTy.getEleTy());
if (isa_ref_type(ty)) if (isa_ref_type(ty))
return needsConversion(unwrapRefType(ty)); return needsConversion(unwrapRefType(ty));
if (auto t = ty.dyn_cast<SequenceType>()) if (auto t = mlir::dyn_cast<SequenceType>(ty))
return needsConversion(unwrapSequenceType(ty)); return needsConversion(unwrapSequenceType(ty));
return false; return false;
} }
@ -246,7 +246,7 @@ public:
if (typeConverter.needsConversion(ty)) { if (typeConverter.needsConversion(ty)) {
rewriter.startOpModification(func); rewriter.startOpModification(func);
auto toTy = auto toTy =
typeConverter.convertType(ty).cast<mlir::FunctionType>(); mlir::cast<mlir::FunctionType>(typeConverter.convertType(ty));
if (!func.empty()) if (!func.empty())
for (auto e : llvm::enumerate(toTy.getInputs())) { for (auto e : llvm::enumerate(toTy.getInputs())) {
unsigned i = e.index(); unsigned i = e.index();
@ -263,7 +263,7 @@ public:
// Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk // Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk
// as required. // as required.
mlir::Type toTy = typeConverter.convertType( mlir::Type toTy = typeConverter.convertType(
embox.getType().cast<BoxProcType>().getEleTy()); mlir::cast<BoxProcType>(embox.getType()).getEleTy());
rewriter.setInsertionPoint(embox); rewriter.setInsertionPoint(embox);
if (embox.getHost()) { if (embox.getHost()) {
// Create the thunk. // Create the thunk.

View File

@ -41,24 +41,24 @@ unsigned fir::cg::XEmboxOp::getOutRank() {
} }
unsigned fir::cg::XReboxOp::getOutRank() { unsigned fir::cg::XReboxOp::getOutRank() {
if (auto seqTy = if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(
fir::dyn_cast_ptrOrBoxEleTy(getType()).dyn_cast<fir::SequenceType>()) fir::dyn_cast_ptrOrBoxEleTy(getType())))
return seqTy.getDimension(); return seqTy.getDimension();
return 0; return 0;
} }
unsigned fir::cg::XReboxOp::getRank() { unsigned fir::cg::XReboxOp::getRank() {
if (auto seqTy = fir::dyn_cast_ptrOrBoxEleTy(getBox().getType()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(
.dyn_cast<fir::SequenceType>()) fir::dyn_cast_ptrOrBoxEleTy(getBox().getType())))
return seqTy.getDimension(); return seqTy.getDimension();
return 0; return 0;
} }
unsigned fir::cg::XArrayCoorOp::getRank() { unsigned fir::cg::XArrayCoorOp::getRank() {
auto memrefTy = getMemref().getType(); auto memrefTy = getMemref().getType();
if (memrefTy.isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(memrefTy))
if (auto seqty = if (auto seqty = mlir::dyn_cast<fir::SequenceType>(
fir::dyn_cast_ptrOrBoxEleTy(memrefTy).dyn_cast<fir::SequenceType>()) fir::dyn_cast_ptrOrBoxEleTy(memrefTy)))
return seqty.getDimension(); return seqty.getDimension();
return getShape().size(); return getShape().size();
} }

View File

@ -101,7 +101,7 @@ static int64_t getConstantIntValue(mlir::Value val) {
} }
static unsigned getTypeDescFieldId(mlir::Type ty) { static unsigned getTypeDescFieldId(mlir::Type ty) {
auto isArray = fir::dyn_cast_ptrOrBoxEleTy(ty).isa<fir::SequenceType>(); auto isArray = mlir::isa<fir::SequenceType>(fir::dyn_cast_ptrOrBoxEleTy(ty));
return isArray ? kOptTypePtrPosInBox : kDimsPosInBox; return isArray ? kOptTypePtrPosInBox : kDimsPosInBox;
} }
static unsigned getLenParamFieldId(mlir::Type ty) { static unsigned getLenParamFieldId(mlir::Type ty) {
@ -147,7 +147,7 @@ genAllocationScaleSize(OP op, mlir::Type ity,
mlir::ConversionPatternRewriter &rewriter) { mlir::ConversionPatternRewriter &rewriter) {
mlir::Location loc = op.getLoc(); mlir::Location loc = op.getLoc();
mlir::Type dataTy = op.getInType(); mlir::Type dataTy = op.getInType();
auto seqTy = dataTy.dyn_cast<fir::SequenceType>(); auto seqTy = mlir::dyn_cast<fir::SequenceType>(dataTy);
fir::SequenceType::Extent constSize = 1; fir::SequenceType::Extent constSize = 1;
if (seqTy) { if (seqTy) {
int constRows = seqTy.getConstantRows(); int constRows = seqTy.getConstantRows();
@ -191,13 +191,13 @@ struct AllocaOpConversion : public fir::FIROpConversion<fir::AllocaOp> {
for (; i < end; ++i) for (; i < end; ++i)
lenParams.push_back(operands[i]); lenParams.push_back(operands[i]);
mlir::Type scalarType = fir::unwrapSequenceType(alloc.getInType()); mlir::Type scalarType = fir::unwrapSequenceType(alloc.getInType());
if (auto chrTy = scalarType.dyn_cast<fir::CharacterType>()) { if (auto chrTy = mlir::dyn_cast<fir::CharacterType>(scalarType)) {
fir::CharacterType rawCharTy = fir::CharacterType::getUnknownLen( fir::CharacterType rawCharTy = fir::CharacterType::getUnknownLen(
chrTy.getContext(), chrTy.getFKind()); chrTy.getContext(), chrTy.getFKind());
llvmObjectType = convertType(rawCharTy); llvmObjectType = convertType(rawCharTy);
assert(end == 1); assert(end == 1);
size = integerCast(loc, rewriter, ity, lenParams[0]); size = integerCast(loc, rewriter, ity, lenParams[0]);
} else if (auto recTy = scalarType.dyn_cast<fir::RecordType>()) { } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(scalarType)) {
mlir::LLVM::LLVMFuncOp memSizeFn = mlir::LLVM::LLVMFuncOp memSizeFn =
getDependentTypeMemSizeFn(recTy, alloc, rewriter); getDependentTypeMemSizeFn(recTy, alloc, rewriter);
if (!memSizeFn) if (!memSizeFn)
@ -265,7 +265,8 @@ struct BoxAddrOpConversion : public fir::FIROpConversion<fir::BoxAddrOp> {
mlir::ConversionPatternRewriter &rewriter) const override { mlir::ConversionPatternRewriter &rewriter) const override {
mlir::Value a = adaptor.getOperands()[0]; mlir::Value a = adaptor.getOperands()[0];
auto loc = boxaddr.getLoc(); auto loc = boxaddr.getLoc();
if (auto argty = boxaddr.getVal().getType().dyn_cast<fir::BaseBoxType>()) { if (auto argty =
mlir::dyn_cast<fir::BaseBoxType>(boxaddr.getVal().getType())) {
TypePair boxTyPair = getBoxTypePair(argty); TypePair boxTyPair = getBoxTypePair(argty);
rewriter.replaceOp(boxaddr, rewriter.replaceOp(boxaddr,
getBaseAddrFromBox(loc, boxTyPair, a, rewriter)); getBaseAddrFromBox(loc, boxTyPair, a, rewriter));
@ -476,24 +477,25 @@ struct StringLitOpConversion : public fir::FIROpConversion<fir::StringLitOp> {
mlir::ConversionPatternRewriter &rewriter) const override { mlir::ConversionPatternRewriter &rewriter) const override {
auto ty = convertType(constop.getType()); auto ty = convertType(constop.getType());
auto attr = constop.getValue(); auto attr = constop.getValue();
if (attr.isa<mlir::StringAttr>()) { if (mlir::isa<mlir::StringAttr>(attr)) {
rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(constop, ty, attr); rewriter.replaceOpWithNewOp<mlir::LLVM::ConstantOp>(constop, ty, attr);
return mlir::success(); return mlir::success();
} }
auto charTy = constop.getType().cast<fir::CharacterType>(); auto charTy = mlir::cast<fir::CharacterType>(constop.getType());
unsigned bits = lowerTy().characterBitsize(charTy); unsigned bits = lowerTy().characterBitsize(charTy);
mlir::Type intTy = rewriter.getIntegerType(bits); mlir::Type intTy = rewriter.getIntegerType(bits);
mlir::Location loc = constop.getLoc(); mlir::Location loc = constop.getLoc();
mlir::Value cst = rewriter.create<mlir::LLVM::UndefOp>(loc, ty); mlir::Value cst = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
if (auto arr = attr.dyn_cast<mlir::DenseElementsAttr>()) { if (auto arr = mlir::dyn_cast<mlir::DenseElementsAttr>(attr)) {
cst = rewriter.create<mlir::LLVM::ConstantOp>(loc, ty, arr); cst = rewriter.create<mlir::LLVM::ConstantOp>(loc, ty, arr);
} else if (auto arr = attr.dyn_cast<mlir::ArrayAttr>()) { } else if (auto arr = mlir::dyn_cast<mlir::ArrayAttr>(attr)) {
for (auto a : llvm::enumerate(arr.getValue())) { for (auto a : llvm::enumerate(arr.getValue())) {
// convert each character to a precise bitsize // convert each character to a precise bitsize
auto elemAttr = mlir::IntegerAttr::get( auto elemAttr = mlir::IntegerAttr::get(
intTy, intTy,
a.value().cast<mlir::IntegerAttr>().getValue().zextOrTrunc(bits)); mlir::cast<mlir::IntegerAttr>(a.value()).getValue().zextOrTrunc(
bits));
auto elemCst = auto elemCst =
rewriter.create<mlir::LLVM::ConstantOp>(loc, intTy, elemAttr); rewriter.create<mlir::LLVM::ConstantOp>(loc, intTy, elemAttr);
cst = rewriter.create<mlir::LLVM::InsertValueOp>(loc, cst, elemCst, cst = rewriter.create<mlir::LLVM::InsertValueOp>(loc, cst, elemCst,
@ -528,9 +530,9 @@ struct CallOpConversion : public fir::FIROpConversion<fir::CallOp> {
} // namespace } // namespace
static mlir::Type getComplexEleTy(mlir::Type complex) { static mlir::Type getComplexEleTy(mlir::Type complex) {
if (auto cc = complex.dyn_cast<mlir::ComplexType>()) if (auto cc = mlir::dyn_cast<mlir::ComplexType>(complex))
return cc.getElementType(); return cc.getElementType();
return complex.cast<fir::ComplexType>().getElementType(); return mlir::cast<fir::ComplexType>(complex).getElementType();
} }
namespace { namespace {
@ -599,7 +601,7 @@ struct ConstcOpConversion : public fir::FIROpConversion<fir::ConstcOp> {
} }
inline llvm::APFloat getValue(mlir::Attribute attr) const { inline llvm::APFloat getValue(mlir::Attribute attr) const {
return attr.cast<fir::RealAttr>().getValue(); return mlir::cast<fir::RealAttr>(attr).getValue();
} }
}; };
@ -608,7 +610,7 @@ struct ConvertOpConversion : public fir::FIROpConversion<fir::ConvertOp> {
using FIROpConversion::FIROpConversion; using FIROpConversion::FIROpConversion;
static bool isFloatingPointTy(mlir::Type ty) { static bool isFloatingPointTy(mlir::Type ty) {
return ty.isa<mlir::FloatType>(); return mlir::isa<mlir::FloatType>(ty);
} }
mlir::LogicalResult mlir::LogicalResult
@ -628,7 +630,8 @@ struct ConvertOpConversion : public fir::FIROpConversion<fir::ConvertOp> {
auto loc = convert.getLoc(); auto loc = convert.getLoc();
auto i1Type = mlir::IntegerType::get(convert.getContext(), 1); auto i1Type = mlir::IntegerType::get(convert.getContext(), 1);
if (fromFirTy.isa<fir::LogicalType>() || toFirTy.isa<fir::LogicalType>()) { if (mlir::isa<fir::LogicalType>(fromFirTy) ||
mlir::isa<fir::LogicalType>(toFirTy)) {
// By specification fir::LogicalType value may be any number, // By specification fir::LogicalType value may be any number,
// where non-zero value represents .true. and zero value represents // where non-zero value represents .true. and zero value represents
// .false. // .false.
@ -641,7 +644,8 @@ struct ConvertOpConversion : public fir::FIROpConversion<fir::ConvertOp> {
// Conversion from narrow logical to wide logical may be implemented // Conversion from narrow logical to wide logical may be implemented
// as a zero or sign extension of the input, but it may use value // as a zero or sign extension of the input, but it may use value
// normalization as well. // normalization as well.
if (!fromTy.isa<mlir::IntegerType>() || !toTy.isa<mlir::IntegerType>()) if (!mlir::isa<mlir::IntegerType>(fromTy) ||
!mlir::isa<mlir::IntegerType>(toTy))
return mlir::emitError(loc) return mlir::emitError(loc)
<< "unsupported types for logical conversion: " << fromTy << "unsupported types for logical conversion: " << fromTy
<< " -> " << toTy; << " -> " << toTy;
@ -722,13 +726,13 @@ struct ConvertOpConversion : public fir::FIROpConversion<fir::ConvertOp> {
rewriter.replaceOp(convert, v); rewriter.replaceOp(convert, v);
return mlir::success(); return mlir::success();
} }
if (toTy.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(toTy)) {
rewriter.replaceOpWithNewOp<mlir::LLVM::FPToSIOp>(convert, toTy, op0); rewriter.replaceOpWithNewOp<mlir::LLVM::FPToSIOp>(convert, toTy, op0);
return mlir::success(); return mlir::success();
} }
} else if (fromTy.isa<mlir::IntegerType>()) { } else if (mlir::isa<mlir::IntegerType>(fromTy)) {
// Integer to integer conversion. // Integer to integer conversion.
if (toTy.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(toTy)) {
auto fromBits = mlir::LLVM::getPrimitiveTypeSizeInBits(fromTy); auto fromBits = mlir::LLVM::getPrimitiveTypeSizeInBits(fromTy);
auto toBits = mlir::LLVM::getPrimitiveTypeSizeInBits(toTy); auto toBits = mlir::LLVM::getPrimitiveTypeSizeInBits(toTy);
assert(fromBits != toBits); assert(fromBits != toBits);
@ -749,18 +753,18 @@ struct ConvertOpConversion : public fir::FIROpConversion<fir::ConvertOp> {
return mlir::success(); return mlir::success();
} }
// Integer to pointer conversion. // Integer to pointer conversion.
if (toTy.isa<mlir::LLVM::LLVMPointerType>()) { if (mlir::isa<mlir::LLVM::LLVMPointerType>(toTy)) {
rewriter.replaceOpWithNewOp<mlir::LLVM::IntToPtrOp>(convert, toTy, op0); rewriter.replaceOpWithNewOp<mlir::LLVM::IntToPtrOp>(convert, toTy, op0);
return mlir::success(); return mlir::success();
} }
} else if (fromTy.isa<mlir::LLVM::LLVMPointerType>()) { } else if (mlir::isa<mlir::LLVM::LLVMPointerType>(fromTy)) {
// Pointer to integer conversion. // Pointer to integer conversion.
if (toTy.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(toTy)) {
rewriter.replaceOpWithNewOp<mlir::LLVM::PtrToIntOp>(convert, toTy, op0); rewriter.replaceOpWithNewOp<mlir::LLVM::PtrToIntOp>(convert, toTy, op0);
return mlir::success(); return mlir::success();
} }
// Pointer to pointer conversion. // Pointer to pointer conversion.
if (toTy.isa<mlir::LLVM::LLVMPointerType>()) { if (mlir::isa<mlir::LLVM::LLVMPointerType>(toTy)) {
rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(convert, toTy, op0); rewriter.replaceOpWithNewOp<mlir::LLVM::BitcastOp>(convert, toTy, op0);
return mlir::success(); return mlir::success();
} }
@ -842,11 +846,11 @@ struct EmboxCharOpConversion : public fir::FIROpConversion<fir::EmboxCharOp> {
auto llvmStruct = rewriter.create<mlir::LLVM::UndefOp>(loc, llvmStructTy); auto llvmStruct = rewriter.create<mlir::LLVM::UndefOp>(loc, llvmStructTy);
mlir::Type lenTy = mlir::Type lenTy =
llvmStructTy.cast<mlir::LLVM::LLVMStructType>().getBody()[1]; mlir::cast<mlir::LLVM::LLVMStructType>(llvmStructTy).getBody()[1];
mlir::Value lenAfterCast = integerCast(loc, rewriter, lenTy, charBufferLen); mlir::Value lenAfterCast = integerCast(loc, rewriter, lenTy, charBufferLen);
mlir::Type addrTy = mlir::Type addrTy =
llvmStructTy.cast<mlir::LLVM::LLVMStructType>().getBody()[0]; mlir::cast<mlir::LLVM::LLVMStructType>(llvmStructTy).getBody()[0];
if (addrTy != charBuffer.getType()) if (addrTy != charBuffer.getType())
charBuffer = charBuffer =
rewriter.create<mlir::LLVM::BitcastOp>(loc, addrTy, charBuffer); rewriter.create<mlir::LLVM::BitcastOp>(loc, addrTy, charBuffer);
@ -979,9 +983,10 @@ static mlir::SymbolRefAttr getFree(fir::FreeMemOp op,
static unsigned getDimension(mlir::LLVM::LLVMArrayType ty) { static unsigned getDimension(mlir::LLVM::LLVMArrayType ty) {
unsigned result = 1; unsigned result = 1;
for (auto eleTy = ty.getElementType().dyn_cast<mlir::LLVM::LLVMArrayType>(); for (auto eleTy =
eleTy; mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(ty.getElementType());
eleTy = eleTy.getElementType().dyn_cast<mlir::LLVM::LLVMArrayType>()) eleTy; eleTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(
eleTy.getElementType()))
++result; ++result;
return result; return result;
} }
@ -1052,9 +1057,9 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
static int getCFIAttr(fir::BaseBoxType boxTy) { static int getCFIAttr(fir::BaseBoxType boxTy) {
auto eleTy = boxTy.getEleTy(); auto eleTy = boxTy.getEleTy();
if (eleTy.isa<fir::PointerType>()) if (mlir::isa<fir::PointerType>(eleTy))
return CFI_attribute_pointer; return CFI_attribute_pointer;
if (eleTy.isa<fir::HeapType>()) if (mlir::isa<fir::HeapType>(eleTy))
return CFI_attribute_allocatable; return CFI_attribute_allocatable;
return CFI_attribute_other; return CFI_attribute_other;
} }
@ -1082,27 +1087,29 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
auto i64Ty = mlir::IntegerType::get(rewriter.getContext(), 64); auto i64Ty = mlir::IntegerType::get(rewriter.getContext(), 64);
if (auto eleTy = fir::dyn_cast_ptrEleTy(boxEleTy)) if (auto eleTy = fir::dyn_cast_ptrEleTy(boxEleTy))
boxEleTy = eleTy; boxEleTy = eleTy;
if (auto seqTy = boxEleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(boxEleTy))
return getSizeAndTypeCode(loc, rewriter, seqTy.getEleTy(), lenParams); return getSizeAndTypeCode(loc, rewriter, seqTy.getEleTy(), lenParams);
if (boxEleTy.isa<mlir::NoneType>()) // unlimited polymorphic or assumed type if (mlir::isa<mlir::NoneType>(
boxEleTy)) // unlimited polymorphic or assumed type
return {rewriter.create<mlir::LLVM::ConstantOp>(loc, i64Ty, 0), return {rewriter.create<mlir::LLVM::ConstantOp>(loc, i64Ty, 0),
this->genConstantOffset(loc, rewriter, CFI_type_other)}; this->genConstantOffset(loc, rewriter, CFI_type_other)};
mlir::Value typeCodeVal = this->genConstantOffset( mlir::Value typeCodeVal = this->genConstantOffset(
loc, rewriter, loc, rewriter,
fir::getTypeCode(boxEleTy, this->lowerTy().getKindMap())); fir::getTypeCode(boxEleTy, this->lowerTy().getKindMap()));
if (fir::isa_integer(boxEleTy) || boxEleTy.dyn_cast<fir::LogicalType>() || if (fir::isa_integer(boxEleTy) ||
fir::isa_real(boxEleTy) || fir::isa_complex(boxEleTy)) mlir::dyn_cast<fir::LogicalType>(boxEleTy) || fir::isa_real(boxEleTy) ||
fir::isa_complex(boxEleTy))
return {genTypeStrideInBytes(loc, i64Ty, rewriter, return {genTypeStrideInBytes(loc, i64Ty, rewriter,
this->convertType(boxEleTy)), this->convertType(boxEleTy)),
typeCodeVal}; typeCodeVal};
if (auto charTy = boxEleTy.dyn_cast<fir::CharacterType>()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(boxEleTy))
return {getCharacterByteSize(loc, rewriter, charTy, lenParams), return {getCharacterByteSize(loc, rewriter, charTy, lenParams),
typeCodeVal}; typeCodeVal};
if (fir::isa_ref_type(boxEleTy)) { if (fir::isa_ref_type(boxEleTy)) {
auto ptrTy = ::getLlvmPtrType(rewriter.getContext()); auto ptrTy = ::getLlvmPtrType(rewriter.getContext());
return {genTypeStrideInBytes(loc, i64Ty, rewriter, ptrTy), typeCodeVal}; return {genTypeStrideInBytes(loc, i64Ty, rewriter, ptrTy), typeCodeVal};
} }
if (boxEleTy.isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(boxEleTy))
return {genTypeStrideInBytes(loc, i64Ty, rewriter, return {genTypeStrideInBytes(loc, i64Ty, rewriter,
this->convertType(boxEleTy)), this->convertType(boxEleTy)),
typeCodeVal}; typeCodeVal};
@ -1211,8 +1218,8 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
if (!typeDesc) { if (!typeDesc) {
if (useInputType) { if (useInputType) {
mlir::Type innerType = fir::unwrapInnerType(inputType); mlir::Type innerType = fir::unwrapInnerType(inputType);
if (innerType && innerType.template isa<fir::RecordType>()) { if (innerType && mlir::isa<fir::RecordType>(innerType)) {
auto recTy = innerType.template dyn_cast<fir::RecordType>(); auto recTy = mlir::dyn_cast<fir::RecordType>(innerType);
typeDesc = getTypeDescriptor(mod, rewriter, loc, recTy); typeDesc = getTypeDescriptor(mod, rewriter, loc, recTy);
} else { } else {
// Unlimited polymorphic type descriptor with no record type. Set // Unlimited polymorphic type descriptor with no record type. Set
@ -1250,7 +1257,7 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
mlir::ValueRange lenParams, mlir::Value sourceBox = {}, mlir::ValueRange lenParams, mlir::Value sourceBox = {},
mlir::Type sourceBoxType = {}) const { mlir::Type sourceBoxType = {}) const {
auto loc = box.getLoc(); auto loc = box.getLoc();
auto boxTy = box.getType().template dyn_cast<fir::BaseBoxType>(); auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType());
bool useInputType = fir::isPolymorphicType(boxTy) && bool useInputType = fir::isPolymorphicType(boxTy) &&
!fir::isUnlimitedPolymorphicType(inputType); !fir::isUnlimitedPolymorphicType(inputType);
llvm::SmallVector<mlir::Value> typeparams = lenParams; llvm::SmallVector<mlir::Value> typeparams = lenParams;
@ -1293,8 +1300,8 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
mlir::ValueRange lenParams, mlir::ValueRange lenParams,
mlir::Value typeDesc = {}) const { mlir::Value typeDesc = {}) const {
auto loc = box.getLoc(); auto loc = box.getLoc();
auto boxTy = box.getType().dyn_cast<fir::BaseBoxType>(); auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType());
auto inputBoxTy = box.getBox().getType().dyn_cast<fir::BaseBoxType>(); auto inputBoxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getBox().getType());
auto inputBoxTyPair = this->getBoxTypePair(inputBoxTy); auto inputBoxTyPair = this->getBoxTypePair(inputBoxTy);
llvm::SmallVector<mlir::Value> typeparams = lenParams; llvm::SmallVector<mlir::Value> typeparams = lenParams;
if (!box.getSubstr().empty() && fir::hasDynamicSize(boxTy.getEleTy())) if (!box.getSubstr().empty() && fir::hasDynamicSize(boxTy.getEleTy()))
@ -1343,7 +1350,7 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
mlir::Type resultTy = llvmBaseObjectType; mlir::Type resultTy = llvmBaseObjectType;
// Fortran is column major, llvm GEP is row major: reverse the indices here. // Fortran is column major, llvm GEP is row major: reverse the indices here.
for (mlir::Value interiorIndex : llvm::reverse(cstInteriorIndices)) { for (mlir::Value interiorIndex : llvm::reverse(cstInteriorIndices)) {
auto arrayTy = resultTy.dyn_cast<mlir::LLVM::LLVMArrayType>(); auto arrayTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(resultTy);
if (!arrayTy) if (!arrayTy)
fir::emitFatalError( fir::emitFatalError(
loc, loc,
@ -1355,7 +1362,7 @@ struct EmboxCommonConversion : public fir::FIROpConversion<OP> {
convertSubcomponentIndices(loc, resultTy, componentIndices, &resultTy); convertSubcomponentIndices(loc, resultTy, componentIndices, &resultTy);
gepArgs.append(gepIndices.begin(), gepIndices.end()); gepArgs.append(gepIndices.begin(), gepIndices.end());
if (substringOffset) { if (substringOffset) {
if (auto arrayTy = resultTy.dyn_cast<mlir::LLVM::LLVMArrayType>()) { if (auto arrayTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(resultTy)) {
gepArgs.push_back(*substringOffset); gepArgs.push_back(*substringOffset);
resultTy = arrayTy.getElementType(); resultTy = arrayTy.getElementType();
} else { } else {
@ -1504,18 +1511,18 @@ struct XEmboxOpConversion : public EmboxCommonConversion<fir::cg::XEmboxOp> {
unsigned constRows = 0; unsigned constRows = 0;
mlir::Value ptrOffset = zero; mlir::Value ptrOffset = zero;
mlir::Type memEleTy = fir::dyn_cast_ptrEleTy(xbox.getMemref().getType()); mlir::Type memEleTy = fir::dyn_cast_ptrEleTy(xbox.getMemref().getType());
assert(memEleTy.isa<fir::SequenceType>()); assert(mlir::isa<fir::SequenceType>(memEleTy));
auto seqTy = memEleTy.cast<fir::SequenceType>(); auto seqTy = mlir::cast<fir::SequenceType>(memEleTy);
mlir::Type seqEleTy = seqTy.getEleTy(); mlir::Type seqEleTy = seqTy.getEleTy();
// Adjust the element scaling factor if the element is a dependent type. // Adjust the element scaling factor if the element is a dependent type.
if (fir::hasDynamicSize(seqEleTy)) { if (fir::hasDynamicSize(seqEleTy)) {
if (auto charTy = seqEleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(seqEleTy)) {
// The GEP pointer type decays to llvm.ptr<i[width]>. // The GEP pointer type decays to llvm.ptr<i[width]>.
// The scaling factor is the runtime value of the length. // The scaling factor is the runtime value of the length.
assert(!adaptor.getLenParams().empty()); assert(!adaptor.getLenParams().empty());
prevPtrOff = FIROpConversion::integerCast( prevPtrOff = FIROpConversion::integerCast(
loc, rewriter, i64Ty, adaptor.getLenParams().back()); loc, rewriter, i64Ty, adaptor.getLenParams().back());
} else if (seqEleTy.isa<fir::RecordType>()) { } else if (mlir::isa<fir::RecordType>(seqEleTy)) {
// prevPtrOff = ; // prevPtrOff = ;
TODO(loc, "generate call to calculate size of PDT"); TODO(loc, "generate call to calculate size of PDT");
} else { } else {
@ -1540,7 +1547,7 @@ struct XEmboxOpConversion : public EmboxCommonConversion<fir::cg::XEmboxOp> {
} else if (hasSubstr) { } else if (hasSubstr) {
// We have a substring. The step value needs to be the number of bytes // We have a substring. The step value needs to be the number of bytes
// per CHARACTER element. // per CHARACTER element.
auto charTy = seqEleTy.cast<fir::CharacterType>(); auto charTy = mlir::cast<fir::CharacterType>(seqEleTy);
if (fir::hasDynamicSize(charTy)) { if (fir::hasDynamicSize(charTy)) {
prevDimByteStride = prevDimByteStride =
getCharacterByteSize(loc, rewriter, charTy, adaptor.getLenParams()); getCharacterByteSize(loc, rewriter, charTy, adaptor.getLenParams());
@ -1589,7 +1596,7 @@ struct XEmboxOpConversion : public EmboxCommonConversion<fir::cg::XEmboxOp> {
// Lower bound is normalized to 0 for BIND(C) interoperability. // Lower bound is normalized to 0 for BIND(C) interoperability.
mlir::Value lb = zero; mlir::Value lb = zero;
const bool isaPointerOrAllocatable = const bool isaPointerOrAllocatable =
eleTy.isa<fir::PointerType>() || eleTy.isa<fir::HeapType>(); mlir::isa<fir::PointerType, fir::HeapType>(eleTy);
// Lower bound is defaults to 1 for POINTER, ALLOCATABLE, and // Lower bound is defaults to 1 for POINTER, ALLOCATABLE, and
// denormalized descriptors. // denormalized descriptors.
if (isaPointerOrAllocatable || !normalizedLowerBound(xbox)) if (isaPointerOrAllocatable || !normalizedLowerBound(xbox))
@ -1695,7 +1702,7 @@ struct XReboxOpConversion : public EmboxCommonConversion<fir::cg::XReboxOp> {
// Create new descriptor and fill its non-shape related data. // Create new descriptor and fill its non-shape related data.
llvm::SmallVector<mlir::Value, 2> lenParams; llvm::SmallVector<mlir::Value, 2> lenParams;
mlir::Type inputEleTy = getInputEleTy(rebox); mlir::Type inputEleTy = getInputEleTy(rebox);
if (auto charTy = inputEleTy.dyn_cast<fir::CharacterType>()) { if (auto charTy = mlir::dyn_cast<fir::CharacterType>(inputEleTy)) {
if (charTy.hasConstantLen()) { if (charTy.hasConstantLen()) {
mlir::Value len = mlir::Value len =
genConstantIndex(loc, idxTy, rewriter, charTy.getLen()); genConstantIndex(loc, idxTy, rewriter, charTy.getLen());
@ -1712,15 +1719,15 @@ struct XReboxOpConversion : public EmboxCommonConversion<fir::cg::XReboxOp> {
} }
lenParams.emplace_back(len); lenParams.emplace_back(len);
} }
} else if (auto recTy = inputEleTy.dyn_cast<fir::RecordType>()) { } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(inputEleTy)) {
if (recTy.getNumLenParams() != 0) if (recTy.getNumLenParams() != 0)
TODO(loc, "reboxing descriptor of derived type with length parameters"); TODO(loc, "reboxing descriptor of derived type with length parameters");
} }
// Rebox on polymorphic entities needs to carry over the dynamic type. // Rebox on polymorphic entities needs to carry over the dynamic type.
mlir::Value typeDescAddr; mlir::Value typeDescAddr;
if (inputBoxTyPair.fir.isa<fir::ClassType>() && if (mlir::isa<fir::ClassType>(inputBoxTyPair.fir) &&
rebox.getType().isa<fir::ClassType>()) mlir::isa<fir::ClassType>(rebox.getType()))
typeDescAddr = typeDescAddr =
loadTypeDescAddress(loc, inputBoxTyPair, loweredBox, rewriter); loadTypeDescAddress(loc, inputBoxTyPair, loweredBox, rewriter);
@ -1908,7 +1915,7 @@ private:
/// Return scalar element type of the input box. /// Return scalar element type of the input box.
static mlir::Type getInputEleTy(fir::cg::XReboxOp rebox) { static mlir::Type getInputEleTy(fir::cg::XReboxOp rebox) {
auto ty = fir::dyn_cast_ptrOrBoxEleTy(rebox.getBox().getType()); auto ty = fir::dyn_cast_ptrOrBoxEleTy(rebox.getBox().getType());
if (auto seqTy = ty.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
return seqTy.getEleTy(); return seqTy.getEleTy();
return ty; return ty;
} }
@ -1936,7 +1943,7 @@ struct ValueOpCommon {
assert(ty && "type is null"); assert(ty && "type is null");
const auto end = indices.size(); const auto end = indices.size();
for (std::remove_const_t<decltype(end)> i = 0; i < end; ++i) { for (std::remove_const_t<decltype(end)> i = 0; i < end; ++i) {
if (auto seq = ty.dyn_cast<mlir::LLVM::LLVMArrayType>()) { if (auto seq = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(ty)) {
const auto dim = getDimension(seq); const auto dim = getDimension(seq);
if (dim > 1) { if (dim > 1) {
auto ub = std::min(i + dim, end); auto ub = std::min(i + dim, end);
@ -1944,7 +1951,7 @@ struct ValueOpCommon {
i += dim - 1; i += dim - 1;
} }
ty = getArrayElementType(seq); ty = getArrayElementType(seq);
} else if (auto st = ty.dyn_cast<mlir::LLVM::LLVMStructType>()) { } else if (auto st = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(ty)) {
ty = st.getBody()[indices[i]]; ty = st.getBody()[indices[i]];
} else { } else {
llvm_unreachable("index into invalid type"); llvm_unreachable("index into invalid type");
@ -1963,7 +1970,7 @@ struct ValueOpCommon {
auto fieldName = i->cast<mlir::StringAttr>().getValue(); auto fieldName = i->cast<mlir::StringAttr>().getValue();
++i; ++i;
auto ty = i->cast<mlir::TypeAttr>().getValue(); auto ty = i->cast<mlir::TypeAttr>().getValue();
auto index = ty.cast<fir::RecordType>().getFieldIndex(fieldName); auto index = mlir::cast<fir::RecordType>(ty).getFieldIndex(fieldName);
indices.push_back(index); indices.push_back(index);
} }
} }
@ -1973,7 +1980,7 @@ struct ValueOpCommon {
private: private:
static mlir::Type getArrayElementType(mlir::LLVM::LLVMArrayType ty) { static mlir::Type getArrayElementType(mlir::LLVM::LLVMArrayType ty) {
auto eleTy = ty.getElementType(); auto eleTy = ty.getElementType();
while (auto arrTy = eleTy.dyn_cast<mlir::LLVM::LLVMArrayType>()) while (auto arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(eleTy))
eleTy = arrTy.getElementType(); eleTy = arrTy.getElementType();
return eleTy; return eleTy;
} }
@ -2041,7 +2048,7 @@ struct InsertOnRangeOpConversion
auto type = adaptor.getOperands()[0].getType(); auto type = adaptor.getOperands()[0].getType();
// Iteratively extract the array dimensions from the type. // Iteratively extract the array dimensions from the type.
while (auto t = type.dyn_cast<mlir::LLVM::LLVMArrayType>()) { while (auto t = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(type)) {
dims.push_back(t.getNumElements()); dims.push_back(t.getNumElements());
type = t.getElementType(); type = t.getElementType();
} }
@ -2107,7 +2114,8 @@ struct XArrayCoorOpConversion
mlir::Value offset = genConstantIndex(loc, idxTy, rewriter, 0); mlir::Value offset = genConstantIndex(loc, idxTy, rewriter, 0);
const bool isShifted = !coor.getShift().empty(); const bool isShifted = !coor.getShift().empty();
const bool isSliced = !coor.getSlice().empty(); const bool isSliced = !coor.getSlice().empty();
const bool baseIsBoxed = coor.getMemref().getType().isa<fir::BaseBoxType>(); const bool baseIsBoxed =
mlir::isa<fir::BaseBoxType>(coor.getMemref().getType());
TypePair baseBoxTyPair = TypePair baseBoxTyPair =
baseIsBoxed ? getBoxTypePair(coor.getMemref().getType()) : TypePair{}; baseIsBoxed ? getBoxTypePair(coor.getMemref().getType()) : TypePair{};
mlir::LLVM::IntegerOverflowFlags nsw = mlir::LLVM::IntegerOverflowFlags nsw =
@ -2185,7 +2193,8 @@ struct XArrayCoorOpConversion
// components. // components.
mlir::Type elementType = mlir::Type elementType =
getLlvmObjectTypeFromBoxType(coor.getMemref().getType()); getLlvmObjectTypeFromBoxType(coor.getMemref().getType());
while (auto arrayTy = elementType.dyn_cast<mlir::LLVM::LLVMArrayType>()) while (auto arrayTy =
mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(elementType))
elementType = arrayTy.getElementType(); elementType = arrayTy.getElementType();
args.clear(); args.clear();
args.push_back(0); args.push_back(0);
@ -2275,11 +2284,12 @@ struct CoordinateOpConversion
} }
// Boxed type - get the base pointer from the box // Boxed type - get the base pointer from the box
if (baseObjectTy.dyn_cast<fir::BaseBoxType>()) if (mlir::dyn_cast<fir::BaseBoxType>(baseObjectTy))
return doRewriteBox(coor, operands, loc, rewriter); return doRewriteBox(coor, operands, loc, rewriter);
// Reference, pointer or a heap type // Reference, pointer or a heap type
if (baseObjectTy.isa<fir::ReferenceType, fir::PointerType, fir::HeapType>()) if (mlir::isa<fir::ReferenceType, fir::PointerType, fir::HeapType>(
baseObjectTy))
return doRewriteRefOrPtr(coor, llvmObjectTy, operands, loc, rewriter); return doRewriteRefOrPtr(coor, llvmObjectTy, operands, loc, rewriter);
return rewriter.notifyMatchFailure( return rewriter.notifyMatchFailure(
@ -2295,7 +2305,7 @@ struct CoordinateOpConversion
} }
static bool hasSubDimensions(mlir::Type type) { static bool hasSubDimensions(mlir::Type type) {
return type.isa<fir::SequenceType, fir::RecordType, mlir::TupleType>(); return mlir::isa<fir::SequenceType, fir::RecordType, mlir::TupleType>(type);
} }
/// Check whether this form of `!fir.coordinate_of` is supported. These /// Check whether this form of `!fir.coordinate_of` is supported. These
@ -2310,14 +2320,14 @@ struct CoordinateOpConversion
bool ptrEle = false; bool ptrEle = false;
for (; i < numOfCoors; ++i) { for (; i < numOfCoors; ++i) {
mlir::Value nxtOpnd = coors[i]; mlir::Value nxtOpnd = coors[i];
if (auto arrTy = type.dyn_cast<fir::SequenceType>()) { if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(type)) {
subEle = true; subEle = true;
i += arrTy.getDimension() - 1; i += arrTy.getDimension() - 1;
type = arrTy.getEleTy(); type = arrTy.getEleTy();
} else if (auto recTy = type.dyn_cast<fir::RecordType>()) { } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(type)) {
subEle = true; subEle = true;
type = recTy.getType(getFieldNumber(recTy, nxtOpnd)); type = recTy.getType(getFieldNumber(recTy, nxtOpnd));
} else if (auto tupTy = type.dyn_cast<mlir::TupleType>()) { } else if (auto tupTy = mlir::dyn_cast<mlir::TupleType>(type)) {
subEle = true; subEle = true;
type = tupTy.getType(getConstantIntValue(nxtOpnd)); type = tupTy.getType(getConstantIntValue(nxtOpnd));
} else { } else {
@ -2335,14 +2345,14 @@ struct CoordinateOpConversion
static bool arraysHaveKnownShape(mlir::Type type, mlir::ValueRange coors) { static bool arraysHaveKnownShape(mlir::Type type, mlir::ValueRange coors) {
for (std::size_t i = 0, sz = coors.size(); i < sz; ++i) { for (std::size_t i = 0, sz = coors.size(); i < sz; ++i) {
mlir::Value nxtOpnd = coors[i]; mlir::Value nxtOpnd = coors[i];
if (auto arrTy = type.dyn_cast<fir::SequenceType>()) { if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(type)) {
if (fir::sequenceWithNonConstantShape(arrTy)) if (fir::sequenceWithNonConstantShape(arrTy))
return false; return false;
i += arrTy.getDimension() - 1; i += arrTy.getDimension() - 1;
type = arrTy.getEleTy(); type = arrTy.getEleTy();
} else if (auto strTy = type.dyn_cast<fir::RecordType>()) { } else if (auto strTy = mlir::dyn_cast<fir::RecordType>(type)) {
type = strTy.getType(getFieldNumber(strTy, nxtOpnd)); type = strTy.getType(getFieldNumber(strTy, nxtOpnd));
} else if (auto strTy = type.dyn_cast<mlir::TupleType>()) { } else if (auto strTy = mlir::dyn_cast<mlir::TupleType>(type)) {
type = strTy.getType(getConstantIntValue(nxtOpnd)); type = strTy.getType(getConstantIntValue(nxtOpnd));
} else { } else {
return true; return true;
@ -2357,7 +2367,8 @@ private:
mlir::Location loc, mlir::Location loc,
mlir::ConversionPatternRewriter &rewriter) const { mlir::ConversionPatternRewriter &rewriter) const {
mlir::Type boxObjTy = coor.getBaseType(); mlir::Type boxObjTy = coor.getBaseType();
assert(boxObjTy.dyn_cast<fir::BaseBoxType>() && "This is not a `fir.box`"); assert(mlir::dyn_cast<fir::BaseBoxType>(boxObjTy) &&
"This is not a `fir.box`");
TypePair boxTyPair = getBoxTypePair(boxObjTy); TypePair boxTyPair = getBoxTypePair(boxObjTy);
mlir::Value boxBaseAddr = operands[0]; mlir::Value boxBaseAddr = operands[0];
@ -2399,7 +2410,7 @@ private:
mlir::LLVM::IntegerOverflowFlags::nsw; mlir::LLVM::IntegerOverflowFlags::nsw;
for (unsigned i = 1, last = operands.size(); i < last; ++i) { for (unsigned i = 1, last = operands.size(); i < last; ++i) {
if (auto arrTy = cpnTy.dyn_cast<fir::SequenceType>()) { if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(cpnTy)) {
if (i != 1) if (i != 1)
TODO(loc, "fir.array nested inside other array and/or derived type"); TODO(loc, "fir.array nested inside other array and/or derived type");
// Applies byte strides from the box. Ignore lower bound from box // Applies byte strides from the box. Ignore lower bound from box
@ -2421,7 +2432,7 @@ private:
llvm::ArrayRef<mlir::LLVM::GEPArg>{off}); llvm::ArrayRef<mlir::LLVM::GEPArg>{off});
i += arrTy.getDimension() - 1; i += arrTy.getDimension() - 1;
cpnTy = arrTy.getEleTy(); cpnTy = arrTy.getEleTy();
} else if (auto recTy = cpnTy.dyn_cast<fir::RecordType>()) { } else if (auto recTy = mlir::dyn_cast<fir::RecordType>(cpnTy)) {
mlir::Value nxtOpnd = operands[i]; mlir::Value nxtOpnd = operands[i];
cpnTy = recTy.getType(getFieldNumber(recTy, nxtOpnd)); cpnTy = recTy.getType(getFieldNumber(recTy, nxtOpnd));
auto llvmRecTy = lowerTy().convertType(recTy); auto llvmRecTy = lowerTy().convertType(recTy);
@ -2456,7 +2467,7 @@ private:
// If only the column is `?`, then we can simply place the column value in // If only the column is `?`, then we can simply place the column value in
// the 0-th GEP position. // the 0-th GEP position.
if (auto arrTy = cpnTy.dyn_cast<fir::SequenceType>()) { if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(cpnTy)) {
if (!hasKnownShape) { if (!hasKnownShape) {
const unsigned sz = arrTy.getDimension(); const unsigned sz = arrTy.getDimension();
if (arraysHaveKnownShape(arrTy.getEleTy(), if (arraysHaveKnownShape(arrTy.getEleTy(),
@ -2500,29 +2511,29 @@ private:
dims = dimsLeft - 1; dims = dimsLeft - 1;
continue; continue;
} }
cpnTy = cpnTy.cast<fir::SequenceType>().getEleTy(); cpnTy = mlir::cast<fir::SequenceType>(cpnTy).getEleTy();
// append array range in reverse (FIR arrays are column-major) // append array range in reverse (FIR arrays are column-major)
offs.append(arrIdx.rbegin(), arrIdx.rend()); offs.append(arrIdx.rbegin(), arrIdx.rend());
arrIdx.clear(); arrIdx.clear();
dims.reset(); dims.reset();
continue; continue;
} }
if (auto arrTy = cpnTy.dyn_cast<fir::SequenceType>()) { if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(cpnTy)) {
int d = arrTy.getDimension() - 1; int d = arrTy.getDimension() - 1;
if (d > 0) { if (d > 0) {
dims = d; dims = d;
arrIdx.push_back(nxtOpnd); arrIdx.push_back(nxtOpnd);
continue; continue;
} }
cpnTy = cpnTy.cast<fir::SequenceType>().getEleTy(); cpnTy = mlir::cast<fir::SequenceType>(cpnTy).getEleTy();
offs.push_back(nxtOpnd); offs.push_back(nxtOpnd);
continue; continue;
} }
// check if the i-th coordinate relates to a field // check if the i-th coordinate relates to a field
if (auto recTy = cpnTy.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(cpnTy))
cpnTy = recTy.getType(getFieldNumber(recTy, nxtOpnd)); cpnTy = recTy.getType(getFieldNumber(recTy, nxtOpnd));
else if (auto tupTy = cpnTy.dyn_cast<mlir::TupleType>()) else if (auto tupTy = mlir::dyn_cast<mlir::TupleType>(cpnTy))
cpnTy = tupTy.getType(getConstantIntValue(nxtOpnd)); cpnTy = tupTy.getType(getConstantIntValue(nxtOpnd));
else else
cpnTy = nullptr; cpnTy = nullptr;
@ -2551,7 +2562,7 @@ struct FieldIndexOpConversion : public fir::FIROpConversion<fir::FieldIndexOp> {
mlir::LogicalResult mlir::LogicalResult
matchAndRewrite(fir::FieldIndexOp field, OpAdaptor adaptor, matchAndRewrite(fir::FieldIndexOp field, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override { mlir::ConversionPatternRewriter &rewriter) const override {
auto recTy = field.getOnType().cast<fir::RecordType>(); auto recTy = mlir::cast<fir::RecordType>(field.getOnType());
unsigned index = recTy.getFieldIndex(field.getFieldId()); unsigned index = recTy.getFieldIndex(field.getFieldId());
if (!fir::hasDynamicSize(recTy)) { if (!fir::hasDynamicSize(recTy)) {
@ -2604,8 +2615,8 @@ struct TypeDescOpConversion : public fir::FIROpConversion<fir::TypeDescOp> {
matchAndRewrite(fir::TypeDescOp typeDescOp, OpAdaptor adaptor, matchAndRewrite(fir::TypeDescOp typeDescOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override { mlir::ConversionPatternRewriter &rewriter) const override {
mlir::Type inTy = typeDescOp.getInType(); mlir::Type inTy = typeDescOp.getInType();
assert(inTy.isa<fir::RecordType>() && "expecting fir.type"); assert(mlir::isa<fir::RecordType>(inTy) && "expecting fir.type");
auto recordType = inTy.dyn_cast<fir::RecordType>(); auto recordType = mlir::dyn_cast<fir::RecordType>(inTy);
auto module = typeDescOp.getOperation()->getParentOfType<mlir::ModuleOp>(); auto module = typeDescOp.getOperation()->getParentOfType<mlir::ModuleOp>();
std::string typeDescName = std::string typeDescName =
fir::NameUniquer::getTypeDescriptorName(recordType.getName()); fir::NameUniquer::getTypeDescriptorName(recordType.getName());
@ -2732,7 +2743,7 @@ struct GlobalOpConversion : public fir::FIROpConversion<fir::GlobalOp> {
mlir::Type vecType = mlir::VectorType::get( mlir::Type vecType = mlir::VectorType::get(
insertOp.getType().getShape(), constant.getType()); insertOp.getType().getShape(), constant.getType());
auto denseAttr = mlir::DenseElementsAttr::get( auto denseAttr = mlir::DenseElementsAttr::get(
vecType.cast<mlir::ShapedType>(), constant.getValue()); mlir::cast<mlir::ShapedType>(vecType), constant.getValue());
rewriter.setInsertionPointAfter(insertOp); rewriter.setInsertionPointAfter(insertOp);
rewriter.replaceOpWithNewOp<mlir::arith::ConstantOp>( rewriter.replaceOpWithNewOp<mlir::arith::ConstantOp>(
insertOp, seqTyAttr, denseAttr); insertOp, seqTyAttr, denseAttr);
@ -2808,7 +2819,7 @@ struct LoadOpConversion : public fir::FIROpConversion<fir::LoadOp> {
matchAndRewrite(fir::LoadOp load, OpAdaptor adaptor, matchAndRewrite(fir::LoadOp load, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const override { mlir::ConversionPatternRewriter &rewriter) const override {
mlir::Type llvmLoadTy = convertObjectType(load.getType()); mlir::Type llvmLoadTy = convertObjectType(load.getType());
if (auto boxTy = load.getType().dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(load.getType())) {
// fir.box is a special case because it is considered as an ssa values in // fir.box is a special case because it is considered as an ssa values in
// fir, but it is lowered as a pointer to a descriptor. So // fir, but it is lowered as a pointer to a descriptor. So
// fir.ref<fir.box> and fir.box end up being the same llvm types and // fir.ref<fir.box> and fir.box end up being the same llvm types and
@ -2921,7 +2932,7 @@ struct SelectCaseOpConversion : public fir::FIROpConversion<fir::SelectCaseOp> {
llvm::ArrayRef<mlir::Attribute> cases = caseOp.getCases().getValue(); llvm::ArrayRef<mlir::Attribute> cases = caseOp.getCases().getValue();
// Type can be CHARACTER, INTEGER, or LOGICAL (C1145) // Type can be CHARACTER, INTEGER, or LOGICAL (C1145)
auto ty = caseOp.getSelector().getType(); auto ty = caseOp.getSelector().getType();
if (ty.isa<fir::CharacterType>()) { if (mlir::isa<fir::CharacterType>(ty)) {
TODO(caseOp.getLoc(), "fir.select_case codegen with character type"); TODO(caseOp.getLoc(), "fir.select_case codegen with character type");
return mlir::failure(); return mlir::failure();
} }
@ -2935,25 +2946,25 @@ struct SelectCaseOpConversion : public fir::FIROpConversion<fir::SelectCaseOp> {
*caseOp.getCompareOperands(adaptor.getOperands(), t); *caseOp.getCompareOperands(adaptor.getOperands(), t);
mlir::Value caseArg = *(cmpOps.value().begin()); mlir::Value caseArg = *(cmpOps.value().begin());
mlir::Attribute attr = cases[t]; mlir::Attribute attr = cases[t];
if (attr.isa<fir::PointIntervalAttr>()) { if (mlir::isa<fir::PointIntervalAttr>(attr)) {
auto cmp = rewriter.create<mlir::LLVM::ICmpOp>( auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
loc, mlir::LLVM::ICmpPredicate::eq, selector, caseArg); loc, mlir::LLVM::ICmpPredicate::eq, selector, caseArg);
genCaseLadderStep(loc, cmp, dest, destOps, rewriter); genCaseLadderStep(loc, cmp, dest, destOps, rewriter);
continue; continue;
} }
if (attr.isa<fir::LowerBoundAttr>()) { if (mlir::isa<fir::LowerBoundAttr>(attr)) {
auto cmp = rewriter.create<mlir::LLVM::ICmpOp>( auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
loc, mlir::LLVM::ICmpPredicate::sle, caseArg, selector); loc, mlir::LLVM::ICmpPredicate::sle, caseArg, selector);
genCaseLadderStep(loc, cmp, dest, destOps, rewriter); genCaseLadderStep(loc, cmp, dest, destOps, rewriter);
continue; continue;
} }
if (attr.isa<fir::UpperBoundAttr>()) { if (mlir::isa<fir::UpperBoundAttr>(attr)) {
auto cmp = rewriter.create<mlir::LLVM::ICmpOp>( auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
loc, mlir::LLVM::ICmpPredicate::sle, selector, caseArg); loc, mlir::LLVM::ICmpPredicate::sle, selector, caseArg);
genCaseLadderStep(loc, cmp, dest, destOps, rewriter); genCaseLadderStep(loc, cmp, dest, destOps, rewriter);
continue; continue;
} }
if (attr.isa<fir::ClosedIntervalAttr>()) { if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
auto cmp = rewriter.create<mlir::LLVM::ICmpOp>( auto cmp = rewriter.create<mlir::LLVM::ICmpOp>(
loc, mlir::LLVM::ICmpPredicate::sle, caseArg, selector); loc, mlir::LLVM::ICmpPredicate::sle, caseArg, selector);
auto *thisBlock = rewriter.getInsertionBlock(); auto *thisBlock = rewriter.getInsertionBlock();
@ -2969,7 +2980,7 @@ struct SelectCaseOpConversion : public fir::FIROpConversion<fir::SelectCaseOp> {
rewriter.setInsertionPointToEnd(newBlock2); rewriter.setInsertionPointToEnd(newBlock2);
continue; continue;
} }
assert(attr.isa<mlir::UnitAttr>()); assert(mlir::isa<mlir::UnitAttr>(attr));
assert((t + 1 == conds) && "unit must be last"); assert((t + 1 == conds) && "unit must be last");
genBrOp(caseOp, dest, destOps, rewriter); genBrOp(caseOp, dest, destOps, rewriter);
} }
@ -2997,7 +3008,7 @@ static void selectMatchAndRewrite(const fir::LLVMTypeConverter &lowering,
mlir::Block *dest = select.getSuccessor(t); mlir::Block *dest = select.getSuccessor(t);
auto destOps = select.getSuccessorOperands(adaptor.getOperands(), t); auto destOps = select.getSuccessorOperands(adaptor.getOperands(), t);
const mlir::Attribute &attr = cases[t]; const mlir::Attribute &attr = cases[t];
if (auto intAttr = attr.template dyn_cast<mlir::IntegerAttr>()) { if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr)) {
destinations.push_back(dest); destinations.push_back(dest);
destinationsOperands.push_back(destOps ? *destOps : mlir::ValueRange{}); destinationsOperands.push_back(destOps ? *destOps : mlir::ValueRange{});
caseValues.push_back(intAttr.getInt()); caseValues.push_back(intAttr.getInt());
@ -3071,7 +3082,7 @@ struct StoreOpConversion : public fir::FIROpConversion<fir::StoreOp> {
mlir::Location loc = store.getLoc(); mlir::Location loc = store.getLoc();
mlir::Type storeTy = store.getValue().getType(); mlir::Type storeTy = store.getValue().getType();
mlir::LLVM::StoreOp newStoreOp; mlir::LLVM::StoreOp newStoreOp;
if (auto boxTy = storeTy.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(storeTy)) {
// fir.box value is actually in memory, load it first before storing it. // fir.box value is actually in memory, load it first before storing it.
mlir::Type llvmBoxTy = lowerTy().convertBoxTypeAsStruct(boxTy); mlir::Type llvmBoxTy = lowerTy().convertBoxTypeAsStruct(boxTy);
auto val = rewriter.create<mlir::LLVM::LoadOp>(loc, llvmBoxTy, auto val = rewriter.create<mlir::LLVM::LoadOp>(loc, llvmBoxTy,
@ -3186,9 +3197,9 @@ struct IsPresentOpConversion : public fir::FIROpConversion<fir::IsPresentOp> {
mlir::Location loc = isPresent.getLoc(); mlir::Location loc = isPresent.getLoc();
auto ptr = adaptor.getOperands()[0]; auto ptr = adaptor.getOperands()[0];
if (isPresent.getVal().getType().isa<fir::BoxCharType>()) { if (mlir::isa<fir::BoxCharType>(isPresent.getVal().getType())) {
[[maybe_unused]] auto structTy = [[maybe_unused]] auto structTy =
ptr.getType().cast<mlir::LLVM::LLVMStructType>(); mlir::cast<mlir::LLVM::LLVMStructType>(ptr.getType());
assert(!structTy.isOpaque() && !structTy.getBody().empty()); assert(!structTy.isOpaque() && !structTy.getBody().empty());
ptr = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, ptr, 0); ptr = rewriter.create<mlir::LLVM::ExtractValueOp>(loc, ptr, 0);
@ -3214,8 +3225,8 @@ struct AbsentOpConversion : public fir::FIROpConversion<fir::AbsentOp> {
mlir::Type ty = convertType(absent.getType()); mlir::Type ty = convertType(absent.getType());
mlir::Location loc = absent.getLoc(); mlir::Location loc = absent.getLoc();
if (absent.getType().isa<fir::BoxCharType>()) { if (mlir::isa<fir::BoxCharType>(absent.getType())) {
auto structTy = ty.cast<mlir::LLVM::LLVMStructType>(); auto structTy = mlir::cast<mlir::LLVM::LLVMStructType>(ty);
assert(!structTy.isOpaque() && !structTy.getBody().empty()); assert(!structTy.isOpaque() && !structTy.getBody().empty());
auto undefStruct = rewriter.create<mlir::LLVM::UndefOp>(loc, ty); auto undefStruct = rewriter.create<mlir::LLVM::UndefOp>(loc, ty);
auto nullField = auto nullField =

View File

@ -20,7 +20,7 @@ static inline mlir::Type getLlvmPtrType(mlir::MLIRContext *context,
} }
static unsigned getTypeDescFieldId(mlir::Type ty) { static unsigned getTypeDescFieldId(mlir::Type ty) {
auto isArray = fir::dyn_cast_ptrOrBoxEleTy(ty).isa<fir::SequenceType>(); auto isArray = mlir::isa<fir::SequenceType>(fir::dyn_cast_ptrOrBoxEleTy(ty));
return isArray ? kOptTypePtrPosInBox : kDimsPosInBox; return isArray ? kOptTypePtrPosInBox : kDimsPosInBox;
} }
@ -37,7 +37,7 @@ ConvertFIRToLLVMPattern::ConvertFIRToLLVMPattern(
// reference. // reference.
mlir::Type mlir::Type
ConvertFIRToLLVMPattern::convertObjectType(mlir::Type firType) const { ConvertFIRToLLVMPattern::convertObjectType(mlir::Type firType) const {
if (auto boxTy = firType.dyn_cast<fir::BaseBoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(firType))
return lowerTy().convertBoxTypeAsStruct(boxTy); return lowerTy().convertBoxTypeAsStruct(boxTy);
return lowerTy().convertType(firType); return lowerTy().convertType(firType);
} }
@ -69,7 +69,7 @@ ConvertFIRToLLVMPattern::integerCast(mlir::Location loc,
auto valTy = val.getType(); auto valTy = val.getType();
// If the value was not yet lowered, lower its type so that it can // If the value was not yet lowered, lower its type so that it can
// be used in getPrimitiveTypeSizeInBits. // be used in getPrimitiveTypeSizeInBits.
if (!valTy.isa<mlir::IntegerType>()) if (!mlir::isa<mlir::IntegerType>(valTy))
valTy = convertType(valTy); valTy = convertType(valTy);
auto toSize = mlir::LLVM::getPrimitiveTypeSizeInBits(ty); auto toSize = mlir::LLVM::getPrimitiveTypeSizeInBits(ty);
auto fromSize = mlir::LLVM::getPrimitiveTypeSizeInBits(valTy); auto fromSize = mlir::LLVM::getPrimitiveTypeSizeInBits(valTy);
@ -91,7 +91,7 @@ ConvertFIRToLLVMPattern::getBoxTypePair(mlir::Type firBoxTy) const {
mlir::Value ConvertFIRToLLVMPattern::getValueFromBox( mlir::Value ConvertFIRToLLVMPattern::getValueFromBox(
mlir::Location loc, TypePair boxTy, mlir::Value box, mlir::Type resultTy, mlir::Location loc, TypePair boxTy, mlir::Value box, mlir::Type resultTy,
mlir::ConversionPatternRewriter &rewriter, int boxValue) const { mlir::ConversionPatternRewriter &rewriter, int boxValue) const {
if (box.getType().isa<mlir::LLVM::LLVMPointerType>()) { if (mlir::isa<mlir::LLVM::LLVMPointerType>(box.getType())) {
auto pty = getLlvmPtrType(resultTy.getContext()); auto pty = getLlvmPtrType(resultTy.getContext());
auto p = rewriter.create<mlir::LLVM::GEPOp>( auto p = rewriter.create<mlir::LLVM::GEPOp>(
loc, pty, boxTy.llvm, box, loc, pty, boxTy.llvm, box,
@ -133,7 +133,7 @@ llvm::SmallVector<mlir::Value, 3> ConvertFIRToLLVMPattern::getDimsFromBox(
mlir::Value ConvertFIRToLLVMPattern::loadDimFieldFromBox( mlir::Value ConvertFIRToLLVMPattern::loadDimFieldFromBox(
mlir::Location loc, TypePair boxTy, mlir::Value box, mlir::Value dim, mlir::Location loc, TypePair boxTy, mlir::Value box, mlir::Value dim,
int off, mlir::Type ty, mlir::ConversionPatternRewriter &rewriter) const { int off, mlir::Type ty, mlir::ConversionPatternRewriter &rewriter) const {
assert(box.getType().isa<mlir::LLVM::LLVMPointerType>() && assert(mlir::isa<mlir::LLVM::LLVMPointerType>(box.getType()) &&
"descriptor inquiry with runtime dim can only be done on descriptor " "descriptor inquiry with runtime dim can only be done on descriptor "
"in memory"); "in memory");
mlir::LLVM::GEPOp p = genGEP(loc, boxTy.llvm, rewriter, box, 0, mlir::LLVM::GEPOp p = genGEP(loc, boxTy.llvm, rewriter, box, 0,
@ -146,7 +146,7 @@ mlir::Value ConvertFIRToLLVMPattern::loadDimFieldFromBox(
mlir::Value ConvertFIRToLLVMPattern::getDimFieldFromBox( mlir::Value ConvertFIRToLLVMPattern::getDimFieldFromBox(
mlir::Location loc, TypePair boxTy, mlir::Value box, int dim, int off, mlir::Location loc, TypePair boxTy, mlir::Value box, int dim, int off,
mlir::Type ty, mlir::ConversionPatternRewriter &rewriter) const { mlir::Type ty, mlir::ConversionPatternRewriter &rewriter) const {
if (box.getType().isa<mlir::LLVM::LLVMPointerType>()) { if (mlir::isa<mlir::LLVM::LLVMPointerType>(box.getType())) {
mlir::LLVM::GEPOp p = genGEP(loc, boxTy.llvm, rewriter, box, 0, mlir::LLVM::GEPOp p = genGEP(loc, boxTy.llvm, rewriter, box, 0,
static_cast<int>(kDimsPosInBox), dim, off); static_cast<int>(kDimsPosInBox), dim, off);
auto loadOp = rewriter.create<mlir::LLVM::LoadOp>(loc, ty, p); auto loadOp = rewriter.create<mlir::LLVM::LoadOp>(loc, ty, p);
@ -184,12 +184,12 @@ mlir::Value ConvertFIRToLLVMPattern::getElementSizeFromBox(
mlir::Type ConvertFIRToLLVMPattern::getBoxEleTy( mlir::Type ConvertFIRToLLVMPattern::getBoxEleTy(
mlir::Type type, llvm::ArrayRef<std::int64_t> indexes) const { mlir::Type type, llvm::ArrayRef<std::int64_t> indexes) const {
for (unsigned i : indexes) { for (unsigned i : indexes) {
if (auto t = type.dyn_cast<mlir::LLVM::LLVMStructType>()) { if (auto t = mlir::dyn_cast<mlir::LLVM::LLVMStructType>(type)) {
assert(!t.isOpaque() && i < t.getBody().size()); assert(!t.isOpaque() && i < t.getBody().size());
type = t.getBody()[i]; type = t.getBody()[i];
} else if (auto t = type.dyn_cast<mlir::LLVM::LLVMArrayType>()) { } else if (auto t = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(type)) {
type = t.getElementType(); type = t.getElementType();
} else if (auto t = type.dyn_cast<mlir::VectorType>()) { } else if (auto t = mlir::dyn_cast<mlir::VectorType>(type)) {
type = t.getElementType(); type = t.getElementType();
} else { } else {
fir::emitFatalError(mlir::UnknownLoc::get(type.getContext()), fir::emitFatalError(mlir::UnknownLoc::get(type.getContext()),

View File

@ -86,10 +86,10 @@ public:
// If the embox does not include a shape, then do not convert it // If the embox does not include a shape, then do not convert it
if (auto shapeVal = embox.getShape()) if (auto shapeVal = embox.getShape())
return rewriteDynamicShape(embox, rewriter, shapeVal); return rewriteDynamicShape(embox, rewriter, shapeVal);
if (embox.getType().isa<fir::ClassType>()) if (mlir::isa<fir::ClassType>(embox.getType()))
TODO(embox.getLoc(), "embox conversion for fir.class type"); TODO(embox.getLoc(), "embox conversion for fir.class type");
if (auto boxTy = embox.getType().dyn_cast<fir::BoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BoxType>(embox.getType()))
if (auto seqTy = boxTy.getEleTy().dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(boxTy.getEleTy()))
if (!seqTy.hasDynamicExtents()) if (!seqTy.hasDynamicExtents())
return rewriteStaticShape(embox, rewriter, seqTy); return rewriteStaticShape(embox, rewriter, seqTy);
return mlir::failure(); return mlir::failure();
@ -294,10 +294,9 @@ public:
target.addIllegalOp<fir::ReboxOp>(); target.addIllegalOp<fir::ReboxOp>();
target.addIllegalOp<fir::DeclareOp>(); target.addIllegalOp<fir::DeclareOp>();
target.addDynamicallyLegalOp<fir::EmboxOp>([](fir::EmboxOp embox) { target.addDynamicallyLegalOp<fir::EmboxOp>([](fir::EmboxOp embox) {
return !(embox.getShape() || embox.getType() return !(embox.getShape() ||
.cast<fir::BaseBoxType>() mlir::isa<fir::SequenceType>(
.getEleTy() mlir::cast<fir::BaseBoxType>(embox.getType()).getEleTy()));
.isa<fir::SequenceType>());
}); });
mlir::RewritePatternSet patterns(&context); mlir::RewritePatternSet patterns(&context);
fir::populatePreCGRewritePatterns(patterns); fir::populatePreCGRewritePatterns(patterns);

View File

@ -120,7 +120,7 @@ void TBAABuilder::attachTBAATag(AliasAnalysisOpInterface op, Type baseFIRType,
// with both data and descriptor accesses. // with both data and descriptor accesses.
// Conservatively set any-access tag if there is any descriptor member. // Conservatively set any-access tag if there is any descriptor member.
tbaaTagSym = getAnyAccessTag(func); tbaaTagSym = getAnyAccessTag(func);
} else if (baseFIRType.isa<fir::BaseBoxType>()) { } else if (mlir::isa<fir::BaseBoxType>(baseFIRType)) {
tbaaTagSym = getBoxAccessTag(baseFIRType, accessFIRType, gep, func); tbaaTagSym = getBoxAccessTag(baseFIRType, accessFIRType, gep, func);
} else { } else {
tbaaTagSym = getDataAccessTag(baseFIRType, accessFIRType, gep, func); tbaaTagSym = getDataAccessTag(baseFIRType, accessFIRType, gep, func);

View File

@ -41,9 +41,9 @@ llvm::StringRef Attributes::getIntExtensionAttrName() const {
static const llvm::fltSemantics &floatToSemantics(const KindMapping &kindMap, static const llvm::fltSemantics &floatToSemantics(const KindMapping &kindMap,
mlir::Type type) { mlir::Type type) {
assert(isa_real(type)); assert(isa_real(type));
if (auto ty = type.dyn_cast<fir::RealType>()) if (auto ty = mlir::dyn_cast<fir::RealType>(type))
return kindMap.getFloatSemantics(ty.getFKind()); return kindMap.getFloatSemantics(ty.getFKind());
return type.cast<mlir::FloatType>().getFloatSemantics(); return mlir::cast<mlir::FloatType>(type).getFloatSemantics();
} }
static void typeTodo(const llvm::fltSemantics *sem, mlir::Location loc, static void typeTodo(const llvm::fltSemantics *sem, mlir::Location loc,

View File

@ -137,7 +137,7 @@ public:
if (!hasPortableSignature(dispatch.getFunctionType(), op)) if (!hasPortableSignature(dispatch.getFunctionType(), op))
convertCallOp(dispatch); convertCallOp(dispatch);
} else if (auto addr = mlir::dyn_cast<fir::AddrOfOp>(op)) { } else if (auto addr = mlir::dyn_cast<fir::AddrOfOp>(op)) {
if (addr.getType().isa<mlir::FunctionType>() && if (mlir::isa<mlir::FunctionType>(addr.getType()) &&
!hasPortableSignature(addr.getType(), op)) !hasPortableSignature(addr.getType(), op))
convertAddrOp(addr); convertAddrOp(addr);
} }
@ -601,7 +601,7 @@ public:
/// Taking the address of a function. Modify the signature as needed. /// Taking the address of a function. Modify the signature as needed.
void convertAddrOp(fir::AddrOfOp addrOp) { void convertAddrOp(fir::AddrOfOp addrOp) {
rewriter->setInsertionPoint(addrOp); rewriter->setInsertionPoint(addrOp);
auto addrTy = addrOp.getType().cast<mlir::FunctionType>(); auto addrTy = mlir::cast<mlir::FunctionType>(addrOp.getType());
fir::CodeGenSpecifics::Marshalling newInTyAndAttrs; fir::CodeGenSpecifics::Marshalling newInTyAndAttrs;
llvm::SmallVector<mlir::Type> newResTys; llvm::SmallVector<mlir::Type> newResTys;
auto loc = addrOp.getLoc(); auto loc = addrOp.getLoc();
@ -705,22 +705,23 @@ public:
/// return `true`. Otherwise, the signature is not portable and `false` is /// return `true`. Otherwise, the signature is not portable and `false` is
/// returned. /// returned.
bool hasPortableSignature(mlir::Type signature, mlir::Operation *op) { bool hasPortableSignature(mlir::Type signature, mlir::Operation *op) {
assert(signature.isa<mlir::FunctionType>()); assert(mlir::isa<mlir::FunctionType>(signature));
auto func = signature.dyn_cast<mlir::FunctionType>(); auto func = mlir::dyn_cast<mlir::FunctionType>(signature);
bool hasCCallingConv = isFuncWithCCallingConvention(op); bool hasCCallingConv = isFuncWithCCallingConvention(op);
for (auto ty : func.getResults()) for (auto ty : func.getResults())
if ((ty.isa<fir::BoxCharType>() && !noCharacterConversion) || if ((mlir::isa<fir::BoxCharType>(ty) && !noCharacterConversion) ||
(fir::isa_complex(ty) && !noComplexConversion) || (fir::isa_complex(ty) && !noComplexConversion) ||
(ty.isa<mlir::IntegerType>() && hasCCallingConv)) { (mlir::isa<mlir::IntegerType>(ty) && hasCCallingConv)) {
LLVM_DEBUG(llvm::dbgs() << "rewrite " << signature << " for target\n"); LLVM_DEBUG(llvm::dbgs() << "rewrite " << signature << " for target\n");
return false; return false;
} }
for (auto ty : func.getInputs()) for (auto ty : func.getInputs())
if (((ty.isa<fir::BoxCharType>() || fir::isCharacterProcedureTuple(ty)) && if (((mlir::isa<fir::BoxCharType>(ty) ||
fir::isCharacterProcedureTuple(ty)) &&
!noCharacterConversion) || !noCharacterConversion) ||
(fir::isa_complex(ty) && !noComplexConversion) || (fir::isa_complex(ty) && !noComplexConversion) ||
(ty.isa<mlir::IntegerType>() && hasCCallingConv) || (mlir::isa<mlir::IntegerType>(ty) && hasCCallingConv) ||
(ty.isa<fir::RecordType>() && !noStructConversion)) { (mlir::isa<fir::RecordType>(ty) && !noStructConversion)) {
LLVM_DEBUG(llvm::dbgs() << "rewrite " << signature << " for target\n"); LLVM_DEBUG(llvm::dbgs() << "rewrite " << signature << " for target\n");
return false; return false;
} }
@ -740,7 +741,7 @@ public:
/// Rewrite the signatures and body of the `FuncOp`s in the module for /// Rewrite the signatures and body of the `FuncOp`s in the module for
/// the immediately subsequent target code gen. /// the immediately subsequent target code gen.
void convertSignature(mlir::func::FuncOp func) { void convertSignature(mlir::func::FuncOp func) {
auto funcTy = func.getFunctionType().cast<mlir::FunctionType>(); auto funcTy = mlir::cast<mlir::FunctionType>(func.getFunctionType());
if (hasPortableSignature(funcTy, func) && !hasHostAssociations(func)) if (hasPortableSignature(funcTy, func) && !hasHostAssociations(func))
return; return;
llvm::SmallVector<mlir::Type> newResTys; llvm::SmallVector<mlir::Type> newResTys;

View File

@ -103,10 +103,10 @@ LLVMTypeConverter::LLVMTypeConverter(mlir::ModuleOp module, bool applyTBAA,
for (auto mem : tuple.getTypes()) { for (auto mem : tuple.getTypes()) {
// Prevent fir.box from degenerating to a pointer to a descriptor in the // Prevent fir.box from degenerating to a pointer to a descriptor in the
// context of a tuple type. // context of a tuple type.
if (auto box = mem.dyn_cast<fir::BaseBoxType>()) if (auto box = mlir::dyn_cast<fir::BaseBoxType>(mem))
members.push_back(convertBoxTypeAsStruct(box)); members.push_back(convertBoxTypeAsStruct(box));
else else
members.push_back(convertType(mem).cast<mlir::Type>()); members.push_back(mlir::cast<mlir::Type>(convertType(mem)));
} }
return mlir::LLVM::LLVMStructType::getLiteral(&getContext(), members, return mlir::LLVM::LLVMStructType::getLiteral(&getContext(), members,
/*isPacked=*/false); /*isPacked=*/false);
@ -181,10 +181,10 @@ std::optional<mlir::LogicalResult> LLVMTypeConverter::convertRecordType(
for (auto mem : derived.getTypeList()) { for (auto mem : derived.getTypeList()) {
// Prevent fir.box from degenerating to a pointer to a descriptor in the // Prevent fir.box from degenerating to a pointer to a descriptor in the
// context of a record type. // context of a record type.
if (auto box = mem.second.dyn_cast<fir::BaseBoxType>()) if (auto box = mlir::dyn_cast<fir::BaseBoxType>(mem.second))
members.push_back(convertBoxTypeAsStruct(box)); members.push_back(convertBoxTypeAsStruct(box));
else else
members.push_back(convertType(mem.second).cast<mlir::Type>()); members.push_back(mlir::cast<mlir::Type>(convertType(mem.second)));
} }
if (mlir::failed(st.setBody(members, /*isPacked=*/false))) if (mlir::failed(st.setBody(members, /*isPacked=*/false)))
return mlir::failure(); return mlir::failure();
@ -196,7 +196,7 @@ std::optional<mlir::LogicalResult> LLVMTypeConverter::convertRecordType(
// Extended descriptors are required for derived types. // Extended descriptors are required for derived types.
bool LLVMTypeConverter::requiresExtendedDesc(mlir::Type boxElementType) const { bool LLVMTypeConverter::requiresExtendedDesc(mlir::Type boxElementType) const {
auto eleTy = fir::unwrapSequenceType(boxElementType); auto eleTy = fir::unwrapSequenceType(boxElementType);
return eleTy.isa<fir::RecordType>(); return mlir::isa<fir::RecordType>(eleTy);
} }
// This corresponds to the descriptor as defined in ISO_Fortran_binding.h and // This corresponds to the descriptor as defined in ISO_Fortran_binding.h and
@ -211,7 +211,8 @@ mlir::Type LLVMTypeConverter::convertBoxTypeAsStruct(BaseBoxType box,
ele = removeIndirection; ele = removeIndirection;
auto eleTy = convertType(ele); auto eleTy = convertType(ele);
// base_addr* // base_addr*
if (ele.isa<SequenceType>() && eleTy.isa<mlir::LLVM::LLVMPointerType>()) if (mlir::isa<SequenceType>(ele) &&
mlir::isa<mlir::LLVM::LLVMPointerType>(eleTy))
dataDescFields.push_back(eleTy); dataDescFields.push_back(eleTy);
else else
dataDescFields.push_back( dataDescFields.push_back(
@ -236,7 +237,7 @@ mlir::Type LLVMTypeConverter::convertBoxTypeAsStruct(BaseBoxType box,
getDescFieldTypeModel<kF18AddendumPosInBox>()(&getContext())); getDescFieldTypeModel<kF18AddendumPosInBox>()(&getContext()));
// [dims] // [dims]
if (rank == unknownRank()) { if (rank == unknownRank()) {
if (auto seqTy = ele.dyn_cast<SequenceType>()) if (auto seqTy = mlir::dyn_cast<SequenceType>(ele))
rank = seqTy.getDimension(); rank = seqTy.getDimension();
else else
rank = 0; rank = 0;
@ -252,7 +253,8 @@ mlir::Type LLVMTypeConverter::convertBoxTypeAsStruct(BaseBoxType box,
auto rowTy = auto rowTy =
getExtendedDescFieldTypeModel<kOptRowTypePosInBox>()(&getContext()); getExtendedDescFieldTypeModel<kOptRowTypePosInBox>()(&getContext());
dataDescFields.push_back(mlir::LLVM::LLVMArrayType::get(rowTy, 1)); dataDescFields.push_back(mlir::LLVM::LLVMArrayType::get(rowTy, 1));
if (auto recTy = fir::unwrapSequenceType(ele).dyn_cast<fir::RecordType>()) if (auto recTy =
mlir::dyn_cast<fir::RecordType>(fir::unwrapSequenceType(ele)))
if (recTy.getNumLenParams() > 0) { if (recTy.getNumLenParams() > 0) {
// The descriptor design needs to be clarified regarding the number of // The descriptor design needs to be clarified regarding the number of
// length parameters in the addendum. Since it can change for // length parameters in the addendum. Since it can change for

View File

@ -264,23 +264,23 @@ void fir::FortranVariableFlagsAttr::print(mlir::AsmPrinter &printer) const {
void fir::printFirAttribute(FIROpsDialect *dialect, mlir::Attribute attr, void fir::printFirAttribute(FIROpsDialect *dialect, mlir::Attribute attr,
mlir::DialectAsmPrinter &p) { mlir::DialectAsmPrinter &p) {
auto &os = p.getStream(); auto &os = p.getStream();
if (auto exact = attr.dyn_cast<fir::ExactTypeAttr>()) { if (auto exact = mlir::dyn_cast<fir::ExactTypeAttr>(attr)) {
os << fir::ExactTypeAttr::getAttrName() << '<'; os << fir::ExactTypeAttr::getAttrName() << '<';
p.printType(exact.getType()); p.printType(exact.getType());
os << '>'; os << '>';
} else if (auto sub = attr.dyn_cast<fir::SubclassAttr>()) { } else if (auto sub = mlir::dyn_cast<fir::SubclassAttr>(attr)) {
os << fir::SubclassAttr::getAttrName() << '<'; os << fir::SubclassAttr::getAttrName() << '<';
p.printType(sub.getType()); p.printType(sub.getType());
os << '>'; os << '>';
} else if (attr.dyn_cast_or_null<fir::PointIntervalAttr>()) { } else if (mlir::dyn_cast_or_null<fir::PointIntervalAttr>(attr)) {
os << fir::PointIntervalAttr::getAttrName(); os << fir::PointIntervalAttr::getAttrName();
} else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) { } else if (mlir::dyn_cast_or_null<fir::ClosedIntervalAttr>(attr)) {
os << fir::ClosedIntervalAttr::getAttrName(); os << fir::ClosedIntervalAttr::getAttrName();
} else if (attr.dyn_cast_or_null<fir::LowerBoundAttr>()) { } else if (mlir::dyn_cast_or_null<fir::LowerBoundAttr>(attr)) {
os << fir::LowerBoundAttr::getAttrName(); os << fir::LowerBoundAttr::getAttrName();
} else if (attr.dyn_cast_or_null<fir::UpperBoundAttr>()) { } else if (mlir::dyn_cast_or_null<fir::UpperBoundAttr>(attr)) {
os << fir::UpperBoundAttr::getAttrName(); os << fir::UpperBoundAttr::getAttrName();
} else if (auto a = attr.dyn_cast_or_null<fir::RealAttr>()) { } else if (auto a = mlir::dyn_cast_or_null<fir::RealAttr>(attr)) {
os << fir::RealAttr::getAttrName() << '<' << a.getFKind() << ", i x"; os << fir::RealAttr::getAttrName() << '<' << a.getFKind() << ", i x";
llvm::SmallString<40> ss; llvm::SmallString<40> ss;
a.getValue().bitcastToAPInt().toStringUnsigned(ss, 16); a.getValue().bitcastToAPInt().toStringUnsigned(ss, 16);

View File

@ -57,7 +57,7 @@ static void propagateAttributes(mlir::Operation *fromOp,
static bool verifyInType(mlir::Type inType, static bool verifyInType(mlir::Type inType,
llvm::SmallVectorImpl<llvm::StringRef> &visited, llvm::SmallVectorImpl<llvm::StringRef> &visited,
unsigned dynamicExtents = 0) { unsigned dynamicExtents = 0) {
if (auto st = inType.dyn_cast<fir::SequenceType>()) { if (auto st = mlir::dyn_cast<fir::SequenceType>(inType)) {
auto shape = st.getShape(); auto shape = st.getShape();
if (shape.size() == 0) if (shape.size() == 0)
return true; return true;
@ -67,7 +67,7 @@ static bool verifyInType(mlir::Type inType,
if (dynamicExtents-- == 0) if (dynamicExtents-- == 0)
return true; return true;
} }
} else if (auto rt = inType.dyn_cast<fir::RecordType>()) { } else if (auto rt = mlir::dyn_cast<fir::RecordType>(inType)) {
// don't recurse if we're already visiting this one // don't recurse if we're already visiting this one
if (llvm::is_contained(visited, rt.getName())) if (llvm::is_contained(visited, rt.getName()))
return false; return false;
@ -84,13 +84,13 @@ static bool verifyInType(mlir::Type inType,
static bool verifyTypeParamCount(mlir::Type inType, unsigned numParams) { static bool verifyTypeParamCount(mlir::Type inType, unsigned numParams) {
auto ty = fir::unwrapSequenceType(inType); auto ty = fir::unwrapSequenceType(inType);
if (numParams > 0) { if (numParams > 0) {
if (auto recTy = ty.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(ty))
return numParams != recTy.getNumLenParams(); return numParams != recTy.getNumLenParams();
if (auto chrTy = ty.dyn_cast<fir::CharacterType>()) if (auto chrTy = mlir::dyn_cast<fir::CharacterType>(ty))
return !(numParams == 1 && chrTy.hasDynamicLen()); return !(numParams == 1 && chrTy.hasDynamicLen());
return true; return true;
} }
if (auto chrTy = ty.dyn_cast<fir::CharacterType>()) if (auto chrTy = mlir::dyn_cast<fir::CharacterType>(ty))
return !chrTy.hasConstantLen(); return !chrTy.hasConstantLen();
return false; return false;
} }
@ -171,13 +171,13 @@ static void printAllocatableOp(mlir::OpAsmPrinter &p, OP &op) {
/// Create a legal memory reference as return type /// Create a legal memory reference as return type
static mlir::Type wrapAllocaResultType(mlir::Type intype) { static mlir::Type wrapAllocaResultType(mlir::Type intype) {
// FIR semantics: memory references to memory references are disallowed // FIR semantics: memory references to memory references are disallowed
if (intype.isa<fir::ReferenceType>()) if (mlir::isa<fir::ReferenceType>(intype))
return {}; return {};
return fir::ReferenceType::get(intype); return fir::ReferenceType::get(intype);
} }
mlir::Type fir::AllocaOp::getAllocatedType() { mlir::Type fir::AllocaOp::getAllocatedType() {
return getType().cast<fir::ReferenceType>().getEleTy(); return mlir::cast<fir::ReferenceType>(getType()).getEleTy();
} }
mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) { mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) {
@ -270,7 +270,7 @@ mlir::LogicalResult fir::AllocaOp::verify() {
if (verifyTypeParamCount(getInType(), numLenParams())) if (verifyTypeParamCount(getInType(), numLenParams()))
return emitOpError("LEN params do not correspond to type"); return emitOpError("LEN params do not correspond to type");
mlir::Type outType = getType(); mlir::Type outType = getType();
if (!outType.isa<fir::ReferenceType>()) if (!mlir::isa<fir::ReferenceType>(outType))
return emitOpError("must be a !fir.ref type"); return emitOpError("must be a !fir.ref type");
if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType))) if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType)))
return emitOpError("cannot allocate !fir.box of unknown rank or type"); return emitOpError("cannot allocate !fir.box of unknown rank or type");
@ -286,14 +286,14 @@ static mlir::Type wrapAllocMemResultType(mlir::Type intype) {
// Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER
// 8.5.3 note 1 prohibits ALLOCATABLE procedures as well // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well
// FIR semantics: one may not allocate a memory reference value // FIR semantics: one may not allocate a memory reference value
if (intype.isa<fir::ReferenceType, fir::HeapType, fir::PointerType, if (mlir::isa<fir::ReferenceType, fir::HeapType, fir::PointerType,
mlir::FunctionType>()) mlir::FunctionType>(intype))
return {}; return {};
return fir::HeapType::get(intype); return fir::HeapType::get(intype);
} }
mlir::Type fir::AllocMemOp::getAllocatedType() { mlir::Type fir::AllocMemOp::getAllocatedType() {
return getType().cast<fir::HeapType>().getEleTy(); return mlir::cast<fir::HeapType>(getType()).getEleTy();
} }
mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) { mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) {
@ -348,7 +348,7 @@ mlir::LogicalResult fir::AllocMemOp::verify() {
if (verifyTypeParamCount(getInType(), numLenParams())) if (verifyTypeParamCount(getInType(), numLenParams()))
return emitOpError("LEN params do not correspond to type"); return emitOpError("LEN params do not correspond to type");
mlir::Type outType = getType(); mlir::Type outType = getType();
if (!outType.dyn_cast<fir::HeapType>()) if (!mlir::dyn_cast<fir::HeapType>(outType))
return emitOpError("must be a !fir.heap type"); return emitOpError("must be a !fir.heap type");
if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType))) if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType)))
return emitOpError("cannot allocate !fir.box of unknown rank or type"); return emitOpError("cannot allocate !fir.box of unknown rank or type");
@ -364,13 +364,13 @@ mlir::LogicalResult fir::AllocMemOp::verify() {
static bool validTypeParams(mlir::Type dynTy, mlir::ValueRange typeParams) { static bool validTypeParams(mlir::Type dynTy, mlir::ValueRange typeParams) {
dynTy = fir::unwrapAllRefAndSeqType(dynTy); dynTy = fir::unwrapAllRefAndSeqType(dynTy);
// A box value will contain type parameter values itself. // A box value will contain type parameter values itself.
if (dynTy.isa<fir::BoxType>()) if (mlir::isa<fir::BoxType>(dynTy))
return typeParams.size() == 0; return typeParams.size() == 0;
// Derived type must have all type parameters satisfied. // Derived type must have all type parameters satisfied.
if (auto recTy = dynTy.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(dynTy))
return typeParams.size() == recTy.getNumLenParams(); return typeParams.size() == recTy.getNumLenParams();
// Characters with non-constant LEN must have a type parameter value. // Characters with non-constant LEN must have a type parameter value.
if (auto charTy = dynTy.dyn_cast<fir::CharacterType>()) if (auto charTy = mlir::dyn_cast<fir::CharacterType>(dynTy))
if (charTy.hasDynamicLen()) if (charTy.hasDynamicLen())
return typeParams.size() == 1; return typeParams.size() == 1;
// Otherwise, any type parameters are invalid. // Otherwise, any type parameters are invalid.
@ -379,7 +379,7 @@ static bool validTypeParams(mlir::Type dynTy, mlir::ValueRange typeParams) {
mlir::LogicalResult fir::ArrayCoorOp::verify() { mlir::LogicalResult fir::ArrayCoorOp::verify() {
auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
auto arrTy = eleTy.dyn_cast<fir::SequenceType>(); auto arrTy = mlir::dyn_cast<fir::SequenceType>(eleTy);
if (!arrTy) if (!arrTy)
return emitOpError("must be a reference to an array"); return emitOpError("must be a reference to an array");
auto arrDim = arrTy.getDimension(); auto arrDim = arrTy.getDimension();
@ -387,14 +387,14 @@ mlir::LogicalResult fir::ArrayCoorOp::verify() {
if (auto shapeOp = getShape()) { if (auto shapeOp = getShape()) {
auto shapeTy = shapeOp.getType(); auto shapeTy = shapeOp.getType();
unsigned shapeTyRank = 0; unsigned shapeTyRank = 0;
if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) { if (auto s = mlir::dyn_cast<fir::ShapeType>(shapeTy)) {
shapeTyRank = s.getRank(); shapeTyRank = s.getRank();
} else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) { } else if (auto ss = mlir::dyn_cast<fir::ShapeShiftType>(shapeTy)) {
shapeTyRank = ss.getRank(); shapeTyRank = ss.getRank();
} else { } else {
auto s = shapeTy.cast<fir::ShiftType>(); auto s = mlir::cast<fir::ShiftType>(shapeTy);
shapeTyRank = s.getRank(); shapeTyRank = s.getRank();
if (!getMemref().getType().isa<fir::BaseBoxType>()) if (!mlir::isa<fir::BaseBoxType>(getMemref().getType()))
return emitOpError("shift can only be provided with fir.box memref"); return emitOpError("shift can only be provided with fir.box memref");
} }
if (arrDim && arrDim != shapeTyRank) if (arrDim && arrDim != shapeTyRank)
@ -407,7 +407,7 @@ mlir::LogicalResult fir::ArrayCoorOp::verify() {
if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp())) if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp()))
if (!sl.getSubstr().empty()) if (!sl.getSubstr().empty())
return emitOpError("array_coor cannot take a slice with substring"); return emitOpError("array_coor cannot take a slice with substring");
if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>()) if (auto sliceTy = mlir::dyn_cast<fir::SliceType>(sliceOp.getType()))
if (sliceTy.getRank() != arrDim) if (sliceTy.getRank() != arrDim)
return emitOpError("rank of dimension in slice mismatched"); return emitOpError("rank of dimension in slice mismatched");
} }
@ -422,13 +422,13 @@ mlir::LogicalResult fir::ArrayCoorOp::verify() {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
static mlir::Type adjustedElementType(mlir::Type t) { static mlir::Type adjustedElementType(mlir::Type t) {
if (auto ty = t.dyn_cast<fir::ReferenceType>()) { if (auto ty = mlir::dyn_cast<fir::ReferenceType>(t)) {
auto eleTy = ty.getEleTy(); auto eleTy = ty.getEleTy();
if (fir::isa_char(eleTy)) if (fir::isa_char(eleTy))
return eleTy; return eleTy;
if (fir::isa_derived(eleTy)) if (fir::isa_derived(eleTy))
return eleTy; return eleTy;
if (eleTy.isa<fir::SequenceType>()) if (mlir::isa<fir::SequenceType>(eleTy))
return eleTy; return eleTy;
} }
return t; return t;
@ -448,7 +448,7 @@ std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() {
mlir::LogicalResult fir::ArrayLoadOp::verify() { mlir::LogicalResult fir::ArrayLoadOp::verify() {
auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
auto arrTy = eleTy.dyn_cast<fir::SequenceType>(); auto arrTy = mlir::dyn_cast<fir::SequenceType>(eleTy);
if (!arrTy) if (!arrTy)
return emitOpError("must be a reference to an array"); return emitOpError("must be a reference to an array");
auto arrDim = arrTy.getDimension(); auto arrDim = arrTy.getDimension();
@ -456,14 +456,14 @@ mlir::LogicalResult fir::ArrayLoadOp::verify() {
if (auto shapeOp = getShape()) { if (auto shapeOp = getShape()) {
auto shapeTy = shapeOp.getType(); auto shapeTy = shapeOp.getType();
unsigned shapeTyRank = 0u; unsigned shapeTyRank = 0u;
if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) { if (auto s = mlir::dyn_cast<fir::ShapeType>(shapeTy)) {
shapeTyRank = s.getRank(); shapeTyRank = s.getRank();
} else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) { } else if (auto ss = mlir::dyn_cast<fir::ShapeShiftType>(shapeTy)) {
shapeTyRank = ss.getRank(); shapeTyRank = ss.getRank();
} else { } else {
auto s = shapeTy.cast<fir::ShiftType>(); auto s = mlir::cast<fir::ShiftType>(shapeTy);
shapeTyRank = s.getRank(); shapeTyRank = s.getRank();
if (!getMemref().getType().isa<fir::BaseBoxType>()) if (!mlir::isa<fir::BaseBoxType>(getMemref().getType()))
return emitOpError("shift can only be provided with fir.box memref"); return emitOpError("shift can only be provided with fir.box memref");
} }
if (arrDim && arrDim != shapeTyRank) if (arrDim && arrDim != shapeTyRank)
@ -474,7 +474,7 @@ mlir::LogicalResult fir::ArrayLoadOp::verify() {
if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp())) if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp()))
if (!sl.getSubstr().empty()) if (!sl.getSubstr().empty())
return emitOpError("array_load cannot take a slice with substring"); return emitOpError("array_load cannot take a slice with substring");
if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>()) if (auto sliceTy = mlir::dyn_cast<fir::SliceType>(sliceOp.getType()))
if (sliceTy.getRank() != arrDim) if (sliceTy.getRank() != arrDim)
return emitOpError("rank of dimension in slice mismatched"); return emitOpError("rank of dimension in slice mismatched");
} }
@ -502,7 +502,7 @@ mlir::LogicalResult fir::ArrayMergeStoreOp::verify() {
// This is an intra-object merge, where the slice is projecting the // This is an intra-object merge, where the slice is projecting the
// subfields that are to be overwritten by the merge operation. // subfields that are to be overwritten by the merge operation.
auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy)) {
auto projTy = auto projTy =
fir::applyPathToType(seqTy.getEleTy(), sliceOp.getFields()); fir::applyPathToType(seqTy.getEleTy(), sliceOp.getFields());
if (fir::unwrapSequenceType(getOriginal().getType()) != projTy) if (fir::unwrapSequenceType(getOriginal().getType()) != projTy)
@ -540,7 +540,7 @@ mlir::Type validArraySubobject(A op) {
} }
mlir::LogicalResult fir::ArrayFetchOp::verify() { mlir::LogicalResult fir::ArrayFetchOp::verify() {
auto arrTy = getSequence().getType().cast<fir::SequenceType>(); auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
auto indSize = getIndices().size(); auto indSize = getIndices().size();
if (indSize < arrTy.getDimension()) if (indSize < arrTy.getDimension())
return emitOpError("number of indices != dimension of array"); return emitOpError("number of indices != dimension of array");
@ -562,7 +562,7 @@ mlir::LogicalResult fir::ArrayFetchOp::verify() {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
mlir::LogicalResult fir::ArrayAccessOp::verify() { mlir::LogicalResult fir::ArrayAccessOp::verify() {
auto arrTy = getSequence().getType().cast<fir::SequenceType>(); auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
std::size_t indSize = getIndices().size(); std::size_t indSize = getIndices().size();
if (indSize < arrTy.getDimension()) if (indSize < arrTy.getDimension())
return emitOpError("number of indices != dimension of array"); return emitOpError("number of indices != dimension of array");
@ -584,7 +584,7 @@ mlir::LogicalResult fir::ArrayAccessOp::verify() {
mlir::LogicalResult fir::ArrayUpdateOp::verify() { mlir::LogicalResult fir::ArrayUpdateOp::verify() {
if (fir::isa_ref_type(getMerge().getType())) if (fir::isa_ref_type(getMerge().getType()))
return emitOpError("does not support reference type for merge"); return emitOpError("does not support reference type for merge");
auto arrTy = getSequence().getType().cast<fir::SequenceType>(); auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
auto indSize = getIndices().size(); auto indSize = getIndices().size();
if (indSize < arrTy.getDimension()) if (indSize < arrTy.getDimension())
return emitOpError("number of indices != dimension of array"); return emitOpError("number of indices != dimension of array");
@ -604,7 +604,7 @@ mlir::LogicalResult fir::ArrayUpdateOp::verify() {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
mlir::LogicalResult fir::ArrayModifyOp::verify() { mlir::LogicalResult fir::ArrayModifyOp::verify() {
auto arrTy = getSequence().getType().cast<fir::SequenceType>(); auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
auto indSize = getIndices().size(); auto indSize = getIndices().size();
if (indSize < arrTy.getDimension()) if (indSize < arrTy.getDimension())
return emitOpError("number of indices must match array dimension"); return emitOpError("number of indices must match array dimension");
@ -740,7 +740,7 @@ mlir::ParseResult fir::CallOp::parse(mlir::OpAsmParser &parser,
parser.parseType(type)) parser.parseType(type))
return mlir::failure(); return mlir::failure();
auto funcType = type.dyn_cast<mlir::FunctionType>(); auto funcType = mlir::dyn_cast<mlir::FunctionType>(type);
if (!funcType) if (!funcType)
return parser.emitError(parser.getNameLoc(), "expected function type"); return parser.emitError(parser.getNameLoc(), "expected function type");
if (isDirect) { if (isDirect) {
@ -785,7 +785,7 @@ void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
mlir::LogicalResult fir::CharConvertOp::verify() { mlir::LogicalResult fir::CharConvertOp::verify() {
auto unwrap = [&](mlir::Type t) { auto unwrap = [&](mlir::Type t) {
t = fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t)); t = fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t));
return t.dyn_cast<fir::CharacterType>(); return mlir::dyn_cast<fir::CharacterType>(t);
}; };
auto inTy = unwrap(getFrom().getType()); auto inTy = unwrap(getFrom().getType());
auto outTy = unwrap(getTo().getType()); auto outTy = unwrap(getTo().getType());
@ -832,13 +832,13 @@ static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser,
parser.resolveOperands(ops, type, result.operands)) parser.resolveOperands(ops, type, result.operands))
return mlir::failure(); return mlir::failure();
if (!predicateNameAttr.isa<mlir::StringAttr>()) if (!mlir::isa<mlir::StringAttr>(predicateNameAttr))
return parser.emitError(parser.getNameLoc(), return parser.emitError(parser.getNameLoc(),
"expected string comparison predicate attribute"); "expected string comparison predicate attribute");
// Rewrite string attribute to an enum value. // Rewrite string attribute to an enum value.
llvm::StringRef predicateName = llvm::StringRef predicateName =
predicateNameAttr.cast<mlir::StringAttr>().getValue(); mlir::cast<mlir::StringAttr>(predicateNameAttr).getValue();
auto predicate = fir::CmpcOp::getPredicateByName(predicateName); auto predicate = fir::CmpcOp::getPredicateByName(predicateName);
auto builder = parser.getBuilder(); auto builder = parser.getBuilder();
mlir::Type i1Type = builder.getI1Type(); mlir::Type i1Type = builder.getI1Type();
@ -906,7 +906,7 @@ void fir::ConstcOp::print(mlir::OpAsmPrinter &p) {
} }
mlir::LogicalResult fir::ConstcOp::verify() { mlir::LogicalResult fir::ConstcOp::verify() {
if (!getType().isa<fir::ComplexType>()) if (!mlir::isa<fir::ComplexType>(getType()))
return emitOpError("must be a !fir.complex type"); return emitOpError("must be a !fir.complex type");
return mlir::success(); return mlir::success();
} }
@ -929,15 +929,16 @@ mlir::OpFoldResult fir::ConvertOp::fold(FoldAdaptor adaptor) {
if (matchPattern(getValue(), mlir::m_Op<fir::ConvertOp>())) { if (matchPattern(getValue(), mlir::m_Op<fir::ConvertOp>())) {
auto inner = mlir::cast<fir::ConvertOp>(getValue().getDefiningOp()); auto inner = mlir::cast<fir::ConvertOp>(getValue().getDefiningOp());
// (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a
if (auto toTy = getType().dyn_cast<fir::LogicalType>()) if (auto toTy = mlir::dyn_cast<fir::LogicalType>(getType()))
if (auto fromTy = inner.getValue().getType().dyn_cast<fir::LogicalType>()) if (auto fromTy =
if (inner.getType().isa<mlir::IntegerType>() && (toTy == fromTy)) mlir::dyn_cast<fir::LogicalType>(inner.getValue().getType()))
if (mlir::isa<mlir::IntegerType>(inner.getType()) && (toTy == fromTy))
return inner.getValue(); return inner.getValue();
// (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a
if (auto toTy = getType().dyn_cast<mlir::IntegerType>()) if (auto toTy = mlir::dyn_cast<mlir::IntegerType>(getType()))
if (auto fromTy = if (auto fromTy =
inner.getValue().getType().dyn_cast<mlir::IntegerType>()) mlir::dyn_cast<mlir::IntegerType>(inner.getValue().getType()))
if (inner.getType().isa<fir::LogicalType>() && (toTy == fromTy) && if (mlir::isa<fir::LogicalType>(inner.getType()) && (toTy == fromTy) &&
(fromTy.getWidth() == 1)) (fromTy.getWidth() == 1))
return inner.getValue(); return inner.getValue();
} }
@ -945,7 +946,7 @@ mlir::OpFoldResult fir::ConvertOp::fold(FoldAdaptor adaptor) {
} }
bool fir::ConvertOp::isInteger(mlir::Type ty) { bool fir::ConvertOp::isInteger(mlir::Type ty) {
return ty.isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType>(); return mlir::isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType>(ty);
} }
bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) { bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) {
@ -953,13 +954,13 @@ bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) {
} }
bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) { bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) {
return ty.isa<mlir::FloatType, fir::RealType>(); return mlir::isa<mlir::FloatType, fir::RealType>(ty);
} }
bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) { bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) {
return ty.isa<fir::ReferenceType, fir::PointerType, fir::HeapType, return mlir::isa<fir::ReferenceType, fir::PointerType, fir::HeapType,
fir::LLVMPointerType, mlir::MemRefType, mlir::FunctionType, fir::LLVMPointerType, mlir::MemRefType, mlir::FunctionType,
fir::TypeDescType>(); fir::TypeDescType>(ty);
} }
static std::optional<mlir::Type> getVectorElementType(mlir::Type ty) { static std::optional<mlir::Type> getVectorElementType(mlir::Type ty) {
@ -1026,12 +1027,14 @@ bool fir::ConvertOp::canBeConverted(mlir::Type inType, mlir::Type outType) {
(isFloatCompatible(inType) && isFloatCompatible(outType)) || (isFloatCompatible(inType) && isFloatCompatible(outType)) ||
(isIntegerCompatible(inType) && isPointerCompatible(outType)) || (isIntegerCompatible(inType) && isPointerCompatible(outType)) ||
(isPointerCompatible(inType) && isIntegerCompatible(outType)) || (isPointerCompatible(inType) && isIntegerCompatible(outType)) ||
(inType.isa<fir::BoxType>() && outType.isa<fir::BoxType>()) || (mlir::isa<fir::BoxType>(inType) &&
(inType.isa<fir::BoxProcType>() && outType.isa<fir::BoxProcType>()) || mlir::isa<fir::BoxType>(outType)) ||
(mlir::isa<fir::BoxProcType>(inType) &&
mlir::isa<fir::BoxProcType>(outType)) ||
(fir::isa_complex(inType) && fir::isa_complex(outType)) || (fir::isa_complex(inType) && fir::isa_complex(outType)) ||
(fir::isBoxedRecordType(inType) && fir::isPolymorphicType(outType)) || (fir::isBoxedRecordType(inType) && fir::isPolymorphicType(outType)) ||
(fir::isPolymorphicType(inType) && fir::isPolymorphicType(outType)) || (fir::isPolymorphicType(inType) && fir::isPolymorphicType(outType)) ||
(fir::isPolymorphicType(inType) && outType.isa<BoxType>()) || (fir::isPolymorphicType(inType) && mlir::isa<BoxType>(outType)) ||
areVectorsCompatible(inType, outType); areVectorsCompatible(inType, outType);
} }
@ -1079,7 +1082,7 @@ mlir::LogicalResult fir::CoordinateOp::verify() {
const mlir::Type refTy = getRef().getType(); const mlir::Type refTy = getRef().getType();
if (fir::isa_ref_type(refTy)) { if (fir::isa_ref_type(refTy)) {
auto eleTy = fir::dyn_cast_ptrEleTy(refTy); auto eleTy = fir::dyn_cast_ptrEleTy(refTy);
if (auto arrTy = eleTy.dyn_cast<fir::SequenceType>()) { if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(eleTy)) {
if (arrTy.hasUnknownShape()) if (arrTy.hasUnknownShape())
return emitOpError("cannot find coordinate in unknown shape"); return emitOpError("cannot find coordinate in unknown shape");
if (arrTy.getConstantRows() < arrTy.getDimension() - 1) if (arrTy.getConstantRows() < arrTy.getDimension() - 1)
@ -1094,8 +1097,8 @@ mlir::LogicalResult fir::CoordinateOp::verify() {
const unsigned numCoors = getCoor().size(); const unsigned numCoors = getCoor().size();
for (auto coorOperand : llvm::enumerate(getCoor())) { for (auto coorOperand : llvm::enumerate(getCoor())) {
auto co = coorOperand.value(); auto co = coorOperand.value();
if (dimension == 0 && eleTy.isa<fir::SequenceType>()) { if (dimension == 0 && mlir::isa<fir::SequenceType>(eleTy)) {
dimension = eleTy.cast<fir::SequenceType>().getDimension(); dimension = mlir::cast<fir::SequenceType>(eleTy).getDimension();
if (dimension == 0) if (dimension == 0)
return emitOpError("cannot apply to array of unknown rank"); return emitOpError("cannot apply to array of unknown rank");
} }
@ -1104,7 +1107,7 @@ mlir::LogicalResult fir::CoordinateOp::verify() {
// Recovering a LEN type parameter only makes sense from a boxed // Recovering a LEN type parameter only makes sense from a boxed
// value. For a bare reference, the LEN type parameters must be // value. For a bare reference, the LEN type parameters must be
// passed as additional arguments to `index`. // passed as additional arguments to `index`.
if (refTy.isa<fir::BoxType>()) { if (mlir::isa<fir::BoxType>(refTy)) {
if (coorOperand.index() != numCoors - 1) if (coorOperand.index() != numCoors - 1)
return emitOpError("len_param_index must be last argument"); return emitOpError("len_param_index must be last argument");
if (getNumOperands() != 2) if (getNumOperands() != 2)
@ -1117,7 +1120,7 @@ mlir::LogicalResult fir::CoordinateOp::verify() {
} else if (auto index = mlir::dyn_cast<fir::FieldIndexOp>(defOp)) { } else if (auto index = mlir::dyn_cast<fir::FieldIndexOp>(defOp)) {
if (eleTy != index.getOnType()) if (eleTy != index.getOnType())
emitOpError("field_index type not compatible with reference type"); emitOpError("field_index type not compatible with reference type");
if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) { if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy)) {
eleTy = recTy.getType(index.getFieldName()); eleTy = recTy.getType(index.getFieldName());
continue; continue;
} }
@ -1126,21 +1129,21 @@ mlir::LogicalResult fir::CoordinateOp::verify() {
} }
if (dimension) { if (dimension) {
if (--dimension == 0) if (--dimension == 0)
eleTy = eleTy.cast<fir::SequenceType>().getEleTy(); eleTy = mlir::cast<fir::SequenceType>(eleTy).getEleTy();
} else { } else {
if (auto t = eleTy.dyn_cast<mlir::TupleType>()) { if (auto t = mlir::dyn_cast<mlir::TupleType>(eleTy)) {
// FIXME: Generally, we don't know which field of the tuple is being // FIXME: Generally, we don't know which field of the tuple is being
// referred to unless the operand is a constant. Just assume everything // referred to unless the operand is a constant. Just assume everything
// is good in the tuple case for now. // is good in the tuple case for now.
return mlir::success(); return mlir::success();
} else if (auto t = eleTy.dyn_cast<fir::RecordType>()) { } else if (auto t = mlir::dyn_cast<fir::RecordType>(eleTy)) {
// FIXME: This is the same as the tuple case. // FIXME: This is the same as the tuple case.
return mlir::success(); return mlir::success();
} else if (auto t = eleTy.dyn_cast<fir::ComplexType>()) { } else if (auto t = mlir::dyn_cast<fir::ComplexType>(eleTy)) {
eleTy = t.getElementType(); eleTy = t.getElementType();
} else if (auto t = eleTy.dyn_cast<mlir::ComplexType>()) { } else if (auto t = mlir::dyn_cast<mlir::ComplexType>(eleTy)) {
eleTy = t.getElementType(); eleTy = t.getElementType();
} else if (auto t = eleTy.dyn_cast<fir::CharacterType>()) { } else if (auto t = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
if (t.getLen() == fir::CharacterType::singleton()) if (t.getLen() == fir::CharacterType::singleton())
return emitOpError("cannot apply to character singleton"); return emitOpError("cannot apply to character singleton");
eleTy = fir::CharacterType::getSingleton(t.getContext(), t.getFKind()); eleTy = fir::CharacterType::getSingleton(t.getContext(), t.getFKind());
@ -1216,17 +1219,17 @@ mlir::LogicalResult fir::TypeInfoOp::verify() {
mlir::LogicalResult fir::EmboxOp::verify() { mlir::LogicalResult fir::EmboxOp::verify() {
auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType()); auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType());
bool isArray = false; bool isArray = false;
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy)) {
eleTy = seqTy.getEleTy(); eleTy = seqTy.getEleTy();
isArray = true; isArray = true;
} }
if (hasLenParams()) { if (hasLenParams()) {
auto lenPs = numLenParams(); auto lenPs = numLenParams();
if (auto rt = eleTy.dyn_cast<fir::RecordType>()) { if (auto rt = mlir::dyn_cast<fir::RecordType>(eleTy)) {
if (lenPs != rt.getNumLenParams()) if (lenPs != rt.getNumLenParams())
return emitOpError("number of LEN params does not correspond" return emitOpError("number of LEN params does not correspond"
" to the !fir.type type"); " to the !fir.type type");
} else if (auto strTy = eleTy.dyn_cast<fir::CharacterType>()) { } else if (auto strTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
if (strTy.getLen() != fir::CharacterType::unknownLen()) if (strTy.getLen() != fir::CharacterType::unknownLen())
return emitOpError("CHARACTER already has static LEN"); return emitOpError("CHARACTER already has static LEN");
} else { } else {
@ -1240,7 +1243,7 @@ mlir::LogicalResult fir::EmboxOp::verify() {
return emitOpError("shape must not be provided for a scalar"); return emitOpError("shape must not be provided for a scalar");
if (getSlice() && !isArray) if (getSlice() && !isArray)
return emitOpError("slice must not be provided for a scalar"); return emitOpError("slice must not be provided for a scalar");
if (getSourceBox() && !getResult().getType().isa<fir::ClassType>()) if (getSourceBox() && !mlir::isa<fir::ClassType>(getResult().getType()))
return emitOpError("source_box must be used with fir.class result type"); return emitOpError("source_box must be used with fir.class result type");
return mlir::success(); return mlir::success();
} }
@ -1251,7 +1254,7 @@ mlir::LogicalResult fir::EmboxOp::verify() {
mlir::LogicalResult fir::EmboxCharOp::verify() { mlir::LogicalResult fir::EmboxCharOp::verify() {
auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType()); auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType());
if (!eleTy.dyn_cast_or_null<fir::CharacterType>()) if (!mlir::dyn_cast_or_null<fir::CharacterType>(eleTy))
return mlir::failure(); return mlir::failure();
return mlir::success(); return mlir::success();
} }
@ -1263,8 +1266,8 @@ mlir::LogicalResult fir::EmboxCharOp::verify() {
mlir::LogicalResult fir::EmboxProcOp::verify() { mlir::LogicalResult fir::EmboxProcOp::verify() {
// host bindings (optional) must be a reference to a tuple // host bindings (optional) must be a reference to a tuple
if (auto h = getHost()) { if (auto h = getHost()) {
if (auto r = h.getType().dyn_cast<fir::ReferenceType>()) if (auto r = mlir::dyn_cast<fir::ReferenceType>(h.getType()))
if (r.getEleTy().isa<mlir::TupleType>()) if (mlir::isa<mlir::TupleType>(r.getEleTy()))
return mlir::success(); return mlir::success();
return mlir::failure(); return mlir::failure();
} }
@ -1300,7 +1303,7 @@ void fir::TypeDescOp::print(mlir::OpAsmPrinter &p) {
mlir::LogicalResult fir::TypeDescOp::verify() { mlir::LogicalResult fir::TypeDescOp::verify() {
mlir::Type resultTy = getType(); mlir::Type resultTy = getType();
if (auto tdesc = resultTy.dyn_cast<fir::TypeDescType>()) { if (auto tdesc = mlir::dyn_cast<fir::TypeDescType>(resultTy)) {
if (tdesc.getOfTy() != getInType()) if (tdesc.getOfTy() != getInType())
return emitOpError("wrapped type mismatched"); return emitOpError("wrapped type mismatched");
return mlir::success(); return mlir::success();
@ -1527,7 +1530,7 @@ mlir::ParseResult parseFieldLikeOp(mlir::OpAsmParser &parser,
return mlir::failure(); return mlir::failure();
result.addAttribute(fir::FieldIndexOp::getFieldAttrName(), result.addAttribute(fir::FieldIndexOp::getFieldAttrName(),
builder.getStringAttr(fieldName)); builder.getStringAttr(fieldName));
if (!recty.dyn_cast<fir::RecordType>()) if (!mlir::dyn_cast<fir::RecordType>(recty))
return mlir::failure(); return mlir::failure();
result.addAttribute(fir::FieldIndexOp::getTypeAttrName(), result.addAttribute(fir::FieldIndexOp::getTypeAttrName(),
mlir::TypeAttr::get(recty)); mlir::TypeAttr::get(recty));
@ -1671,7 +1674,7 @@ mlir::LogicalResult fir::InsertOnRangeOp::verify() {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
static bool checkIsIntegerConstant(mlir::Attribute attr, std::int64_t conVal) { static bool checkIsIntegerConstant(mlir::Attribute attr, std::int64_t conVal) {
if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>()) if (auto iattr = mlir::dyn_cast<mlir::IntegerAttr>(attr))
return iattr.getInt() == conVal; return iattr.getInt() == conVal;
return false; return false;
} }
@ -1690,7 +1693,7 @@ struct UndoComplexPattern : public mlir::RewritePattern {
matchAndRewrite(mlir::Operation *op, matchAndRewrite(mlir::Operation *op,
mlir::PatternRewriter &rewriter) const override { mlir::PatternRewriter &rewriter) const override {
auto insval = mlir::dyn_cast_or_null<fir::InsertValueOp>(op); auto insval = mlir::dyn_cast_or_null<fir::InsertValueOp>(op);
if (!insval || !insval.getType().isa<fir::ComplexType>()) if (!insval || !mlir::isa<fir::ComplexType>(insval.getType()))
return mlir::failure(); return mlir::failure();
auto insval2 = mlir::dyn_cast_or_null<fir::InsertValueOp>( auto insval2 = mlir::dyn_cast_or_null<fir::InsertValueOp>(
insval.getAdt().getDefiningOp()); insval.getAdt().getDefiningOp());
@ -1819,7 +1822,7 @@ mlir::ParseResult fir::IterWhileOp::parse(mlir::OpAsmParser &parser,
parser.parseRParen()) parser.parseRParen())
return mlir::failure(); return mlir::failure();
// Type list must be "(index, i1)". // Type list must be "(index, i1)".
if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() || if (typeList.size() != 2 || !mlir::isa<mlir::IndexType>(typeList[0]) ||
!typeList[1].isSignlessInteger(1)) !typeList[1].isSignlessInteger(1))
return mlir::failure(); return mlir::failure();
result.addTypes(typeList); result.addTypes(typeList);
@ -1873,7 +1876,7 @@ mlir::LogicalResult fir::IterWhileOp::verify() {
auto opNumResults = getNumResults(); auto opNumResults = getNumResults();
if (getFinalValue()) { if (getFinalValue()) {
// Result type must be "(index, i1, ...)". // Result type must be "(index, i1, ...)".
if (!getResult(0).getType().isa<mlir::IndexType>()) if (!mlir::isa<mlir::IndexType>(getResult(0).getType()))
return emitOpError("result #0 expected to be index"); return emitOpError("result #0 expected to be index");
if (!getResult(1).getType().isSignlessInteger(1)) if (!getResult(1).getType().isSignlessInteger(1))
return emitOpError("result #1 expected to be i1"); return emitOpError("result #1 expected to be i1");
@ -2316,7 +2319,7 @@ void fir::DTEntryOp::print(mlir::OpAsmPrinter &p) {
/// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>. /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>.
static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) { static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy); auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
return seqTy.getEleTy(); return seqTy.getEleTy();
return eleTy; return eleTy;
} }
@ -2324,8 +2327,8 @@ static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
/// Test if \p t1 and \p t2 are compatible character types (if they can /// Test if \p t1 and \p t2 are compatible character types (if they can
/// represent the same type at runtime). /// represent the same type at runtime).
static bool areCompatibleCharacterTypes(mlir::Type t1, mlir::Type t2) { static bool areCompatibleCharacterTypes(mlir::Type t1, mlir::Type t2) {
auto c1 = t1.dyn_cast<fir::CharacterType>(); auto c1 = mlir::dyn_cast<fir::CharacterType>(t1);
auto c2 = t2.dyn_cast<fir::CharacterType>(); auto c2 = mlir::dyn_cast<fir::CharacterType>(t2);
if (!c1 || !c2) if (!c1 || !c2)
return false; return false;
if (c1.hasDynamicLen() || c2.hasDynamicLen()) if (c1.hasDynamicLen() || c2.hasDynamicLen())
@ -2347,10 +2350,10 @@ mlir::LogicalResult fir::ReboxOp::verify() {
if (auto sliceVal = getSlice()) { if (auto sliceVal = getSlice()) {
// Slicing case // Slicing case
if (sliceVal.getType().cast<fir::SliceType>().getRank() != inputRank) if (mlir::cast<fir::SliceType>(sliceVal.getType()).getRank() != inputRank)
return emitOpError("slice operand rank must match box operand rank"); return emitOpError("slice operand rank must match box operand rank");
if (auto shapeVal = getShape()) { if (auto shapeVal = getShape()) {
if (auto shiftTy = shapeVal.getType().dyn_cast<fir::ShiftType>()) { if (auto shiftTy = mlir::dyn_cast<fir::ShiftType>(shapeVal.getType())) {
if (shiftTy.getRank() != inputRank) if (shiftTy.getRank() != inputRank)
return emitOpError("shape operand and input box ranks must match " return emitOpError("shape operand and input box ranks must match "
"when there is a slice"); "when there is a slice");
@ -2370,12 +2373,12 @@ mlir::LogicalResult fir::ReboxOp::verify() {
unsigned shapeRank = inputRank; unsigned shapeRank = inputRank;
if (auto shapeVal = getShape()) { if (auto shapeVal = getShape()) {
auto ty = shapeVal.getType(); auto ty = shapeVal.getType();
if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) { if (auto shapeTy = mlir::dyn_cast<fir::ShapeType>(ty)) {
shapeRank = shapeTy.getRank(); shapeRank = shapeTy.getRank();
} else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) { } else if (auto shapeShiftTy = mlir::dyn_cast<fir::ShapeShiftType>(ty)) {
shapeRank = shapeShiftTy.getRank(); shapeRank = shapeShiftTy.getRank();
} else { } else {
auto shiftTy = ty.cast<fir::ShiftType>(); auto shiftTy = mlir::cast<fir::ShiftType>(ty);
shapeRank = shiftTy.getRank(); shapeRank = shiftTy.getRank();
if (shapeRank != inputRank) if (shapeRank != inputRank)
return emitOpError("shape operand and input box ranks must match " return emitOpError("shape operand and input box ranks must match "
@ -2394,11 +2397,13 @@ mlir::LogicalResult fir::ReboxOp::verify() {
// the types is a character with dynamic length, the other type can be any // the types is a character with dynamic length, the other type can be any
// character type. // character type.
const bool typeCanMismatch = const bool typeCanMismatch =
inputEleTy.isa<fir::RecordType>() || outEleTy.isa<mlir::NoneType>() || mlir::isa<fir::RecordType>(inputEleTy) ||
(inputEleTy.isa<mlir::NoneType>() && outEleTy.isa<fir::RecordType>()) || mlir::isa<mlir::NoneType>(outEleTy) ||
(getSlice() && inputEleTy.isa<fir::CharacterType>()) || (mlir::isa<mlir::NoneType>(inputEleTy) &&
mlir::isa<fir::RecordType>(outEleTy)) ||
(getSlice() && mlir::isa<fir::CharacterType>(inputEleTy)) ||
(getSlice() && fir::isa_complex(inputEleTy) && (getSlice() && fir::isa_complex(inputEleTy) &&
outEleTy.isa<mlir::FloatType>()) || mlir::isa<mlir::FloatType>(outEleTy)) ||
areCompatibleCharacterTypes(inputEleTy, outEleTy); areCompatibleCharacterTypes(inputEleTy, outEleTy);
if (!typeCanMismatch) if (!typeCanMismatch)
return emitOpError( return emitOpError(
@ -2435,7 +2440,7 @@ mlir::LogicalResult fir::SaveResultOp::verify() {
if (fir::isa_unknown_size_box(resultType)) if (fir::isa_unknown_size_box(resultType))
return emitOpError("cannot save !fir.box of unknown rank or type"); return emitOpError("cannot save !fir.box of unknown rank or type");
if (resultType.isa<fir::BoxType>()) { if (mlir::isa<fir::BoxType>(resultType)) {
if (getShape() || !getTypeparams().empty()) if (getShape() || !getTypeparams().empty())
return emitOpError( return emitOpError(
"must not have shape or length operands if the value is a fir.box"); "must not have shape or length operands if the value is a fir.box");
@ -2446,14 +2451,14 @@ mlir::LogicalResult fir::SaveResultOp::verify() {
unsigned shapeTyRank = 0; unsigned shapeTyRank = 0;
if (auto shapeVal = getShape()) { if (auto shapeVal = getShape()) {
auto shapeTy = shapeVal.getType(); auto shapeTy = shapeVal.getType();
if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) if (auto s = mlir::dyn_cast<fir::ShapeType>(shapeTy))
shapeTyRank = s.getRank(); shapeTyRank = s.getRank();
else else
shapeTyRank = shapeTy.cast<fir::ShapeShiftType>().getRank(); shapeTyRank = mlir::cast<fir::ShapeShiftType>(shapeTy).getRank();
} }
auto eleTy = resultType; auto eleTy = resultType;
if (auto seqTy = resultType.dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(resultType)) {
if (seqTy.getDimension() != shapeTyRank) if (seqTy.getDimension() != shapeTyRank)
emitOpError("shape operand must be provided and have the value rank " emitOpError("shape operand must be provided and have the value rank "
"when the value is a fir.array"); "when the value is a fir.array");
@ -2464,11 +2469,11 @@ mlir::LogicalResult fir::SaveResultOp::verify() {
"shape operand should only be provided if the value is a fir.array"); "shape operand should only be provided if the value is a fir.array");
} }
if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) { if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy)) {
if (recTy.getNumLenParams() != getTypeparams().size()) if (recTy.getNumLenParams() != getTypeparams().size())
emitOpError("length parameters number must match with the value type " emitOpError("length parameters number must match with the value type "
"length parameters"); "length parameters");
} else if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { } else if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
if (getTypeparams().size() > 1) if (getTypeparams().size() > 1)
emitOpError("no more than one length parameter must be provided for " emitOpError("no more than one length parameter must be provided for "
"character value"); "character value");
@ -2508,7 +2513,7 @@ static mlir::LogicalResult verifyIntegralSwitchTerminator(OpT op) {
if (op.targetOffsetSize() != count) if (op.targetOffsetSize() != count)
return op.emitOpError("incorrect number of successor operand groups"); return op.emitOpError("incorrect number of successor operand groups");
for (decltype(count) i = 0; i != count; ++i) { for (decltype(count) i = 0; i != count; ++i) {
if (!cases[i].template isa<mlir::IntegerAttr, mlir::UnitAttr>()) if (!mlir::isa<mlir::IntegerAttr, mlir::UnitAttr>(cases[i]))
return op.emitOpError("invalid case alternative"); return op.emitOpError("invalid case alternative");
} }
return mlir::success(); return mlir::success();
@ -2620,7 +2625,7 @@ getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands,
*owner->getAttrDictionary().getNamed(offsetAttr); *owner->getAttrDictionary().getNamed(offsetAttr);
return getSubOperands( return getSubOperands(
pos, operands, pos, operands,
targetOffsetAttr.getValue().cast<mlir::DenseI32ArrayAttr>(), mlir::cast<mlir::DenseI32ArrayAttr>(targetOffsetAttr.getValue()),
mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr)); mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr));
} }
@ -2742,9 +2747,9 @@ mlir::ParseResult fir::SelectCaseOp::parse(mlir::OpAsmParser &parser,
parser.parseComma()) parser.parseComma())
return mlir::failure(); return mlir::failure();
attrs.push_back(attr); attrs.push_back(attr);
if (attr.dyn_cast_or_null<mlir::UnitAttr>()) { if (mlir::dyn_cast_or_null<mlir::UnitAttr>(attr)) {
argOffs.push_back(0); argOffs.push_back(0);
} else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) { } else if (mlir::dyn_cast_or_null<fir::ClosedIntervalAttr>(attr)) {
mlir::OpAsmParser::UnresolvedOperand oper1; mlir::OpAsmParser::UnresolvedOperand oper1;
mlir::OpAsmParser::UnresolvedOperand oper2; mlir::OpAsmParser::UnresolvedOperand oper2;
if (parser.parseOperand(oper1) || parser.parseComma() || if (parser.parseOperand(oper1) || parser.parseComma() ||
@ -2806,11 +2811,11 @@ void fir::SelectCaseOp::print(mlir::OpAsmPrinter &p) {
if (i) if (i)
p << ", "; p << ", ";
p << cases[i] << ", "; p << cases[i] << ", ";
if (!cases[i].isa<mlir::UnitAttr>()) { if (!mlir::isa<mlir::UnitAttr>(cases[i])) {
auto caseArgs = *getCompareOperands(i); auto caseArgs = *getCompareOperands(i);
p.printOperand(*caseArgs.begin()); p.printOperand(*caseArgs.begin());
p << ", "; p << ", ";
if (cases[i].isa<fir::ClosedIntervalAttr>()) { if (mlir::isa<fir::ClosedIntervalAttr>(cases[i])) {
p.printOperand(*(++caseArgs.begin())); p.printOperand(*(++caseArgs.begin()));
p << ", "; p << ", ";
} }
@ -2848,10 +2853,10 @@ void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
llvm::SmallVector<int32_t> operOffs; llvm::SmallVector<int32_t> operOffs;
int32_t operSize = 0; int32_t operSize = 0;
for (auto attr : compareAttrs) { for (auto attr : compareAttrs) {
if (attr.isa<fir::ClosedIntervalAttr>()) { if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
operOffs.push_back(2); operOffs.push_back(2);
operSize += 2; operSize += 2;
} else if (attr.isa<mlir::UnitAttr>()) { } else if (mlir::isa<mlir::UnitAttr>(attr)) {
operOffs.push_back(0); operOffs.push_back(0);
} else { } else {
operOffs.push_back(1); operOffs.push_back(1);
@ -2900,10 +2905,10 @@ void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
llvm::SmallVector<mlir::ValueRange> cmpOpers; llvm::SmallVector<mlir::ValueRange> cmpOpers;
auto iter = cmpOpList.begin(); auto iter = cmpOpList.begin();
for (auto &attr : compareAttrs) { for (auto &attr : compareAttrs) {
if (attr.isa<fir::ClosedIntervalAttr>()) { if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
cmpOpers.push_back(mlir::ValueRange({iter, iter + 2})); cmpOpers.push_back(mlir::ValueRange({iter, iter + 2}));
iter += 2; iter += 2;
} else if (attr.isa<mlir::UnitAttr>()) { } else if (mlir::isa<mlir::UnitAttr>(attr)) {
cmpOpers.push_back(mlir::ValueRange{}); cmpOpers.push_back(mlir::ValueRange{});
} else { } else {
cmpOpers.push_back(mlir::ValueRange({iter, iter + 1})); cmpOpers.push_back(mlir::ValueRange({iter, iter + 1}));
@ -2915,10 +2920,8 @@ void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
} }
mlir::LogicalResult fir::SelectCaseOp::verify() { mlir::LogicalResult fir::SelectCaseOp::verify() {
if (!getSelector() if (!mlir::isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType,
.getType() fir::LogicalType, fir::CharacterType>(getSelector().getType()))
.isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType,
fir::LogicalType, fir::CharacterType>())
return emitOpError("must be an integer, character, or logical"); return emitOpError("must be an integer, character, or logical");
auto cases = auto cases =
getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue(); getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
@ -2933,9 +2936,11 @@ mlir::LogicalResult fir::SelectCaseOp::verify() {
return emitOpError("incorrect number of successor operand groups"); return emitOpError("incorrect number of successor operand groups");
for (decltype(count) i = 0; i != count; ++i) { for (decltype(count) i = 0; i != count; ++i) {
auto &attr = cases[i]; auto &attr = cases[i];
if (!(attr.isa<fir::PointIntervalAttr>() || if (!(mlir::isa<fir::PointIntervalAttr>(attr) ||
attr.isa<fir::LowerBoundAttr>() || attr.isa<fir::UpperBoundAttr>() || mlir::isa<fir::LowerBoundAttr>(attr) ||
attr.isa<fir::ClosedIntervalAttr>() || attr.isa<mlir::UnitAttr>())) mlir::isa<fir::UpperBoundAttr>(attr) ||
mlir::isa<fir::ClosedIntervalAttr>(attr) ||
mlir::isa<mlir::UnitAttr>(attr)))
return emitOpError("incorrect select case attribute type"); return emitOpError("incorrect select case attribute type");
} }
return mlir::success(); return mlir::success();
@ -3111,14 +3116,14 @@ void fir::SelectTypeOp::print(mlir::OpAsmPrinter &p) {
} }
mlir::LogicalResult fir::SelectTypeOp::verify() { mlir::LogicalResult fir::SelectTypeOp::verify() {
if (!(getSelector().getType().isa<fir::BaseBoxType>())) if (!mlir::isa<fir::BaseBoxType>(getSelector().getType()))
return emitOpError("must be a fir.class or fir.box type"); return emitOpError("must be a fir.class or fir.box type");
if (auto boxType = getSelector().getType().dyn_cast<fir::BoxType>()) if (auto boxType = mlir::dyn_cast<fir::BoxType>(getSelector().getType()))
if (!boxType.getEleTy().isa<mlir::NoneType>()) if (!mlir::isa<mlir::NoneType>(boxType.getEleTy()))
return emitOpError("selector must be polymorphic"); return emitOpError("selector must be polymorphic");
auto typeGuardAttr = getCases(); auto typeGuardAttr = getCases();
for (unsigned idx = 0; idx < typeGuardAttr.size(); ++idx) for (unsigned idx = 0; idx < typeGuardAttr.size(); ++idx)
if (typeGuardAttr[idx].isa<mlir::UnitAttr>() && if (mlir::isa<mlir::UnitAttr>(typeGuardAttr[idx]) &&
idx != typeGuardAttr.size() - 1) idx != typeGuardAttr.size() - 1)
return emitOpError("default must be the last attribute"); return emitOpError("default must be the last attribute");
auto count = getNumDest(); auto count = getNumDest();
@ -3129,9 +3134,8 @@ mlir::LogicalResult fir::SelectTypeOp::verify() {
if (targetOffsetSize() != count) if (targetOffsetSize() != count)
return emitOpError("incorrect number of successor operand groups"); return emitOpError("incorrect number of successor operand groups");
for (unsigned i = 0; i != count; ++i) { for (unsigned i = 0; i != count; ++i) {
if (!(typeGuardAttr[i].isa<fir::ExactTypeAttr>() || if (!mlir::isa<fir::ExactTypeAttr, fir::SubclassAttr, mlir::UnitAttr>(
typeGuardAttr[i].isa<fir::SubclassAttr>() || typeGuardAttr[i]))
typeGuardAttr[i].isa<mlir::UnitAttr>()))
return emitOpError("invalid type-case alternative"); return emitOpError("invalid type-case alternative");
} }
return mlir::success(); return mlir::success();
@ -3175,7 +3179,7 @@ void fir::SelectTypeOp::build(mlir::OpBuilder &builder,
mlir::LogicalResult fir::ShapeOp::verify() { mlir::LogicalResult fir::ShapeOp::verify() {
auto size = getExtents().size(); auto size = getExtents().size();
auto shapeTy = getType().dyn_cast<fir::ShapeType>(); auto shapeTy = mlir::dyn_cast<fir::ShapeType>(getType());
assert(shapeTy && "must be a shape type"); assert(shapeTy && "must be a shape type");
if (shapeTy.getRank() != size) if (shapeTy.getRank() != size)
return emitOpError("shape type rank mismatch"); return emitOpError("shape type rank mismatch");
@ -3198,7 +3202,7 @@ mlir::LogicalResult fir::ShapeShiftOp::verify() {
return emitOpError("incorrect number of args"); return emitOpError("incorrect number of args");
if (size % 2 != 0) if (size % 2 != 0)
return emitOpError("requires a multiple of 2 args"); return emitOpError("requires a multiple of 2 args");
auto shapeTy = getType().dyn_cast<fir::ShapeShiftType>(); auto shapeTy = mlir::dyn_cast<fir::ShapeShiftType>(getType());
assert(shapeTy && "must be a shape shift type"); assert(shapeTy && "must be a shape shift type");
if (shapeTy.getRank() * 2 != size) if (shapeTy.getRank() * 2 != size)
return emitOpError("shape type rank mismatch"); return emitOpError("shape type rank mismatch");
@ -3211,7 +3215,7 @@ mlir::LogicalResult fir::ShapeShiftOp::verify() {
mlir::LogicalResult fir::ShiftOp::verify() { mlir::LogicalResult fir::ShiftOp::verify() {
auto size = getOrigins().size(); auto size = getOrigins().size();
auto shiftTy = getType().dyn_cast<fir::ShiftType>(); auto shiftTy = mlir::dyn_cast<fir::ShiftType>(getType());
assert(shiftTy && "must be a shift type"); assert(shiftTy && "must be a shift type");
if (shiftTy.getRank() != size) if (shiftTy.getRank() != size)
return emitOpError("shift type rank mismatch"); return emitOpError("shift type rank mismatch");
@ -3251,7 +3255,7 @@ mlir::LogicalResult fir::SliceOp::verify() {
return emitOpError("incorrect number of args for triple"); return emitOpError("incorrect number of args for triple");
if (size % 3 != 0) if (size % 3 != 0)
return emitOpError("requires a multiple of 3 args"); return emitOpError("requires a multiple of 3 args");
auto sliceTy = getType().dyn_cast<fir::SliceType>(); auto sliceTy = mlir::dyn_cast<fir::SliceType>(getType());
assert(sliceTy && "must be a slice type"); assert(sliceTy && "must be a slice type");
if (sliceTy.getRank() * 3 != size) if (sliceTy.getRank() * 3 != size)
return emitOpError("slice type rank mismatch"); return emitOpError("slice type rank mismatch");
@ -3309,8 +3313,8 @@ void fir::StoreOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
inline fir::CharacterType::KindTy stringLitOpGetKind(fir::StringLitOp op) { inline fir::CharacterType::KindTy stringLitOpGetKind(fir::StringLitOp op) {
auto eleTy = op.getType().cast<fir::SequenceType>().getEleTy(); auto eleTy = mlir::cast<fir::SequenceType>(op.getType()).getEleTy();
return eleTy.cast<fir::CharacterType>().getFKind(); return mlir::cast<fir::CharacterType>(eleTy).getFKind();
} }
bool fir::StringLitOp::isWideValue() { return stringLitOpGetKind(*this) != 1; } bool fir::StringLitOp::isWideValue() { return stringLitOpGetKind(*this) != 1; }
@ -3390,13 +3394,13 @@ mlir::ParseResult fir::StringLitOp::parse(mlir::OpAsmParser &parser,
llvm::SMLoc trailingTypeLoc; llvm::SMLoc trailingTypeLoc;
if (parser.parseAttribute(val, "fake", attrs)) if (parser.parseAttribute(val, "fake", attrs))
return mlir::failure(); return mlir::failure();
if (auto v = val.dyn_cast<mlir::StringAttr>()) if (auto v = mlir::dyn_cast<mlir::StringAttr>(val))
result.attributes.push_back( result.attributes.push_back(
builder.getNamedAttr(fir::StringLitOp::value(), v)); builder.getNamedAttr(fir::StringLitOp::value(), v));
else if (auto v = val.dyn_cast<mlir::DenseElementsAttr>()) else if (auto v = mlir::dyn_cast<mlir::DenseElementsAttr>(val))
result.attributes.push_back( result.attributes.push_back(
builder.getNamedAttr(fir::StringLitOp::xlist(), v)); builder.getNamedAttr(fir::StringLitOp::xlist(), v));
else if (auto v = val.dyn_cast<mlir::ArrayAttr>()) else if (auto v = mlir::dyn_cast<mlir::ArrayAttr>(val))
result.attributes.push_back( result.attributes.push_back(
builder.getNamedAttr(fir::StringLitOp::xlist(), v)); builder.getNamedAttr(fir::StringLitOp::xlist(), v));
else else
@ -3409,7 +3413,7 @@ mlir::ParseResult fir::StringLitOp::parse(mlir::OpAsmParser &parser,
parser.parseRParen() || parser.getCurrentLocation(&trailingTypeLoc) || parser.parseRParen() || parser.getCurrentLocation(&trailingTypeLoc) ||
parser.parseColonType(type)) parser.parseColonType(type))
return mlir::failure(); return mlir::failure();
auto charTy = type.dyn_cast<fir::CharacterType>(); auto charTy = mlir::dyn_cast<fir::CharacterType>(type);
if (!charTy) if (!charTy)
return parser.emitError(trailingTypeLoc, "must have character type"); return parser.emitError(trailingTypeLoc, "must have character type");
type = fir::CharacterType::get(builder.getContext(), charTy.getFKind(), type = fir::CharacterType::get(builder.getContext(), charTy.getFKind(),
@ -3421,19 +3425,19 @@ mlir::ParseResult fir::StringLitOp::parse(mlir::OpAsmParser &parser,
void fir::StringLitOp::print(mlir::OpAsmPrinter &p) { void fir::StringLitOp::print(mlir::OpAsmPrinter &p) {
p << ' ' << getValue() << '('; p << ' ' << getValue() << '(';
p << getSize().cast<mlir::IntegerAttr>().getValue() << ") : "; p << mlir::cast<mlir::IntegerAttr>(getSize()).getValue() << ") : ";
p.printType(getType()); p.printType(getType());
} }
mlir::LogicalResult fir::StringLitOp::verify() { mlir::LogicalResult fir::StringLitOp::verify() {
if (getSize().cast<mlir::IntegerAttr>().getValue().isNegative()) if (mlir::cast<mlir::IntegerAttr>(getSize()).getValue().isNegative())
return emitOpError("size must be non-negative"); return emitOpError("size must be non-negative");
if (auto xl = getOperation()->getAttr(fir::StringLitOp::xlist())) { if (auto xl = getOperation()->getAttr(fir::StringLitOp::xlist())) {
if (auto xList = xl.dyn_cast<mlir::ArrayAttr>()) { if (auto xList = mlir::dyn_cast<mlir::ArrayAttr>(xl)) {
for (auto a : xList) for (auto a : xList)
if (!a.isa<mlir::IntegerAttr>()) if (!mlir::isa<mlir::IntegerAttr>(a))
return emitOpError("values in initializer must be integers"); return emitOpError("values in initializer must be integers");
} else if (xl.isa<mlir::DenseElementsAttr>()) { } else if (mlir::isa<mlir::DenseElementsAttr>(xl)) {
// do nothing // do nothing
} else { } else {
return emitOpError("has unexpected attribute"); return emitOpError("has unexpected attribute");
@ -3448,7 +3452,7 @@ mlir::LogicalResult fir::StringLitOp::verify() {
mlir::LogicalResult fir::UnboxProcOp::verify() { mlir::LogicalResult fir::UnboxProcOp::verify() {
if (auto eleTy = fir::dyn_cast_ptrEleTy(getRefTuple().getType())) if (auto eleTy = fir::dyn_cast_ptrEleTy(getRefTuple().getType()))
if (eleTy.isa<mlir::TupleType>()) if (mlir::isa<mlir::TupleType>(eleTy))
return mlir::success(); return mlir::success();
return emitOpError("second output argument has bad type"); return emitOpError("second output argument has bad type");
} }
@ -3527,7 +3531,7 @@ void fir::IfOp::getEntrySuccessorRegions(
void fir::IfOp::getRegionInvocationBounds( void fir::IfOp::getRegionInvocationBounds(
llvm::ArrayRef<mlir::Attribute> operands, llvm::ArrayRef<mlir::Attribute> operands,
llvm::SmallVectorImpl<mlir::InvocationBounds> &invocationBounds) { llvm::SmallVectorImpl<mlir::InvocationBounds> &invocationBounds) {
if (auto cond = operands[0].dyn_cast_or_null<mlir::BoolAttr>()) { if (auto cond = mlir::dyn_cast_or_null<mlir::BoolAttr>(operands[0])) {
// If the condition is known, then one region is known to be executed once // If the condition is known, then one region is known to be executed once
// and the other zero times. // and the other zero times.
invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0); invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
@ -3646,8 +3650,8 @@ void fir::BoxOffsetOp::build(mlir::OpBuilder &builder,
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) { mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) {
if (attr.isa<mlir::UnitAttr, fir::ClosedIntervalAttr, fir::PointIntervalAttr, if (mlir::isa<mlir::UnitAttr, fir::ClosedIntervalAttr, fir::PointIntervalAttr,
fir::LowerBoundAttr, fir::UpperBoundAttr>()) fir::LowerBoundAttr, fir::UpperBoundAttr>(attr))
return mlir::success(); return mlir::success();
return mlir::failure(); return mlir::failure();
} }
@ -3657,9 +3661,9 @@ unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,
unsigned o = 0; unsigned o = 0;
for (unsigned i = 0; i < dest; ++i) { for (unsigned i = 0; i < dest; ++i) {
auto &attr = cases[i]; auto &attr = cases[i];
if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) { if (!mlir::dyn_cast_or_null<mlir::UnitAttr>(attr)) {
++o; ++o;
if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) if (mlir::dyn_cast_or_null<fir::ClosedIntervalAttr>(attr))
++o; ++o;
} }
} }
@ -3722,7 +3726,7 @@ fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module,
bool fir::hasHostAssociationArgument(mlir::func::FuncOp func) { bool fir::hasHostAssociationArgument(mlir::func::FuncOp func) {
if (auto allArgAttrs = func.getAllArgAttrs()) if (auto allArgAttrs = func.getAllArgAttrs())
for (auto attr : allArgAttrs) for (auto attr : allArgAttrs)
if (auto dict = attr.template dyn_cast_or_null<mlir::DictionaryAttr>()) if (auto dict = mlir::dyn_cast_or_null<mlir::DictionaryAttr>(attr))
if (dict.get(fir::getHostAssocAttrName())) if (dict.get(fir::getHostAssocAttrName()))
return true; return true;
return false; return false;
@ -3772,7 +3776,7 @@ valueCheckFirAttributes(mlir::Value value,
}; };
// If this is a fir.box that was loaded, the fir attributes will be on the // If this is a fir.box that was loaded, the fir attributes will be on the
// related fir.ref<fir.box> creation. // related fir.ref<fir.box> creation.
if (value.getType().isa<fir::BoxType>()) if (mlir::isa<fir::BoxType>(value.getType()))
if (auto definingOp = value.getDefiningOp()) if (auto definingOp = value.getDefiningOp())
if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp)) if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp))
value = loadOp.getMemref(); value = loadOp.getMemref();
@ -3837,10 +3841,10 @@ bool fir::anyFuncArgsHaveAttr(mlir::func::FuncOp func, llvm::StringRef attr) {
std::optional<std::int64_t> fir::getIntIfConstant(mlir::Value value) { std::optional<std::int64_t> fir::getIntIfConstant(mlir::Value value) {
if (auto *definingOp = value.getDefiningOp()) { if (auto *definingOp = value.getDefiningOp()) {
if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp)) if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp))
if (auto intAttr = cst.getValue().dyn_cast<mlir::IntegerAttr>()) if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(cst.getValue()))
return intAttr.getInt(); return intAttr.getInt();
if (auto llConstOp = mlir::dyn_cast<mlir::LLVM::ConstantOp>(definingOp)) if (auto llConstOp = mlir::dyn_cast<mlir::LLVM::ConstantOp>(definingOp))
if (auto attr = llConstOp.getValue().dyn_cast<mlir::IntegerAttr>()) if (auto attr = mlir::dyn_cast<mlir::IntegerAttr>(llConstOp.getValue()))
return attr.getValue().getSExtValue(); return attr.getValue().getSExtValue();
} }
return {}; return {};
@ -4002,15 +4006,15 @@ mlir::LogicalResult fir::CUDAKernelOp::verify() {
mlir::LogicalResult fir::CUDAAllocateOp::verify() { mlir::LogicalResult fir::CUDAAllocateOp::verify() {
if (getPinned() && getStream()) if (getPinned() && getStream())
return emitOpError("pinned and stream cannot appears at the same time"); return emitOpError("pinned and stream cannot appears at the same time");
if (!fir::unwrapRefType(getBox().getType()).isa<fir::BaseBoxType>()) if (!mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(getBox().getType())))
return emitOpError( return emitOpError(
"expect box to be a reference to a class or box type value"); "expect box to be a reference to a class or box type value");
if (getSource() && if (getSource() &&
!fir::unwrapRefType(getSource().getType()).isa<fir::BaseBoxType>()) !mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(getSource().getType())))
return emitOpError( return emitOpError(
"expect source to be a reference to/or a class or box type value"); "expect source to be a reference to/or a class or box type value");
if (getErrmsg() && if (getErrmsg() &&
!fir::unwrapRefType(getErrmsg().getType()).isa<fir::BoxType>()) !mlir::isa<fir::BoxType>(fir::unwrapRefType(getErrmsg().getType())))
return emitOpError( return emitOpError(
"expect errmsg to be a reference to/or a box type value"); "expect errmsg to be a reference to/or a box type value");
if (getErrmsg() && !getHasStat()) if (getErrmsg() && !getHasStat())
@ -4019,11 +4023,11 @@ mlir::LogicalResult fir::CUDAAllocateOp::verify() {
} }
mlir::LogicalResult fir::CUDADeallocateOp::verify() { mlir::LogicalResult fir::CUDADeallocateOp::verify() {
if (!fir::unwrapRefType(getBox().getType()).isa<fir::BaseBoxType>()) if (!mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(getBox().getType())))
return emitOpError( return emitOpError(
"expect box to be a reference to class or box type value"); "expect box to be a reference to class or box type value");
if (getErrmsg() && if (getErrmsg() &&
!fir::unwrapRefType(getErrmsg().getType()).isa<fir::BoxType>()) !mlir::isa<fir::BoxType>(fir::unwrapRefType(getErrmsg().getType())))
return emitOpError( return emitOpError(
"expect errmsg to be a reference to/or a box type value"); "expect errmsg to be a reference to/or a box type value");
if (getErrmsg() && !getHasStat()) if (getErrmsg() && !getHasStat())

View File

@ -61,14 +61,13 @@ TYPE parseTypeSingleton(mlir::AsmParser &parser) {
/// Is `ty` a standard or FIR integer type? /// Is `ty` a standard or FIR integer type?
static bool isaIntegerType(mlir::Type ty) { static bool isaIntegerType(mlir::Type ty) {
// TODO: why aren't we using isa_integer? investigatation required. // TODO: why aren't we using isa_integer? investigatation required.
return ty.isa<mlir::IntegerType>() || ty.isa<fir::IntegerType>(); return mlir::isa<mlir::IntegerType, fir::IntegerType>(ty);
} }
bool verifyRecordMemberType(mlir::Type ty) { bool verifyRecordMemberType(mlir::Type ty) {
return !(ty.isa<BoxCharType>() || ty.isa<ShapeType>() || return !mlir::isa<BoxCharType, ShapeType, ShapeShiftType, ShiftType,
ty.isa<ShapeShiftType>() || ty.isa<ShiftType>() || SliceType, FieldType, LenType, ReferenceType, TypeDescType>(
ty.isa<SliceType>() || ty.isa<FieldType>() || ty.isa<LenType>() || ty);
ty.isa<ReferenceType>() || ty.isa<TypeDescType>());
} }
bool verifySameLists(llvm::ArrayRef<RecordType::TypePair> a1, bool verifySameLists(llvm::ArrayRef<RecordType::TypePair> a1,
@ -194,7 +193,7 @@ bool isa_std_type(mlir::Type t) {
} }
bool isa_fir_or_std_type(mlir::Type t) { bool isa_fir_or_std_type(mlir::Type t) {
if (auto funcType = t.dyn_cast<mlir::FunctionType>()) if (auto funcType = mlir::dyn_cast<mlir::FunctionType>(t))
return llvm::all_of(funcType.getInputs(), isa_fir_or_std_type) && return llvm::all_of(funcType.getInputs(), isa_fir_or_std_type) &&
llvm::all_of(funcType.getResults(), isa_fir_or_std_type); llvm::all_of(funcType.getResults(), isa_fir_or_std_type);
return isa_fir_type(t) || isa_std_type(t); return isa_fir_type(t) || isa_std_type(t);
@ -203,7 +202,7 @@ bool isa_fir_or_std_type(mlir::Type t) {
mlir::Type getDerivedType(mlir::Type ty) { mlir::Type getDerivedType(mlir::Type ty) {
return llvm::TypeSwitch<mlir::Type, mlir::Type>(ty) return llvm::TypeSwitch<mlir::Type, mlir::Type>(ty)
.Case<fir::PointerType, fir::HeapType, fir::SequenceType>([](auto p) { .Case<fir::PointerType, fir::HeapType, fir::SequenceType>([](auto p) {
if (auto seq = p.getEleTy().template dyn_cast<fir::SequenceType>()) if (auto seq = mlir::dyn_cast<fir::SequenceType>(p.getEleTy()))
return seq.getEleTy(); return seq.getEleTy();
return p.getEleTy(); return p.getEleTy();
}) })
@ -228,12 +227,12 @@ mlir::Type dyn_cast_ptrOrBoxEleTy(mlir::Type t) {
static bool hasDynamicSize(fir::RecordType recTy) { static bool hasDynamicSize(fir::RecordType recTy) {
for (auto field : recTy.getTypeList()) { for (auto field : recTy.getTypeList()) {
if (auto arr = field.second.dyn_cast<fir::SequenceType>()) { if (auto arr = mlir::dyn_cast<fir::SequenceType>(field.second)) {
if (sequenceWithNonConstantShape(arr)) if (sequenceWithNonConstantShape(arr))
return true; return true;
} else if (characterWithDynamicLen(field.second)) { } else if (characterWithDynamicLen(field.second)) {
return true; return true;
} else if (auto rec = field.second.dyn_cast<fir::RecordType>()) { } else if (auto rec = mlir::dyn_cast<fir::RecordType>(field.second)) {
if (hasDynamicSize(rec)) if (hasDynamicSize(rec))
return true; return true;
} }
@ -242,14 +241,14 @@ static bool hasDynamicSize(fir::RecordType recTy) {
} }
bool hasDynamicSize(mlir::Type t) { bool hasDynamicSize(mlir::Type t) {
if (auto arr = t.dyn_cast<fir::SequenceType>()) { if (auto arr = mlir::dyn_cast<fir::SequenceType>(t)) {
if (sequenceWithNonConstantShape(arr)) if (sequenceWithNonConstantShape(arr))
return true; return true;
t = arr.getEleTy(); t = arr.getEleTy();
} }
if (characterWithDynamicLen(t)) if (characterWithDynamicLen(t))
return true; return true;
if (auto rec = t.dyn_cast<fir::RecordType>()) if (auto rec = mlir::dyn_cast<fir::RecordType>(t))
return hasDynamicSize(rec); return hasDynamicSize(rec);
return false; return false;
} }
@ -269,33 +268,33 @@ mlir::Type extractSequenceType(mlir::Type ty) {
bool isPointerType(mlir::Type ty) { bool isPointerType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty)) if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy; ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty))
return boxTy.getEleTy().isa<fir::PointerType>(); return mlir::isa<fir::PointerType>(boxTy.getEleTy());
return false; return false;
} }
bool isAllocatableType(mlir::Type ty) { bool isAllocatableType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty)) if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy; ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty))
return boxTy.getEleTy().isa<fir::HeapType>(); return mlir::isa<fir::HeapType>(boxTy.getEleTy());
return false; return false;
} }
bool isBoxNone(mlir::Type ty) { bool isBoxNone(mlir::Type ty) {
if (auto box = ty.dyn_cast<fir::BoxType>()) if (auto box = mlir::dyn_cast<fir::BoxType>(ty))
return box.getEleTy().isa<mlir::NoneType>(); return mlir::isa<mlir::NoneType>(box.getEleTy());
return false; return false;
} }
bool isBoxedRecordType(mlir::Type ty) { bool isBoxedRecordType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty)) if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy; ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BoxType>(ty)) {
if (boxTy.getEleTy().isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(boxTy.getEleTy()))
return true; return true;
mlir::Type innerType = boxTy.unwrapInnerType(); mlir::Type innerType = boxTy.unwrapInnerType();
return innerType && innerType.isa<fir::RecordType>(); return innerType && mlir::isa<fir::RecordType>(innerType);
} }
return false; return false;
} }
@ -303,13 +302,13 @@ bool isBoxedRecordType(mlir::Type ty) {
bool isScalarBoxedRecordType(mlir::Type ty) { bool isScalarBoxedRecordType(mlir::Type ty) {
if (auto refTy = fir::dyn_cast_ptrEleTy(ty)) if (auto refTy = fir::dyn_cast_ptrEleTy(ty))
ty = refTy; ty = refTy;
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
if (boxTy.getEleTy().isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(boxTy.getEleTy()))
return true; return true;
if (auto heapTy = boxTy.getEleTy().dyn_cast<fir::HeapType>()) if (auto heapTy = mlir::dyn_cast<fir::HeapType>(boxTy.getEleTy()))
return heapTy.getEleTy().isa<fir::RecordType>(); return mlir::isa<fir::RecordType>(heapTy.getEleTy());
if (auto ptrTy = boxTy.getEleTy().dyn_cast<fir::PointerType>()) if (auto ptrTy = mlir::dyn_cast<fir::PointerType>(boxTy.getEleTy()))
return ptrTy.getEleTy().isa<fir::RecordType>(); return mlir::isa<fir::RecordType>(ptrTy.getEleTy());
} }
return false; return false;
} }
@ -363,10 +362,10 @@ bool isPolymorphicType(mlir::Type ty) {
bool isUnlimitedPolymorphicType(mlir::Type ty) { bool isUnlimitedPolymorphicType(mlir::Type ty) {
// CLASS(*) // CLASS(*)
if (auto clTy = mlir::dyn_cast<fir::ClassType>(fir::unwrapRefType(ty))) { if (auto clTy = mlir::dyn_cast<fir::ClassType>(fir::unwrapRefType(ty))) {
if (clTy.getEleTy().isa<mlir::NoneType>()) if (mlir::isa<mlir::NoneType>(clTy.getEleTy()))
return true; return true;
mlir::Type innerType = clTy.unwrapInnerType(); mlir::Type innerType = clTy.unwrapInnerType();
return innerType && innerType.isa<mlir::NoneType>(); return innerType && mlir::isa<mlir::NoneType>(innerType);
} }
// TYPE(*) // TYPE(*)
return isAssumedType(ty); return isAssumedType(ty);
@ -376,7 +375,7 @@ mlir::Type unwrapInnerType(mlir::Type ty) {
return llvm::TypeSwitch<mlir::Type, mlir::Type>(ty) return llvm::TypeSwitch<mlir::Type, mlir::Type>(ty)
.Case<fir::PointerType, fir::HeapType, fir::SequenceType>([](auto t) { .Case<fir::PointerType, fir::HeapType, fir::SequenceType>([](auto t) {
mlir::Type eleTy = t.getEleTy(); mlir::Type eleTy = t.getEleTy();
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
return seqTy.getEleTy(); return seqTy.getEleTy();
return eleTy; return eleTy;
}) })
@ -385,13 +384,14 @@ mlir::Type unwrapInnerType(mlir::Type ty) {
} }
bool isRecordWithAllocatableMember(mlir::Type ty) { bool isRecordWithAllocatableMember(mlir::Type ty) {
if (auto recTy = ty.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(ty))
for (auto [field, memTy] : recTy.getTypeList()) { for (auto [field, memTy] : recTy.getTypeList()) {
if (fir::isAllocatableType(memTy)) if (fir::isAllocatableType(memTy))
return true; return true;
// A record type cannot recursively include itself as a direct member. // A record type cannot recursively include itself as a direct member.
// There must be an intervening `ptr` type, so recursion is safe here. // There must be an intervening `ptr` type, so recursion is safe here.
if (memTy.isa<fir::RecordType>() && isRecordWithAllocatableMember(memTy)) if (mlir::isa<fir::RecordType>(memTy) &&
isRecordWithAllocatableMember(memTy))
return true; return true;
} }
return false; return false;
@ -399,11 +399,12 @@ bool isRecordWithAllocatableMember(mlir::Type ty) {
bool isRecordWithDescriptorMember(mlir::Type ty) { bool isRecordWithDescriptorMember(mlir::Type ty) {
ty = unwrapSequenceType(ty); ty = unwrapSequenceType(ty);
if (auto recTy = ty.dyn_cast<fir::RecordType>()) if (auto recTy = mlir::dyn_cast<fir::RecordType>(ty))
for (auto [field, memTy] : recTy.getTypeList()) { for (auto [field, memTy] : recTy.getTypeList()) {
if (mlir::isa<fir::BaseBoxType>(memTy)) if (mlir::isa<fir::BaseBoxType>(memTy))
return true; return true;
if (memTy.isa<fir::RecordType>() && isRecordWithDescriptorMember(memTy)) if (mlir::isa<fir::RecordType>(memTy) &&
isRecordWithDescriptorMember(memTy))
return true; return true;
} }
return false; return false;
@ -412,7 +413,7 @@ bool isRecordWithDescriptorMember(mlir::Type ty) {
mlir::Type unwrapAllRefAndSeqType(mlir::Type ty) { mlir::Type unwrapAllRefAndSeqType(mlir::Type ty) {
while (true) { while (true) {
mlir::Type nt = unwrapSequenceType(unwrapRefType(ty)); mlir::Type nt = unwrapSequenceType(unwrapRefType(ty));
if (auto vecTy = nt.dyn_cast<fir::VectorType>()) if (auto vecTy = mlir::dyn_cast<fir::VectorType>(nt))
nt = vecTy.getEleTy(); nt = vecTy.getEleTy();
if (nt == ty) if (nt == ty)
return ty; return ty;
@ -421,11 +422,11 @@ mlir::Type unwrapAllRefAndSeqType(mlir::Type ty) {
} }
mlir::Type unwrapSeqOrBoxedSeqType(mlir::Type ty) { mlir::Type unwrapSeqOrBoxedSeqType(mlir::Type ty) {
if (auto seqTy = ty.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
return seqTy.getEleTy(); return seqTy.getEleTy();
if (auto boxTy = ty.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
auto eleTy = unwrapRefType(boxTy.getEleTy()); auto eleTy = unwrapRefType(boxTy.getEleTy());
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
return seqTy.getEleTy(); return seqTy.getEleTy();
} }
return ty; return ty;
@ -433,7 +434,7 @@ mlir::Type unwrapSeqOrBoxedSeqType(mlir::Type ty) {
unsigned getBoxRank(mlir::Type boxTy) { unsigned getBoxRank(mlir::Type boxTy) {
auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy); auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
return seqTy.getDimension(); return seqTy.getDimension();
return 0; return 0;
} }
@ -441,7 +442,7 @@ unsigned getBoxRank(mlir::Type boxTy) {
/// Return the ISO_C_BINDING intrinsic module value of type \p ty. /// Return the ISO_C_BINDING intrinsic module value of type \p ty.
int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) { int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
unsigned width = 0; unsigned width = 0;
if (mlir::IntegerType intTy = ty.dyn_cast<mlir::IntegerType>()) { if (mlir::IntegerType intTy = mlir::dyn_cast<mlir::IntegerType>(ty)) {
switch (intTy.getWidth()) { switch (intTy.getWidth()) {
case 8: case 8:
return CFI_type_int8_t; return CFI_type_int8_t;
@ -456,7 +457,7 @@ int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
} }
llvm_unreachable("unsupported integer type"); llvm_unreachable("unsupported integer type");
} }
if (fir::LogicalType logicalTy = ty.dyn_cast<fir::LogicalType>()) { if (fir::LogicalType logicalTy = mlir::dyn_cast<fir::LogicalType>(ty)) {
switch (kindMap.getLogicalBitsize(logicalTy.getFKind())) { switch (kindMap.getLogicalBitsize(logicalTy.getFKind())) {
case 8: case 8:
return CFI_type_Bool; return CFI_type_Bool;
@ -469,7 +470,7 @@ int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
} }
llvm_unreachable("unsupported logical type"); llvm_unreachable("unsupported logical type");
} }
if (mlir::FloatType floatTy = ty.dyn_cast<mlir::FloatType>()) { if (mlir::FloatType floatTy = mlir::dyn_cast<mlir::FloatType>(ty)) {
switch (floatTy.getWidth()) { switch (floatTy.getWidth()) {
case 16: case 16:
return floatTy.isBF16() ? CFI_type_bfloat : CFI_type_half_float; return floatTy.isBF16() ? CFI_type_bfloat : CFI_type_half_float;
@ -485,13 +486,14 @@ int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
llvm_unreachable("unsupported real type"); llvm_unreachable("unsupported real type");
} }
if (fir::isa_complex(ty)) { if (fir::isa_complex(ty)) {
if (mlir::ComplexType complexTy = ty.dyn_cast<mlir::ComplexType>()) { if (mlir::ComplexType complexTy = mlir::dyn_cast<mlir::ComplexType>(ty)) {
mlir::FloatType floatTy = mlir::FloatType floatTy =
complexTy.getElementType().cast<mlir::FloatType>(); mlir::cast<mlir::FloatType>(complexTy.getElementType());
if (floatTy.isBF16()) if (floatTy.isBF16())
return CFI_type_bfloat_Complex; return CFI_type_bfloat_Complex;
width = floatTy.getWidth(); width = floatTy.getWidth();
} else if (fir::ComplexType complexTy = ty.dyn_cast<fir::ComplexType>()) { } else if (fir::ComplexType complexTy =
mlir::dyn_cast<fir::ComplexType>(ty)) {
auto FKind = complexTy.getFKind(); auto FKind = complexTy.getFKind();
if (FKind == 3) if (FKind == 3)
return CFI_type_bfloat_Complex; return CFI_type_bfloat_Complex;
@ -511,7 +513,7 @@ int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
} }
llvm_unreachable("unsupported complex size"); llvm_unreachable("unsupported complex size");
} }
if (fir::CharacterType charTy = ty.dyn_cast<fir::CharacterType>()) { if (fir::CharacterType charTy = mlir::dyn_cast<fir::CharacterType>(ty)) {
switch (kindMap.getCharacterBitsize(charTy.getFKind())) { switch (kindMap.getCharacterBitsize(charTy.getFKind())) {
case 8: case 8:
return CFI_type_char; return CFI_type_char;
@ -524,7 +526,7 @@ int getTypeCode(mlir::Type ty, const fir::KindMapping &kindMap) {
} }
if (fir::isa_ref_type(ty)) if (fir::isa_ref_type(ty))
return CFI_type_cptr; return CFI_type_cptr;
if (ty.isa<fir::RecordType>()) if (mlir::isa<fir::RecordType>(ty))
return CFI_type_struct; return CFI_type_struct;
llvm_unreachable("unsupported type"); llvm_unreachable("unsupported type");
} }
@ -542,12 +544,12 @@ std::string getTypeAsString(mlir::Type ty, const fir::KindMapping &kindMap,
name << "idx"; name << "idx";
} else if (ty.isIntOrIndex()) { } else if (ty.isIntOrIndex()) {
name << 'i' << ty.getIntOrFloatBitWidth(); name << 'i' << ty.getIntOrFloatBitWidth();
} else if (ty.isa<mlir::FloatType>()) { } else if (mlir::isa<mlir::FloatType>(ty)) {
name << 'f' << ty.getIntOrFloatBitWidth(); name << 'f' << ty.getIntOrFloatBitWidth();
} else if (fir::isa_complex(ty)) { } else if (fir::isa_complex(ty)) {
name << 'z'; name << 'z';
if (auto cplxTy = mlir::dyn_cast_or_null<mlir::ComplexType>(ty)) { if (auto cplxTy = mlir::dyn_cast_or_null<mlir::ComplexType>(ty)) {
auto floatTy = cplxTy.getElementType().cast<mlir::FloatType>(); auto floatTy = mlir::cast<mlir::FloatType>(cplxTy.getElementType());
name << floatTy.getWidth(); name << floatTy.getWidth();
} else if (auto cplxTy = mlir::dyn_cast_or_null<fir::ComplexType>(ty)) { } else if (auto cplxTy = mlir::dyn_cast_or_null<fir::ComplexType>(ty)) {
name << kindMap.getRealBitsize(cplxTy.getFKind()); name << kindMap.getRealBitsize(cplxTy.getFKind());
@ -644,7 +646,7 @@ static llvm::SmallPtrSet<detail::RecordTypeStorage const *, 4>
} // namespace } // namespace
void fir::verifyIntegralType(mlir::Type type) { void fir::verifyIntegralType(mlir::Type type) {
if (isaIntegerType(type) || type.isa<mlir::IndexType>()) if (isaIntegerType(type) || mlir::isa<mlir::IndexType>(type))
return; return;
llvm::report_fatal_error("expected integral type"); llvm::report_fatal_error("expected integral type");
} }
@ -656,9 +658,9 @@ void fir::printFirType(FIROpsDialect *, mlir::Type ty,
} }
bool fir::isa_unknown_size_box(mlir::Type t) { bool fir::isa_unknown_size_box(mlir::Type t) {
if (auto boxTy = t.dyn_cast<fir::BaseBoxType>()) { if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(t)) {
auto valueType = fir::unwrapPassByRefType(boxTy); auto valueType = fir::unwrapPassByRefType(boxTy);
if (auto seqTy = valueType.dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(valueType))
if (seqTy.hasUnknownShape()) if (seqTy.hasUnknownShape())
return true; return true;
} }
@ -684,10 +686,10 @@ void fir::BoxProcType::print(mlir::AsmPrinter &printer) const {
mlir::LogicalResult mlir::LogicalResult
BoxProcType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError, BoxProcType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) { mlir::Type eleTy) {
if (eleTy.isa<mlir::FunctionType>()) if (mlir::isa<mlir::FunctionType>(eleTy))
return mlir::success(); return mlir::success();
if (auto refTy = eleTy.dyn_cast<ReferenceType>()) if (auto refTy = mlir::dyn_cast<ReferenceType>(eleTy))
if (refTy.isa<mlir::FunctionType>()) if (mlir::isa<mlir::FunctionType>(refTy))
return mlir::success(); return mlir::success();
return emitError() << "invalid type for boxproc" << eleTy << '\n'; return emitError() << "invalid type for boxproc" << eleTy << '\n';
} }
@ -705,7 +707,7 @@ static bool cannotBePointerOrHeapElementType(mlir::Type eleTy) {
mlir::LogicalResult mlir::LogicalResult
fir::BoxType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError, fir::BoxType::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
mlir::Type eleTy) { mlir::Type eleTy) {
if (eleTy.isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(eleTy))
return emitError() << "invalid element type\n"; return emitError() << "invalid element type\n";
// TODO // TODO
return mlir::success(); return mlir::success();
@ -1236,10 +1238,10 @@ bool fir::VectorType::isValidElementType(mlir::Type t) {
} }
bool fir::isCharacterProcedureTuple(mlir::Type ty, bool acceptRawFunc) { bool fir::isCharacterProcedureTuple(mlir::Type ty, bool acceptRawFunc) {
mlir::TupleType tuple = ty.dyn_cast<mlir::TupleType>(); mlir::TupleType tuple = mlir::dyn_cast<mlir::TupleType>(ty);
return tuple && tuple.size() == 2 && return tuple && tuple.size() == 2 &&
(tuple.getType(0).isa<fir::BoxProcType>() || (mlir::isa<fir::BoxProcType>(tuple.getType(0)) ||
(acceptRawFunc && tuple.getType(0).isa<mlir::FunctionType>())) && (acceptRawFunc && mlir::isa<mlir::FunctionType>(tuple.getType(0)))) &&
fir::isa_integer(tuple.getType(1)); fir::isa_integer(tuple.getType(1));
} }
@ -1247,7 +1249,8 @@ bool fir::hasAbstractResult(mlir::FunctionType ty) {
if (ty.getNumResults() == 0) if (ty.getNumResults() == 0)
return false; return false;
auto resultType = ty.getResult(0); auto resultType = ty.getResult(0);
return resultType.isa<fir::SequenceType, fir::BaseBoxType, fir::RecordType>(); return mlir::isa<fir::SequenceType, fir::BaseBoxType, fir::RecordType>(
resultType);
} }
/// Convert llvm::Type::TypeID to mlir::Type. \p kind is provided for error /// Convert llvm::Type::TypeID to mlir::Type. \p kind is provided for error

View File

@ -18,7 +18,7 @@ mlir::LogicalResult
fir::FortranVariableOpInterface::verifyDeclareLikeOpImpl(mlir::Value memref) { fir::FortranVariableOpInterface::verifyDeclareLikeOpImpl(mlir::Value memref) {
const unsigned numExplicitTypeParams = getExplicitTypeParams().size(); const unsigned numExplicitTypeParams = getExplicitTypeParams().size();
mlir::Type memType = memref.getType(); mlir::Type memType = memref.getType();
const bool sourceIsBoxValue = memType.isa<fir::BaseBoxType>(); const bool sourceIsBoxValue = mlir::isa<fir::BaseBoxType>(memType);
const bool sourceIsBoxAddress = fir::isBoxAddress(memType); const bool sourceIsBoxAddress = fir::isBoxAddress(memType);
const bool sourceIsBox = sourceIsBoxValue || sourceIsBoxAddress; const bool sourceIsBox = sourceIsBoxValue || sourceIsBoxAddress;
if (isCharacter()) { if (isCharacter()) {
@ -29,7 +29,8 @@ fir::FortranVariableOpInterface::verifyDeclareLikeOpImpl(mlir::Value memref) {
return emitOpError("must be provided exactly one type parameter when its " return emitOpError("must be provided exactly one type parameter when its "
"base is a character that is not a box"); "base is a character that is not a box");
} else if (auto recordType = getElementType().dyn_cast<fir::RecordType>()) { } else if (auto recordType =
mlir::dyn_cast<fir::RecordType>(getElementType())) {
if (numExplicitTypeParams < recordType.getNumLenParams() && !sourceIsBox) if (numExplicitTypeParams < recordType.getNumLenParams() && !sourceIsBox)
return emitOpError("must be provided all the derived type length " return emitOpError("must be provided all the derived type length "
"parameters when the base is not a box"); "parameters when the base is not a box");
@ -45,16 +46,16 @@ fir::FortranVariableOpInterface::verifyDeclareLikeOpImpl(mlir::Value memref) {
if (sourceIsBoxAddress) if (sourceIsBoxAddress)
return emitOpError("for box address must not have a shape operand"); return emitOpError("for box address must not have a shape operand");
unsigned shapeRank = 0; unsigned shapeRank = 0;
if (auto shapeType = shape.getType().dyn_cast<fir::ShapeType>()) { if (auto shapeType = mlir::dyn_cast<fir::ShapeType>(shape.getType())) {
shapeRank = shapeType.getRank(); shapeRank = shapeType.getRank();
} else if (auto shapeShiftType = } else if (auto shapeShiftType =
shape.getType().dyn_cast<fir::ShapeShiftType>()) { mlir::dyn_cast<fir::ShapeShiftType>(shape.getType())) {
shapeRank = shapeShiftType.getRank(); shapeRank = shapeShiftType.getRank();
} else { } else {
if (!sourceIsBoxValue) if (!sourceIsBoxValue)
emitOpError("of array entity with a raw address base must have a " emitOpError("of array entity with a raw address base must have a "
"shape operand that is a shape or shapeshift"); "shape operand that is a shape or shapeshift");
shapeRank = shape.getType().cast<fir::ShiftType>().getRank(); shapeRank = mlir::cast<fir::ShiftType>(shape.getType()).getRank();
} }
std::optional<unsigned> rank = getRank(); std::optional<unsigned> rank = getRank();

View File

@ -84,7 +84,8 @@ bool hlfir::isFortranVariableType(mlir::Type type) {
return llvm::TypeSwitch<mlir::Type, bool>(type) return llvm::TypeSwitch<mlir::Type, bool>(type)
.Case<fir::ReferenceType, fir::PointerType, fir::HeapType>([](auto p) { .Case<fir::ReferenceType, fir::PointerType, fir::HeapType>([](auto p) {
mlir::Type eleType = p.getEleTy(); mlir::Type eleType = p.getEleTy();
return eleType.isa<fir::BaseBoxType>() || !fir::hasDynamicSize(eleType); return mlir::isa<fir::BaseBoxType>(eleType) ||
!fir::hasDynamicSize(eleType);
}) })
.Case<fir::BaseBoxType, fir::BoxCharType>([](auto) { return true; }) .Case<fir::BaseBoxType, fir::BoxCharType>([](auto) { return true; })
.Case<fir::VectorType>([](auto) { return true; }) .Case<fir::VectorType>([](auto) { return true; })
@ -93,15 +94,15 @@ bool hlfir::isFortranVariableType(mlir::Type type) {
bool hlfir::isFortranScalarCharacterType(mlir::Type type) { bool hlfir::isFortranScalarCharacterType(mlir::Type type) {
return isFortranScalarCharacterExprType(type) || return isFortranScalarCharacterExprType(type) ||
type.isa<fir::BoxCharType>() || mlir::isa<fir::BoxCharType>(type) ||
fir::unwrapPassByRefType(fir::unwrapRefType(type)) mlir::isa<fir::CharacterType>(
.isa<fir::CharacterType>(); fir::unwrapPassByRefType(fir::unwrapRefType(type)));
} }
bool hlfir::isFortranScalarCharacterExprType(mlir::Type type) { bool hlfir::isFortranScalarCharacterExprType(mlir::Type type) {
if (auto exprType = type.dyn_cast<hlfir::ExprType>()) if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(type))
return exprType.isScalar() && return exprType.isScalar() &&
exprType.getElementType().isa<fir::CharacterType>(); mlir::isa<fir::CharacterType>(exprType.getElementType());
return false; return false;
} }
@ -121,8 +122,8 @@ bool hlfir::isFortranScalarNumericalType(mlir::Type type) {
bool hlfir::isFortranNumericalArrayObject(mlir::Type type) { bool hlfir::isFortranNumericalArrayObject(mlir::Type type) {
if (isBoxAddressType(type)) if (isBoxAddressType(type))
return false; return false;
if (auto arrayTy = if (auto arrayTy = mlir::dyn_cast<fir::SequenceType>(
getFortranElementOrSequenceType(type).dyn_cast<fir::SequenceType>()) getFortranElementOrSequenceType(type)))
return isFortranScalarNumericalType(arrayTy.getEleTy()); return isFortranScalarNumericalType(arrayTy.getEleTy());
return false; return false;
} }
@ -130,8 +131,8 @@ bool hlfir::isFortranNumericalArrayObject(mlir::Type type) {
bool hlfir::isFortranNumericalOrLogicalArrayObject(mlir::Type type) { bool hlfir::isFortranNumericalOrLogicalArrayObject(mlir::Type type) {
if (isBoxAddressType(type)) if (isBoxAddressType(type))
return false; return false;
if (auto arrayTy = if (auto arrayTy = mlir::dyn_cast<fir::SequenceType>(
getFortranElementOrSequenceType(type).dyn_cast<fir::SequenceType>()) { getFortranElementOrSequenceType(type))) {
mlir::Type eleTy = arrayTy.getEleTy(); mlir::Type eleTy = arrayTy.getEleTy();
return isFortranScalarNumericalType(eleTy) || return isFortranScalarNumericalType(eleTy) ||
mlir::isa<fir::LogicalType>(eleTy); mlir::isa<fir::LogicalType>(eleTy);
@ -142,7 +143,8 @@ bool hlfir::isFortranNumericalOrLogicalArrayObject(mlir::Type type) {
bool hlfir::isFortranArrayObject(mlir::Type type) { bool hlfir::isFortranArrayObject(mlir::Type type) {
if (isBoxAddressType(type)) if (isBoxAddressType(type))
return false; return false;
return !!getFortranElementOrSequenceType(type).dyn_cast<fir::SequenceType>(); return !!mlir::dyn_cast<fir::SequenceType>(
getFortranElementOrSequenceType(type));
} }
bool hlfir::isPassByRefOrIntegerType(mlir::Type type) { bool hlfir::isPassByRefOrIntegerType(mlir::Type type) {
@ -151,7 +153,7 @@ bool hlfir::isPassByRefOrIntegerType(mlir::Type type) {
} }
bool hlfir::isI1Type(mlir::Type type) { bool hlfir::isI1Type(mlir::Type type) {
if (mlir::IntegerType integer = type.dyn_cast<mlir::IntegerType>()) if (mlir::IntegerType integer = mlir::dyn_cast<mlir::IntegerType>(type))
if (integer.getWidth() == 1) if (integer.getWidth() == 1)
return true; return true;
return false; return false;
@ -160,8 +162,8 @@ bool hlfir::isI1Type(mlir::Type type) {
bool hlfir::isFortranLogicalArrayObject(mlir::Type type) { bool hlfir::isFortranLogicalArrayObject(mlir::Type type) {
if (isBoxAddressType(type)) if (isBoxAddressType(type))
return false; return false;
if (auto arrayTy = if (auto arrayTy = mlir::dyn_cast<fir::SequenceType>(
getFortranElementOrSequenceType(type).dyn_cast<fir::SequenceType>()) { getFortranElementOrSequenceType(type))) {
mlir::Type eleTy = arrayTy.getEleTy(); mlir::Type eleTy = arrayTy.getEleTy();
return mlir::isa<fir::LogicalType>(eleTy); return mlir::isa<fir::LogicalType>(eleTy);
} }

View File

@ -74,8 +74,8 @@ getIntrinsicEffects(mlir::Operation *self,
/// Is this a fir.[ref/ptr/heap]<fir.[box/class]<fir.heap<T>>> type? /// Is this a fir.[ref/ptr/heap]<fir.[box/class]<fir.heap<T>>> type?
static bool isAllocatableBoxRef(mlir::Type type) { static bool isAllocatableBoxRef(mlir::Type type) {
fir::BaseBoxType boxType = fir::BaseBoxType boxType =
fir::dyn_cast_ptrEleTy(type).dyn_cast_or_null<fir::BaseBoxType>(); mlir::dyn_cast_or_null<fir::BaseBoxType>(fir::dyn_cast_ptrEleTy(type));
return boxType && boxType.getEleTy().isa<fir::HeapType>(); return boxType && mlir::isa<fir::HeapType>(boxType.getEleTy());
} }
mlir::LogicalResult hlfir::AssignOp::verify() { mlir::LogicalResult hlfir::AssignOp::verify() {
@ -84,7 +84,7 @@ mlir::LogicalResult hlfir::AssignOp::verify() {
return emitOpError("lhs must be an allocatable when `realloc` is set"); return emitOpError("lhs must be an allocatable when `realloc` is set");
if (mustKeepLhsLengthInAllocatableAssignment() && if (mustKeepLhsLengthInAllocatableAssignment() &&
!(isAllocatableAssignment() && !(isAllocatableAssignment() &&
hlfir::getFortranElementType(lhsType).isa<fir::CharacterType>())) mlir::isa<fir::CharacterType>(hlfir::getFortranElementType(lhsType))))
return emitOpError("`realloc` must be set and lhs must be a character " return emitOpError("`realloc` must be set and lhs must be a character "
"allocatable when `keep_lhs_length_if_realloc` is set"); "allocatable when `keep_lhs_length_if_realloc` is set");
return mlir::success(); return mlir::success();
@ -99,13 +99,13 @@ mlir::LogicalResult hlfir::AssignOp::verify() {
mlir::Type hlfir::DeclareOp::getHLFIRVariableType(mlir::Type inputType, mlir::Type hlfir::DeclareOp::getHLFIRVariableType(mlir::Type inputType,
bool hasExplicitLowerBounds) { bool hasExplicitLowerBounds) {
mlir::Type type = fir::unwrapRefType(inputType); mlir::Type type = fir::unwrapRefType(inputType);
if (type.isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(type))
return inputType; return inputType;
if (auto charType = type.dyn_cast<fir::CharacterType>()) if (auto charType = mlir::dyn_cast<fir::CharacterType>(type))
if (charType.hasDynamicLen()) if (charType.hasDynamicLen())
return fir::BoxCharType::get(charType.getContext(), charType.getFKind()); return fir::BoxCharType::get(charType.getContext(), charType.getFKind());
auto seqType = type.dyn_cast<fir::SequenceType>(); auto seqType = mlir::dyn_cast<fir::SequenceType>(type);
bool hasDynamicExtents = bool hasDynamicExtents =
seqType && fir::sequenceWithNonConstantShape(seqType); seqType && fir::sequenceWithNonConstantShape(seqType);
mlir::Type eleType = seqType ? seqType.getEleTy() : type; mlir::Type eleType = seqType ? seqType.getEleTy() : type;
@ -117,7 +117,8 @@ mlir::Type hlfir::DeclareOp::getHLFIRVariableType(mlir::Type inputType,
} }
static bool hasExplicitLowerBounds(mlir::Value shape) { static bool hasExplicitLowerBounds(mlir::Value shape) {
return shape && shape.getType().isa<fir::ShapeShiftType, fir::ShiftType>(); return shape &&
mlir::isa<fir::ShapeShiftType, fir::ShiftType>(shape.getType());
} }
void hlfir::DeclareOp::build(mlir::OpBuilder &builder, void hlfir::DeclareOp::build(mlir::OpBuilder &builder,
@ -288,7 +289,7 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
bool hasBoxComponent; bool hasBoxComponent;
if (getComponent()) { if (getComponent()) {
auto component = getComponent().value(); auto component = getComponent().value();
auto recType = baseElementType.dyn_cast<fir::RecordType>(); auto recType = mlir::dyn_cast<fir::RecordType>(baseElementType);
if (!recType) if (!recType)
return emitOpError( return emitOpError(
"component must be provided only when the memref is a derived type"); "component must be provided only when the memref is a derived type");
@ -300,14 +301,14 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
} }
mlir::Type fieldType = recType.getType(fieldIdx); mlir::Type fieldType = recType.getType(fieldIdx);
mlir::Type componentBaseType = getFortranElementOrSequenceType(fieldType); mlir::Type componentBaseType = getFortranElementOrSequenceType(fieldType);
hasBoxComponent = fieldType.isa<fir::BaseBoxType>(); hasBoxComponent = mlir::isa<fir::BaseBoxType>(fieldType);
if (componentBaseType.isa<fir::SequenceType>() && if (mlir::isa<fir::SequenceType>(componentBaseType) &&
baseType.isa<fir::SequenceType>() && mlir::isa<fir::SequenceType>(baseType) &&
(numSubscripts == 0 || subscriptsRank > 0)) (numSubscripts == 0 || subscriptsRank > 0))
return emitOpError("indices must be provided and must not contain " return emitOpError("indices must be provided and must not contain "
"triplets when both memref and component are arrays"); "triplets when both memref and component are arrays");
if (numSubscripts != 0) { if (numSubscripts != 0) {
if (!componentBaseType.isa<fir::SequenceType>()) if (!mlir::isa<fir::SequenceType>(componentBaseType))
return emitOpError("indices must not be provided if component appears " return emitOpError("indices must not be provided if component appears "
"and is not an array component"); "and is not an array component");
if (!getComponentShape()) if (!getComponentShape())
@ -315,9 +316,9 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
"component_shape must be provided when indexing a component"); "component_shape must be provided when indexing a component");
mlir::Type compShapeType = getComponentShape().getType(); mlir::Type compShapeType = getComponentShape().getType();
unsigned componentRank = unsigned componentRank =
componentBaseType.cast<fir::SequenceType>().getDimension(); mlir::cast<fir::SequenceType>(componentBaseType).getDimension();
auto shapeType = compShapeType.dyn_cast<fir::ShapeType>(); auto shapeType = mlir::dyn_cast<fir::ShapeType>(compShapeType);
auto shapeShiftType = compShapeType.dyn_cast<fir::ShapeShiftType>(); auto shapeShiftType = mlir::dyn_cast<fir::ShapeShiftType>(compShapeType);
if (!((shapeType && shapeType.getRank() == componentRank) || if (!((shapeType && shapeType.getRank() == componentRank) ||
(shapeShiftType && shapeShiftType.getRank() == componentRank))) (shapeShiftType && shapeShiftType.getRank() == componentRank)))
return emitOpError("component_shape must be a fir.shape or " return emitOpError("component_shape must be a fir.shape or "
@ -325,33 +326,33 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
if (numSubscripts > componentRank) if (numSubscripts > componentRank)
return emitOpError("indices number must match array component rank"); return emitOpError("indices number must match array component rank");
} }
if (auto baseSeqType = baseType.dyn_cast<fir::SequenceType>()) if (auto baseSeqType = mlir::dyn_cast<fir::SequenceType>(baseType))
// This case must come first to cover "array%array_comp(i, j)" that has // This case must come first to cover "array%array_comp(i, j)" that has
// subscripts for the component but whose rank come from the base. // subscripts for the component but whose rank come from the base.
outputRank = baseSeqType.getDimension(); outputRank = baseSeqType.getDimension();
else if (numSubscripts != 0) else if (numSubscripts != 0)
outputRank = subscriptsRank; outputRank = subscriptsRank;
else if (auto componentSeqType = else if (auto componentSeqType =
componentBaseType.dyn_cast<fir::SequenceType>()) mlir::dyn_cast<fir::SequenceType>(componentBaseType))
outputRank = componentSeqType.getDimension(); outputRank = componentSeqType.getDimension();
outputElementType = fir::unwrapSequenceType(componentBaseType); outputElementType = fir::unwrapSequenceType(componentBaseType);
} else { } else {
outputElementType = baseElementType; outputElementType = baseElementType;
unsigned baseTypeRank = unsigned baseTypeRank =
baseType.isa<fir::SequenceType>() mlir::isa<fir::SequenceType>(baseType)
? baseType.cast<fir::SequenceType>().getDimension() ? mlir::cast<fir::SequenceType>(baseType).getDimension()
: 0; : 0;
if (numSubscripts != 0) { if (numSubscripts != 0) {
if (baseTypeRank != numSubscripts) if (baseTypeRank != numSubscripts)
return emitOpError("indices number must match memref rank"); return emitOpError("indices number must match memref rank");
outputRank = subscriptsRank; outputRank = subscriptsRank;
} else if (auto baseSeqType = baseType.dyn_cast<fir::SequenceType>()) { } else if (auto baseSeqType = mlir::dyn_cast<fir::SequenceType>(baseType)) {
outputRank = baseSeqType.getDimension(); outputRank = baseSeqType.getDimension();
} }
} }
if (!getSubstring().empty()) { if (!getSubstring().empty()) {
if (!outputElementType.isa<fir::CharacterType>()) if (!mlir::isa<fir::CharacterType>(outputElementType))
return emitOpError("memref or component must have character type if " return emitOpError("memref or component must have character type if "
"substring indices are provided"); "substring indices are provided");
if (getSubstring().size() != 2) if (getSubstring().size() != 2)
@ -361,16 +362,16 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
if (!fir::isa_complex(outputElementType)) if (!fir::isa_complex(outputElementType))
return emitOpError("memref or component must have complex type if " return emitOpError("memref or component must have complex type if "
"complex_part is provided"); "complex_part is provided");
if (auto firCplx = outputElementType.dyn_cast<fir::ComplexType>()) if (auto firCplx = mlir::dyn_cast<fir::ComplexType>(outputElementType))
outputElementType = firCplx.getElementType(); outputElementType = firCplx.getElementType();
else else
outputElementType = outputElementType =
outputElementType.cast<mlir::ComplexType>().getElementType(); mlir::cast<mlir::ComplexType>(outputElementType).getElementType();
} }
mlir::Type resultBaseType = mlir::Type resultBaseType =
getFortranElementOrSequenceType(getResult().getType()); getFortranElementOrSequenceType(getResult().getType());
unsigned resultRank = 0; unsigned resultRank = 0;
if (auto resultSeqType = resultBaseType.dyn_cast<fir::SequenceType>()) if (auto resultSeqType = mlir::dyn_cast<fir::SequenceType>(resultBaseType))
resultRank = resultSeqType.getDimension(); resultRank = resultSeqType.getDimension();
if (resultRank != outputRank) if (resultRank != outputRank)
return emitOpError("result type rank is not consistent with operands, " return emitOpError("result type rank is not consistent with operands, "
@ -380,10 +381,10 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
// result type must match the one that was inferred here, except the character // result type must match the one that was inferred here, except the character
// length may differ because of substrings. // length may differ because of substrings.
if (resultElementType != outputElementType && if (resultElementType != outputElementType &&
!(resultElementType.isa<fir::CharacterType>() && !(mlir::isa<fir::CharacterType>(resultElementType) &&
outputElementType.isa<fir::CharacterType>()) && mlir::isa<fir::CharacterType>(outputElementType)) &&
!(resultElementType.isa<mlir::FloatType>() && !(mlir::isa<mlir::FloatType>(resultElementType) &&
outputElementType.isa<fir::RealType>())) mlir::isa<fir::RealType>(outputElementType)))
return emitOpError( return emitOpError(
"result element type is not consistent with operands, expected ") "result element type is not consistent with operands, expected ")
<< outputElementType; << outputElementType;
@ -401,22 +402,22 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
return emitOpError("shape must be provided if and only if the result is " return emitOpError("shape must be provided if and only if the result is "
"an array that is not a box address"); "an array that is not a box address");
if (resultRank != 0) { if (resultRank != 0) {
auto shapeType = getShape().getType().dyn_cast<fir::ShapeType>(); auto shapeType = mlir::dyn_cast<fir::ShapeType>(getShape().getType());
auto shapeShiftType = auto shapeShiftType =
getShape().getType().dyn_cast<fir::ShapeShiftType>(); mlir::dyn_cast<fir::ShapeShiftType>(getShape().getType());
if (!((shapeType && shapeType.getRank() == resultRank) || if (!((shapeType && shapeType.getRank() == resultRank) ||
(shapeShiftType && shapeShiftType.getRank() == resultRank))) (shapeShiftType && shapeShiftType.getRank() == resultRank)))
return emitOpError("shape must be a fir.shape or fir.shapeshift with " return emitOpError("shape must be a fir.shape or fir.shapeshift with "
"the rank of the result"); "the rank of the result");
} }
auto numLenParam = getTypeparams().size(); auto numLenParam = getTypeparams().size();
if (outputElementType.isa<fir::CharacterType>()) { if (mlir::isa<fir::CharacterType>(outputElementType)) {
if (numLenParam != 1) if (numLenParam != 1)
return emitOpError("must be provided one length parameter when the " return emitOpError("must be provided one length parameter when the "
"result is a character"); "result is a character");
} else if (fir::isRecordWithTypeParameters(outputElementType)) { } else if (fir::isRecordWithTypeParameters(outputElementType)) {
if (numLenParam != if (numLenParam !=
outputElementType.cast<fir::RecordType>().getNumLenParams()) mlir::cast<fir::RecordType>(outputElementType).getNumLenParams())
return emitOpError("must be provided the same number of length " return emitOpError("must be provided the same number of length "
"parameters as in the result derived type"); "parameters as in the result derived type");
} else if (numLenParam != 0) { } else if (numLenParam != 0) {
@ -434,18 +435,18 @@ mlir::LogicalResult hlfir::DesignateOp::verify() {
mlir::LogicalResult hlfir::ParentComponentOp::verify() { mlir::LogicalResult hlfir::ParentComponentOp::verify() {
mlir::Type baseType = mlir::Type baseType =
hlfir::getFortranElementOrSequenceType(getMemref().getType()); hlfir::getFortranElementOrSequenceType(getMemref().getType());
auto maybeInputSeqType = baseType.dyn_cast<fir::SequenceType>(); auto maybeInputSeqType = mlir::dyn_cast<fir::SequenceType>(baseType);
unsigned inputTypeRank = unsigned inputTypeRank =
maybeInputSeqType ? maybeInputSeqType.getDimension() : 0; maybeInputSeqType ? maybeInputSeqType.getDimension() : 0;
unsigned shapeRank = 0; unsigned shapeRank = 0;
if (mlir::Value shape = getShape()) if (mlir::Value shape = getShape())
if (auto shapeType = shape.getType().dyn_cast<fir::ShapeType>()) if (auto shapeType = mlir::dyn_cast<fir::ShapeType>(shape.getType()))
shapeRank = shapeType.getRank(); shapeRank = shapeType.getRank();
if (inputTypeRank != shapeRank) if (inputTypeRank != shapeRank)
return emitOpError( return emitOpError(
"must be provided a shape if and only if the base is an array"); "must be provided a shape if and only if the base is an array");
mlir::Type outputBaseType = hlfir::getFortranElementOrSequenceType(getType()); mlir::Type outputBaseType = hlfir::getFortranElementOrSequenceType(getType());
auto maybeOutputSeqType = outputBaseType.dyn_cast<fir::SequenceType>(); auto maybeOutputSeqType = mlir::dyn_cast<fir::SequenceType>(outputBaseType);
unsigned outputTypeRank = unsigned outputTypeRank =
maybeOutputSeqType ? maybeOutputSeqType.getDimension() : 0; maybeOutputSeqType ? maybeOutputSeqType.getDimension() : 0;
if (inputTypeRank != outputTypeRank) if (inputTypeRank != outputTypeRank)
@ -459,23 +460,23 @@ mlir::LogicalResult hlfir::ParentComponentOp::verify() {
return emitOpError( return emitOpError(
"result type extents are inconsistent with memref type"); "result type extents are inconsistent with memref type");
fir::RecordType baseRecType = fir::RecordType baseRecType =
hlfir::getFortranElementType(baseType).dyn_cast<fir::RecordType>(); mlir::dyn_cast<fir::RecordType>(hlfir::getFortranElementType(baseType));
fir::RecordType outRecType = fir::RecordType outRecType = mlir::dyn_cast<fir::RecordType>(
hlfir::getFortranElementType(outputBaseType).dyn_cast<fir::RecordType>(); hlfir::getFortranElementType(outputBaseType));
if (!baseRecType || !outRecType) if (!baseRecType || !outRecType)
return emitOpError("result type and input type must be derived types"); return emitOpError("result type and input type must be derived types");
// Note: result should not be a fir.class: its dynamic type is being set to // Note: result should not be a fir.class: its dynamic type is being set to
// the parent type and allowing fir.class would break the operation codegen: // the parent type and allowing fir.class would break the operation codegen:
// it would keep the input dynamic type. // it would keep the input dynamic type.
if (getType().isa<fir::ClassType>()) if (mlir::isa<fir::ClassType>(getType()))
return emitOpError("result type must not be polymorphic"); return emitOpError("result type must not be polymorphic");
// The array results are known to not be dis-contiguous in most cases (the // The array results are known to not be dis-contiguous in most cases (the
// exception being if the parent type was extended by a type without any // exception being if the parent type was extended by a type without any
// components): require a fir.box to be used for the result to carry the // components): require a fir.box to be used for the result to carry the
// strides. // strides.
if (!getType().isa<fir::BoxType>() && if (!mlir::isa<fir::BoxType>(getType()) &&
(outputTypeRank != 0 || fir::isRecordWithTypeParameters(outRecType))) (outputTypeRank != 0 || fir::isRecordWithTypeParameters(outRecType)))
return emitOpError("result type must be a fir.box if the result is an " return emitOpError("result type must be a fir.box if the result is an "
"array or has length parameters"); "array or has length parameters");
@ -496,9 +497,8 @@ verifyLogicalReductionOp(LogicalReductionOp reductionOp) {
mlir::Value mask = reductionOp->getMask(); mlir::Value mask = reductionOp->getMask();
mlir::Value dim = reductionOp->getDim(); mlir::Value dim = reductionOp->getDim();
fir::SequenceType maskTy = fir::SequenceType maskTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(mask.getType()) hlfir::getFortranElementOrSequenceType(mask.getType()));
.cast<fir::SequenceType>();
mlir::Type logicalTy = maskTy.getEleTy(); mlir::Type logicalTy = maskTy.getEleTy();
llvm::ArrayRef<int64_t> maskShape = maskTy.getShape(); llvm::ArrayRef<int64_t> maskShape = maskTy.getShape();
@ -576,9 +576,8 @@ mlir::LogicalResult hlfir::CountOp::verify() {
mlir::Value mask = getMask(); mlir::Value mask = getMask();
mlir::Value dim = getDim(); mlir::Value dim = getDim();
fir::SequenceType maskTy = fir::SequenceType maskTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(mask.getType()) hlfir::getFortranElementOrSequenceType(mask.getType()));
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> maskShape = maskTy.getShape(); llvm::ArrayRef<int64_t> maskShape = maskTy.getShape();
mlir::Type resultType = results[0]; mlir::Type resultType = results[0];
@ -613,13 +612,14 @@ void hlfir::CountOp::getEffects(
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
static unsigned getCharacterKind(mlir::Type t) { static unsigned getCharacterKind(mlir::Type t) {
return hlfir::getFortranElementType(t).cast<fir::CharacterType>().getFKind(); return mlir::cast<fir::CharacterType>(hlfir::getFortranElementType(t))
.getFKind();
} }
static std::optional<fir::CharacterType::LenType> static std::optional<fir::CharacterType::LenType>
getCharacterLengthIfStatic(mlir::Type t) { getCharacterLengthIfStatic(mlir::Type t) {
if (auto charType = if (auto charType =
hlfir::getFortranElementType(t).dyn_cast<fir::CharacterType>()) mlir::dyn_cast<fir::CharacterType>(hlfir::getFortranElementType(t)))
if (charType.hasConstantLen()) if (charType.hasConstantLen())
return charType.getLen(); return charType.getLen();
return std::nullopt; return std::nullopt;
@ -672,15 +672,13 @@ verifyArrayAndMaskForReductionOp(NumericalReductionOp reductionOp) {
mlir::Value array = reductionOp->getArray(); mlir::Value array = reductionOp->getArray();
mlir::Value mask = reductionOp->getMask(); mlir::Value mask = reductionOp->getMask();
fir::SequenceType arrayTy = fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(array.getType()) hlfir::getFortranElementOrSequenceType(array.getType()));
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape(); llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
if (mask) { if (mask) {
fir::SequenceType maskSeq = fir::SequenceType maskSeq = mlir::dyn_cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(mask.getType()) hlfir::getFortranElementOrSequenceType(mask.getType()));
.dyn_cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> maskShape; llvm::ArrayRef<int64_t> maskShape;
if (maskSeq) if (maskSeq)
@ -720,9 +718,8 @@ verifyNumericalReductionOp(NumericalReductionOp reductionOp) {
mlir::Value array = reductionOp->getArray(); mlir::Value array = reductionOp->getArray();
mlir::Value dim = reductionOp->getDim(); mlir::Value dim = reductionOp->getDim();
fir::SequenceType arrayTy = fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(array.getType()) hlfir::getFortranElementOrSequenceType(array.getType()));
.cast<fir::SequenceType>();
mlir::Type numTy = arrayTy.getEleTy(); mlir::Type numTy = arrayTy.getEleTy();
llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape(); llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
@ -790,13 +787,12 @@ verifyCharacterReductionOp(CharacterReductionOp reductionOp) {
mlir::Value array = reductionOp->getArray(); mlir::Value array = reductionOp->getArray();
mlir::Value dim = reductionOp->getDim(); mlir::Value dim = reductionOp->getDim();
fir::SequenceType arrayTy = fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(array.getType()) hlfir::getFortranElementOrSequenceType(array.getType()));
.cast<fir::SequenceType>();
mlir::Type numTy = arrayTy.getEleTy(); mlir::Type numTy = arrayTy.getEleTy();
llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape(); llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
auto resultExpr = results[0].cast<hlfir::ExprType>(); auto resultExpr = mlir::cast<hlfir::ExprType>(results[0]);
mlir::Type resultType = resultExpr.getEleTy(); mlir::Type resultType = resultExpr.getEleTy();
assert(mlir::isa<fir::CharacterType>(resultType) && assert(mlir::isa<fir::CharacterType>(resultType) &&
"result must be character"); "result must be character");
@ -881,9 +877,8 @@ verifyResultForMinMaxLoc(NumericalReductionOp reductionOp) {
mlir::Value array = reductionOp->getArray(); mlir::Value array = reductionOp->getArray();
mlir::Value dim = reductionOp->getDim(); mlir::Value dim = reductionOp->getDim();
fir::SequenceType arrayTy = fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(array.getType()) hlfir::getFortranElementOrSequenceType(array.getType()));
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape(); llvm::ArrayRef<int64_t> arrayShape = arrayTy.getShape();
mlir::Type resultType = results[0]; mlir::Type resultType = results[0];
@ -993,12 +988,10 @@ void hlfir::SumOp::getEffects(
mlir::LogicalResult hlfir::DotProductOp::verify() { mlir::LogicalResult hlfir::DotProductOp::verify() {
mlir::Value lhs = getLhs(); mlir::Value lhs = getLhs();
mlir::Value rhs = getRhs(); mlir::Value rhs = getRhs();
fir::SequenceType lhsTy = fir::SequenceType lhsTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(lhs.getType()) hlfir::getFortranElementOrSequenceType(lhs.getType()));
.cast<fir::SequenceType>(); fir::SequenceType rhsTy = mlir::cast<fir::SequenceType>(
fir::SequenceType rhsTy = hlfir::getFortranElementOrSequenceType(rhs.getType()));
hlfir::getFortranElementOrSequenceType(rhs.getType())
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape(); llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape();
llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape(); llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape();
std::size_t lhsRank = lhsShape.size(); std::size_t lhsRank = lhsShape.size();
@ -1051,19 +1044,17 @@ void hlfir::DotProductOp::getEffects(
mlir::LogicalResult hlfir::MatmulOp::verify() { mlir::LogicalResult hlfir::MatmulOp::verify() {
mlir::Value lhs = getLhs(); mlir::Value lhs = getLhs();
mlir::Value rhs = getRhs(); mlir::Value rhs = getRhs();
fir::SequenceType lhsTy = fir::SequenceType lhsTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(lhs.getType()) hlfir::getFortranElementOrSequenceType(lhs.getType()));
.cast<fir::SequenceType>(); fir::SequenceType rhsTy = mlir::cast<fir::SequenceType>(
fir::SequenceType rhsTy = hlfir::getFortranElementOrSequenceType(rhs.getType()));
hlfir::getFortranElementOrSequenceType(rhs.getType())
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape(); llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape();
llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape(); llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape();
std::size_t lhsRank = lhsShape.size(); std::size_t lhsRank = lhsShape.size();
std::size_t rhsRank = rhsShape.size(); std::size_t rhsRank = rhsShape.size();
mlir::Type lhsEleTy = lhsTy.getEleTy(); mlir::Type lhsEleTy = lhsTy.getEleTy();
mlir::Type rhsEleTy = rhsTy.getEleTy(); mlir::Type rhsEleTy = rhsTy.getEleTy();
hlfir::ExprType resultTy = getResult().getType().cast<hlfir::ExprType>(); hlfir::ExprType resultTy = mlir::cast<hlfir::ExprType>(getResult().getType());
llvm::ArrayRef<int64_t> resultShape = resultTy.getShape(); llvm::ArrayRef<int64_t> resultShape = resultTy.getShape();
mlir::Type resultEleTy = resultTy.getEleTy(); mlir::Type resultEleTy = resultTy.getEleTy();
@ -1180,13 +1171,12 @@ void hlfir::MatmulOp::getEffects(
mlir::LogicalResult hlfir::TransposeOp::verify() { mlir::LogicalResult hlfir::TransposeOp::verify() {
mlir::Value array = getArray(); mlir::Value array = getArray();
fir::SequenceType arrayTy = fir::SequenceType arrayTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(array.getType()) hlfir::getFortranElementOrSequenceType(array.getType()));
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> inShape = arrayTy.getShape(); llvm::ArrayRef<int64_t> inShape = arrayTy.getShape();
std::size_t rank = inShape.size(); std::size_t rank = inShape.size();
mlir::Type eleTy = arrayTy.getEleTy(); mlir::Type eleTy = arrayTy.getEleTy();
hlfir::ExprType resultTy = getResult().getType().cast<hlfir::ExprType>(); hlfir::ExprType resultTy = mlir::cast<hlfir::ExprType>(getResult().getType());
llvm::ArrayRef<int64_t> resultShape = resultTy.getShape(); llvm::ArrayRef<int64_t> resultShape = resultTy.getShape();
std::size_t resultRank = resultShape.size(); std::size_t resultRank = resultShape.size();
mlir::Type resultEleTy = resultTy.getEleTy(); mlir::Type resultEleTy = resultTy.getEleTy();
@ -1224,19 +1214,17 @@ void hlfir::TransposeOp::getEffects(
mlir::LogicalResult hlfir::MatmulTransposeOp::verify() { mlir::LogicalResult hlfir::MatmulTransposeOp::verify() {
mlir::Value lhs = getLhs(); mlir::Value lhs = getLhs();
mlir::Value rhs = getRhs(); mlir::Value rhs = getRhs();
fir::SequenceType lhsTy = fir::SequenceType lhsTy = mlir::cast<fir::SequenceType>(
hlfir::getFortranElementOrSequenceType(lhs.getType()) hlfir::getFortranElementOrSequenceType(lhs.getType()));
.cast<fir::SequenceType>(); fir::SequenceType rhsTy = mlir::cast<fir::SequenceType>(
fir::SequenceType rhsTy = hlfir::getFortranElementOrSequenceType(rhs.getType()));
hlfir::getFortranElementOrSequenceType(rhs.getType())
.cast<fir::SequenceType>();
llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape(); llvm::ArrayRef<int64_t> lhsShape = lhsTy.getShape();
llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape(); llvm::ArrayRef<int64_t> rhsShape = rhsTy.getShape();
std::size_t lhsRank = lhsShape.size(); std::size_t lhsRank = lhsShape.size();
std::size_t rhsRank = rhsShape.size(); std::size_t rhsRank = rhsShape.size();
mlir::Type lhsEleTy = lhsTy.getEleTy(); mlir::Type lhsEleTy = lhsTy.getEleTy();
mlir::Type rhsEleTy = rhsTy.getEleTy(); mlir::Type rhsEleTy = rhsTy.getEleTy();
hlfir::ExprType resultTy = getResult().getType().cast<hlfir::ExprType>(); hlfir::ExprType resultTy = mlir::cast<hlfir::ExprType>(getResult().getType());
llvm::ArrayRef<int64_t> resultShape = resultTy.getShape(); llvm::ArrayRef<int64_t> resultShape = resultTy.getShape();
mlir::Type resultEleTy = resultTy.getEleTy(); mlir::Type resultEleTy = resultTy.getEleTy();
@ -1381,7 +1369,7 @@ void hlfir::AsExprOp::build(mlir::OpBuilder &builder,
hlfir::ExprType::Shape typeShape; hlfir::ExprType::Shape typeShape;
bool isPolymorphic = fir::isPolymorphicType(var.getType()); bool isPolymorphic = fir::isPolymorphicType(var.getType());
mlir::Type type = getFortranElementOrSequenceType(var.getType()); mlir::Type type = getFortranElementOrSequenceType(var.getType());
if (auto seqType = type.dyn_cast<fir::SequenceType>()) { if (auto seqType = mlir::dyn_cast<fir::SequenceType>(type)) {
typeShape.append(seqType.getShape().begin(), seqType.getShape().end()); typeShape.append(seqType.getShape().begin(), seqType.getShape().end());
type = seqType.getEleTy(); type = seqType.getEleTy();
} }
@ -1427,7 +1415,7 @@ static void buildElemental(mlir::OpBuilder &builder,
isUnordered ? builder.getUnitAttr() : nullptr); isUnordered ? builder.getUnitAttr() : nullptr);
mlir::Region *bodyRegion = odsState.addRegion(); mlir::Region *bodyRegion = odsState.addRegion();
bodyRegion->push_back(new mlir::Block{}); bodyRegion->push_back(new mlir::Block{});
if (auto shapeType = shape.getType().dyn_cast<fir::ShapeType>()) { if (auto shapeType = mlir::dyn_cast<fir::ShapeType>(shape.getType())) {
unsigned dim = shapeType.getRank(); unsigned dim = shapeType.getRank();
mlir::Type indexType = builder.getIndexType(); mlir::Type indexType = builder.getIndexType();
for (unsigned d = 0; d < dim; ++d) for (unsigned d = 0; d < dim; ++d)
@ -1468,7 +1456,7 @@ void hlfir::ApplyOp::build(mlir::OpBuilder &builder,
mlir::ValueRange indices, mlir::ValueRange indices,
mlir::ValueRange typeparams) { mlir::ValueRange typeparams) {
mlir::Type resultType = expr.getType(); mlir::Type resultType = expr.getType();
if (auto exprType = resultType.dyn_cast<hlfir::ExprType>()) if (auto exprType = mlir::dyn_cast<hlfir::ExprType>(resultType))
resultType = exprType.getElementExprType(); resultType = exprType.getElementExprType();
build(builder, odsState, resultType, expr, indices, typeparams); build(builder, odsState, resultType, expr, indices, typeparams);
} }
@ -1517,20 +1505,20 @@ void hlfir::CopyInOp::build(mlir::OpBuilder &builder,
void hlfir::ShapeOfOp::build(mlir::OpBuilder &builder, void hlfir::ShapeOfOp::build(mlir::OpBuilder &builder,
mlir::OperationState &result, mlir::Value expr) { mlir::OperationState &result, mlir::Value expr) {
hlfir::ExprType exprTy = expr.getType().cast<hlfir::ExprType>(); hlfir::ExprType exprTy = mlir::cast<hlfir::ExprType>(expr.getType());
mlir::Type type = fir::ShapeType::get(builder.getContext(), exprTy.getRank()); mlir::Type type = fir::ShapeType::get(builder.getContext(), exprTy.getRank());
build(builder, result, type, expr); build(builder, result, type, expr);
} }
std::size_t hlfir::ShapeOfOp::getRank() { std::size_t hlfir::ShapeOfOp::getRank() {
mlir::Type resTy = getResult().getType(); mlir::Type resTy = getResult().getType();
fir::ShapeType shape = resTy.cast<fir::ShapeType>(); fir::ShapeType shape = mlir::cast<fir::ShapeType>(resTy);
return shape.getRank(); return shape.getRank();
} }
mlir::LogicalResult hlfir::ShapeOfOp::verify() { mlir::LogicalResult hlfir::ShapeOfOp::verify() {
mlir::Value expr = getExpr(); mlir::Value expr = getExpr();
hlfir::ExprType exprTy = expr.getType().cast<hlfir::ExprType>(); hlfir::ExprType exprTy = mlir::cast<hlfir::ExprType>(expr.getType());
std::size_t exprRank = exprTy.getShape().size(); std::size_t exprRank = exprTy.getShape().size();
if (exprRank == 0) if (exprRank == 0)
@ -1549,7 +1537,8 @@ hlfir::ShapeOfOp::canonicalize(ShapeOfOp shapeOf,
// if extent information is available at compile time, immediately fold the // if extent information is available at compile time, immediately fold the
// hlfir.shape_of into a fir.shape // hlfir.shape_of into a fir.shape
mlir::Location loc = shapeOf.getLoc(); mlir::Location loc = shapeOf.getLoc();
hlfir::ExprType expr = shapeOf.getExpr().getType().cast<hlfir::ExprType>(); hlfir::ExprType expr =
mlir::cast<hlfir::ExprType>(shapeOf.getExpr().getType());
mlir::Value shape = hlfir::genExprShape(rewriter, loc, expr); mlir::Value shape = hlfir::genExprShape(rewriter, loc, expr);
if (!shape) if (!shape)
@ -1574,7 +1563,7 @@ void hlfir::GetExtentOp::build(mlir::OpBuilder &builder,
} }
mlir::LogicalResult hlfir::GetExtentOp::verify() { mlir::LogicalResult hlfir::GetExtentOp::verify() {
fir::ShapeType shapeTy = getShape().getType().cast<fir::ShapeType>(); fir::ShapeType shapeTy = mlir::cast<fir::ShapeType>(getShape().getType());
std::uint64_t rank = shapeTy.getRank(); std::uint64_t rank = shapeTy.getRank();
llvm::APInt dim = getDim(); llvm::APInt dim = getDim();
if (dim.sge(rank)) if (dim.sge(rank))
@ -1709,10 +1698,11 @@ mlir::LogicalResult hlfir::ElementalAddrOp::verify() {
return emitOpError("body region must be terminated by an hlfir.yield"); return emitOpError("body region must be terminated by an hlfir.yield");
mlir::Type elementAddrType = yieldOp.getEntity().getType(); mlir::Type elementAddrType = yieldOp.getEntity().getType();
if (!hlfir::isFortranVariableType(elementAddrType) || if (!hlfir::isFortranVariableType(elementAddrType) ||
hlfir::getFortranElementOrSequenceType(elementAddrType) mlir::isa<fir::SequenceType>(
.isa<fir::SequenceType>()) hlfir::getFortranElementOrSequenceType(elementAddrType)))
return emitOpError("body must compute the address of a scalar entity"); return emitOpError("body must compute the address of a scalar entity");
unsigned shapeRank = getShape().getType().cast<fir::ShapeType>().getRank(); unsigned shapeRank =
mlir::cast<fir::ShapeType>(getShape().getType()).getRank();
if (shapeRank != getIndices().size()) if (shapeRank != getIndices().size())
return emitOpError("body number of indices must match shape rank"); return emitOpError("body number of indices must match shape rank");
return mlir::success(); return mlir::success();
@ -1817,8 +1807,8 @@ static bool yieldsLogical(mlir::Region &region, bool mustBeScalarI1) {
if (mustBeScalarI1) if (mustBeScalarI1)
return hlfir::isI1Type(yieldType); return hlfir::isI1Type(yieldType);
return hlfir::isMaskArgument(yieldType) && return hlfir::isMaskArgument(yieldType) &&
hlfir::getFortranElementOrSequenceType(yieldType) mlir::isa<fir::SequenceType>(
.isa<fir::SequenceType>(); hlfir::getFortranElementOrSequenceType(yieldType));
} }
mlir::LogicalResult hlfir::ForallMaskOp::verify() { mlir::LogicalResult hlfir::ForallMaskOp::verify() {

View File

@ -77,7 +77,7 @@ static mlir::Value packageBufferizedExpr(mlir::Location loc,
/// currently enforced by the verifiers that only accept HLFIR value or /// currently enforced by the verifiers that only accept HLFIR value or
/// variable types which do not include tuples. /// variable types which do not include tuples.
static hlfir::Entity getBufferizedExprStorage(mlir::Value bufferizedExpr) { static hlfir::Entity getBufferizedExprStorage(mlir::Value bufferizedExpr) {
auto tupleType = bufferizedExpr.getType().dyn_cast<mlir::TupleType>(); auto tupleType = mlir::dyn_cast<mlir::TupleType>(bufferizedExpr.getType());
if (!tupleType) if (!tupleType)
return hlfir::Entity{bufferizedExpr}; return hlfir::Entity{bufferizedExpr};
assert(tupleType.size() == 2 && "unexpected tuple type"); assert(tupleType.size() == 2 && "unexpected tuple type");
@ -90,7 +90,7 @@ static hlfir::Entity getBufferizedExprStorage(mlir::Value bufferizedExpr) {
/// Helper to extract the clean-up flag from a tuple created by /// Helper to extract the clean-up flag from a tuple created by
/// packageBufferizedExpr. /// packageBufferizedExpr.
static mlir::Value getBufferizedExprMustFreeFlag(mlir::Value bufferizedExpr) { static mlir::Value getBufferizedExprMustFreeFlag(mlir::Value bufferizedExpr) {
auto tupleType = bufferizedExpr.getType().dyn_cast<mlir::TupleType>(); auto tupleType = mlir::dyn_cast<mlir::TupleType>(bufferizedExpr.getType());
if (!tupleType) if (!tupleType)
return bufferizedExpr; return bufferizedExpr;
assert(tupleType.size() == 2 && "unexpected tuple type"); assert(tupleType.size() == 2 && "unexpected tuple type");
@ -218,7 +218,7 @@ struct ShapeOfOpConversion
} else { } else {
// everything else failed so try to create a shape from static type info // everything else failed so try to create a shape from static type info
hlfir::ExprType exprTy = hlfir::ExprType exprTy =
adaptor.getExpr().getType().dyn_cast_or_null<hlfir::ExprType>(); mlir::dyn_cast_or_null<hlfir::ExprType>(adaptor.getExpr().getType());
if (exprTy) if (exprTy)
shape = hlfir::genExprShape(builder, loc, exprTy); shape = hlfir::genExprShape(builder, loc, exprTy);
} }
@ -480,10 +480,10 @@ struct AssociateOpConversion
assert(mlir::isa<fir::ClassType>(sourceVar.getType()) && assert(mlir::isa<fir::ClassType>(sourceVar.getType()) &&
fir::isAllocatableType(sourceVar.getType())); fir::isAllocatableType(sourceVar.getType()));
assert(sourceVar.getType() == assocType); assert(sourceVar.getType() == assocType);
} else if ((sourceVar.getType().isa<fir::BaseBoxType>() && } else if ((mlir::isa<fir::BaseBoxType>(sourceVar.getType()) &&
!assocType.isa<fir::BaseBoxType>()) || !mlir::isa<fir::BaseBoxType>(assocType)) ||
((sourceVar.getType().isa<fir::BoxCharType>() && ((mlir::isa<fir::BoxCharType>(sourceVar.getType()) &&
!assocType.isa<fir::BoxCharType>()))) { !mlir::isa<fir::BoxCharType>(assocType)))) {
sourceVar = builder.create<fir::BoxAddrOp>(loc, assocType, sourceVar); sourceVar = builder.create<fir::BoxAddrOp>(loc, assocType, sourceVar);
} else { } else {
sourceVar = builder.createConvert(loc, assocType, sourceVar); sourceVar = builder.createConvert(loc, assocType, sourceVar);
@ -590,13 +590,13 @@ static void genBufferDestruction(mlir::Location loc, fir::FirOpBuilder &builder,
// for MERGE with polymorphic results. // for MERGE with polymorphic results.
if (mustFinalize) if (mustFinalize)
TODO(loc, "finalizing polymorphic temporary in HLFIR"); TODO(loc, "finalizing polymorphic temporary in HLFIR");
} else if (var.getType().isa<fir::BaseBoxType, fir::BoxCharType>()) { } else if (mlir::isa<fir::BaseBoxType, fir::BoxCharType>(var.getType())) {
if (mustFinalize && !mlir::isa<fir::BaseBoxType>(var.getType())) if (mustFinalize && !mlir::isa<fir::BaseBoxType>(var.getType()))
fir::emitFatalError(loc, "non-finalizable variable"); fir::emitFatalError(loc, "non-finalizable variable");
addr = builder.create<fir::BoxAddrOp>(loc, heapType, var); addr = builder.create<fir::BoxAddrOp>(loc, heapType, var);
} else { } else {
if (!var.getType().isa<fir::HeapType>()) if (!mlir::isa<fir::HeapType>(var.getType()))
addr = builder.create<fir::ConvertOp>(loc, heapType, var); addr = builder.create<fir::ConvertOp>(loc, heapType, var);
if (mustFinalize || deallocComponents) { if (mustFinalize || deallocComponents) {
@ -831,7 +831,7 @@ struct ElementalOpConversion
// the assign, insert an hlfir.destroy to mark the expression end-of-life. // the assign, insert an hlfir.destroy to mark the expression end-of-life.
// If the expression creation allocated a buffer on the heap inside the // If the expression creation allocated a buffer on the heap inside the
// loop, this will ensure the buffer properly deallocated. // loop, this will ensure the buffer properly deallocated.
if (elementValue.getType().isa<hlfir::ExprType>() && if (mlir::isa<hlfir::ExprType>(elementValue.getType()) &&
wasCreatedInCurrentBlock(elementValue, builder)) wasCreatedInCurrentBlock(elementValue, builder))
builder.create<hlfir::DestroyOp>(loc, elementValue); builder.create<hlfir::DestroyOp>(loc, elementValue);
} }
@ -926,11 +926,12 @@ public:
hlfir::EndAssociateOp, hlfir::SetLengthOp>(); hlfir::EndAssociateOp, hlfir::SetLengthOp>();
target.markUnknownOpDynamicallyLegal([](mlir::Operation *op) { target.markUnknownOpDynamicallyLegal([](mlir::Operation *op) {
return llvm::all_of( return llvm::all_of(op->getResultTypes(),
op->getResultTypes(), [](mlir::Type ty) {
[](mlir::Type ty) { return !ty.isa<hlfir::ExprType>(); }) && return !mlir::isa<hlfir::ExprType>(ty);
}) &&
llvm::all_of(op->getOperandTypes(), [](mlir::Type ty) { llvm::all_of(op->getOperandTypes(), [](mlir::Type ty) {
return !ty.isa<hlfir::ExprType>(); return !mlir::isa<hlfir::ExprType>(ty);
}); });
}); });
if (mlir::failed( if (mlir::failed(

View File

@ -34,7 +34,7 @@ using namespace mlir;
static mlir::Value genAllocatableTempFromSourceBox(mlir::Location loc, static mlir::Value genAllocatableTempFromSourceBox(mlir::Location loc,
fir::FirOpBuilder &builder, fir::FirOpBuilder &builder,
mlir::Value sourceBox) { mlir::Value sourceBox) {
assert(sourceBox.getType().isa<fir::BaseBoxType>() && assert(mlir::isa<fir::BaseBoxType>(sourceBox.getType()) &&
"must be a base box type"); "must be a base box type");
// Use the runtime to make a quick and dirty temp with the rhs value. // Use the runtime to make a quick and dirty temp with the rhs value.
// Overkill for scalar rhs that could be done in much more clever ways. // Overkill for scalar rhs that could be done in much more clever ways.
@ -44,7 +44,7 @@ static mlir::Value genAllocatableTempFromSourceBox(mlir::Location loc,
// This has the huge benefit of dealing with all cases, including // This has the huge benefit of dealing with all cases, including
// polymorphic entities. // polymorphic entities.
mlir::Type fromHeapType = fir::HeapType::get(fir::unwrapRefType( mlir::Type fromHeapType = fir::HeapType::get(fir::unwrapRefType(
sourceBox.getType().cast<fir::BaseBoxType>().getEleTy())); mlir::cast<fir::BaseBoxType>(sourceBox.getType()).getEleTy()));
mlir::Type fromBoxHeapType = fir::BoxType::get(fromHeapType); mlir::Type fromBoxHeapType = fir::BoxType::get(fromHeapType);
mlir::Value fromMutableBox = mlir::Value fromMutableBox =
fir::factory::genNullBoxStorage(builder, loc, fromBoxHeapType); fir::factory::genNullBoxStorage(builder, loc, fromBoxHeapType);
@ -69,7 +69,7 @@ public:
auto module = assignOp->getParentOfType<mlir::ModuleOp>(); auto module = assignOp->getParentOfType<mlir::ModuleOp>();
fir::FirOpBuilder builder(rewriter, module); fir::FirOpBuilder builder(rewriter, module);
if (rhs.getType().isa<hlfir::ExprType>()) { if (mlir::isa<hlfir::ExprType>(rhs.getType())) {
mlir::emitError(loc, "hlfir must be bufferized with --bufferize-hlfir " mlir::emitError(loc, "hlfir must be bufferized with --bufferize-hlfir "
"pass before being converted to FIR"); "pass before being converted to FIR");
return mlir::failure(); return mlir::failure();
@ -343,16 +343,15 @@ public:
auto firBase = firDeclareOp.getResult(); auto firBase = firDeclareOp.getResult();
mlir::Value hlfirBase; mlir::Value hlfirBase;
mlir::Type hlfirBaseType = declareOp.getBase().getType(); mlir::Type hlfirBaseType = declareOp.getBase().getType();
if (hlfirBaseType.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(hlfirBaseType)) {
fir::FirOpBuilder builder(rewriter, declareOp.getOperation()); fir::FirOpBuilder builder(rewriter, declareOp.getOperation());
// Helper to generate the hlfir fir.box with the local lower bounds and // Helper to generate the hlfir fir.box with the local lower bounds and
// type parameters. // type parameters.
auto genHlfirBox = [&]() -> mlir::Value { auto genHlfirBox = [&]() -> mlir::Value {
if (!firBase.getType().isa<fir::BaseBoxType>()) { if (!mlir::isa<fir::BaseBoxType>(firBase.getType())) {
llvm::SmallVector<mlir::Value> typeParams; llvm::SmallVector<mlir::Value> typeParams;
auto maybeCharType = auto maybeCharType = mlir::dyn_cast<fir::CharacterType>(
fir::unwrapSequenceType(fir::unwrapPassByRefType(hlfirBaseType)) fir::unwrapSequenceType(fir::unwrapPassByRefType(hlfirBaseType)));
.dyn_cast<fir::CharacterType>();
if (!maybeCharType || maybeCharType.hasDynamicLen()) if (!maybeCharType || maybeCharType.hasDynamicLen())
typeParams.append(declareOp.getTypeparams().begin(), typeParams.append(declareOp.getTypeparams().begin(),
declareOp.getTypeparams().end()); declareOp.getTypeparams().end());
@ -399,7 +398,7 @@ public:
}) })
.getResults()[0]; .getResults()[0];
} }
} else if (hlfirBaseType.isa<fir::BoxCharType>()) { } else if (mlir::isa<fir::BoxCharType>(hlfirBaseType)) {
assert(declareOp.getTypeparams().size() == 1 && assert(declareOp.getTypeparams().size() == 1 &&
"must contain character length"); "must contain character length");
hlfirBase = rewriter.create<fir::EmboxCharOp>( hlfirBase = rewriter.create<fir::EmboxCharOp>(
@ -480,11 +479,12 @@ public:
// - scalar%scalar_component [substring|complex_part] or // - scalar%scalar_component [substring|complex_part] or
// - scalar%static_size_array_comp // - scalar%static_size_array_comp
// - scalar%array(indices) [substring| complex part] // - scalar%array(indices) [substring| complex part]
mlir::Type componentType = baseEleTy.cast<fir::RecordType>().getType( mlir::Type componentType =
designate.getComponent().value()); mlir::cast<fir::RecordType>(baseEleTy).getType(
designate.getComponent().value());
mlir::Type coorTy = fir::ReferenceType::get(componentType); mlir::Type coorTy = fir::ReferenceType::get(componentType);
base = builder.create<fir::CoordinateOp>(loc, coorTy, base, fieldIndex); base = builder.create<fir::CoordinateOp>(loc, coorTy, base, fieldIndex);
if (componentType.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(componentType)) {
auto variableInterface = mlir::cast<fir::FortranVariableOpInterface>( auto variableInterface = mlir::cast<fir::FortranVariableOpInterface>(
designate.getOperation()); designate.getOperation());
if (variableInterface.isAllocatable() || if (variableInterface.isAllocatable() ||
@ -500,14 +500,14 @@ public:
} else { } else {
// array%component[(indices) substring|complex part] cases. // array%component[(indices) substring|complex part] cases.
// Component ref of array bases are dealt with below in embox/rebox. // Component ref of array bases are dealt with below in embox/rebox.
assert(designateResultType.isa<fir::BaseBoxType>()); assert(mlir::isa<fir::BaseBoxType>(designateResultType));
} }
} }
if (designateResultType.isa<fir::BaseBoxType>()) { if (mlir::isa<fir::BaseBoxType>(designateResultType)) {
// Generate embox or rebox. // Generate embox or rebox.
mlir::Type eleTy = fir::unwrapPassByRefType(designateResultType); mlir::Type eleTy = fir::unwrapPassByRefType(designateResultType);
bool isScalarDesignator = !eleTy.isa<fir::SequenceType>(); bool isScalarDesignator = !mlir::isa<fir::SequenceType>(eleTy);
mlir::Value sourceBox; mlir::Value sourceBox;
if (isScalarDesignator) { if (isScalarDesignator) {
// The base box will be used for emboxing the scalar element. // The base box will be used for emboxing the scalar element.
@ -583,7 +583,7 @@ public:
assert(sliceFields.empty() && substring.empty()); assert(sliceFields.empty() && substring.empty());
llvm::SmallVector<mlir::Type> resultType{designateResultType}; llvm::SmallVector<mlir::Type> resultType{designateResultType};
mlir::Value resultBox; mlir::Value resultBox;
if (base.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(base.getType()))
resultBox = resultBox =
builder.create<fir::ReboxOp>(loc, resultType, base, shape, slice); builder.create<fir::ReboxOp>(loc, resultType, base, shape, slice);
else else
@ -598,7 +598,8 @@ public:
// first element of a contiguous array section with compile time constant // first element of a contiguous array section with compile time constant
// shape. The base may be an array, or a scalar. // shape. The base may be an array, or a scalar.
mlir::Type resultAddressType = designateResultType; mlir::Type resultAddressType = designateResultType;
if (auto boxCharType = designateResultType.dyn_cast<fir::BoxCharType>()) if (auto boxCharType =
mlir::dyn_cast<fir::BoxCharType>(designateResultType))
resultAddressType = fir::ReferenceType::get(boxCharType.getEleTy()); resultAddressType = fir::ReferenceType::get(boxCharType.getEleTy());
// Array element indexing. // Array element indexing.
@ -620,7 +621,7 @@ public:
// Scalar complex part ref // Scalar complex part ref
if (designate.getComplexPart()) { if (designate.getComplexPart()) {
// Sequence types should have already been handled by this point // Sequence types should have already been handled by this point
assert(!designateResultType.isa<fir::SequenceType>()); assert(!mlir::isa<fir::SequenceType>(designateResultType));
auto index = builder.createIntegerConstant(loc, builder.getIndexType(), auto index = builder.createIntegerConstant(loc, builder.getIndexType(),
*designate.getComplexPart()); *designate.getComplexPart());
auto coorTy = fir::ReferenceType::get(resultEleTy); auto coorTy = fir::ReferenceType::get(resultEleTy);
@ -628,7 +629,7 @@ public:
} }
// Cast/embox the computed scalar address if needed. // Cast/embox the computed scalar address if needed.
if (designateResultType.isa<fir::BoxCharType>()) { if (mlir::isa<fir::BoxCharType>(designateResultType)) {
assert(designate.getTypeparams().size() == 1 && assert(designate.getTypeparams().size() == 1 &&
"must have character length"); "must have character length");
auto emboxChar = builder.create<fir::EmboxCharOp>( auto emboxChar = builder.create<fir::EmboxCharOp>(
@ -671,13 +672,13 @@ public:
mlir::PatternRewriter &rewriter) const override { mlir::PatternRewriter &rewriter) const override {
mlir::Location loc = parentComponent.getLoc(); mlir::Location loc = parentComponent.getLoc();
mlir::Type resultType = parentComponent.getType(); mlir::Type resultType = parentComponent.getType();
if (!parentComponent.getType().isa<fir::BoxType>()) { if (!mlir::isa<fir::BoxType>(parentComponent.getType())) {
mlir::Value baseAddr = parentComponent.getMemref(); mlir::Value baseAddr = parentComponent.getMemref();
// Scalar parent component ref without any length type parameters. The // Scalar parent component ref without any length type parameters. The
// input may be a fir.class if it is polymorphic, since this is a scalar // input may be a fir.class if it is polymorphic, since this is a scalar
// and the output will be monomorphic, the base address can be extracted // and the output will be monomorphic, the base address can be extracted
// from the fir.class. // from the fir.class.
if (baseAddr.getType().isa<fir::BaseBoxType>()) if (mlir::isa<fir::BaseBoxType>(baseAddr.getType()))
baseAddr = rewriter.create<fir::BoxAddrOp>(loc, baseAddr); baseAddr = rewriter.create<fir::BoxAddrOp>(loc, baseAddr);
rewriter.replaceOpWithNewOp<fir::ConvertOp>(parentComponent, resultType, rewriter.replaceOpWithNewOp<fir::ConvertOp>(parentComponent, resultType,
baseAddr); baseAddr);
@ -686,7 +687,7 @@ public:
// Array parent component ref or PDTs. // Array parent component ref or PDTs.
hlfir::Entity base{parentComponent.getMemref()}; hlfir::Entity base{parentComponent.getMemref()};
mlir::Value baseAddr = base.getBase(); mlir::Value baseAddr = base.getBase();
if (!baseAddr.getType().isa<fir::BaseBoxType>()) { if (!mlir::isa<fir::BaseBoxType>(baseAddr.getType())) {
// Embox cannot directly be used to address parent components: it expects // Embox cannot directly be used to address parent components: it expects
// the output type to match the input type when there are no slices. When // the output type to match the input type when there are no slices. When
// the types have at least one component, a slice to the first element can // the types have at least one component, a slice to the first element can
@ -748,7 +749,7 @@ public:
// the hlfir.shape_of operation which led to the creation of this get_extent // the hlfir.shape_of operation which led to the creation of this get_extent
// operation should now have been lowered to a fir.shape operation // operation should now have been lowered to a fir.shape operation
if (auto s = mlir::dyn_cast_or_null<fir::ShapeOp>(shapeOp)) { if (auto s = mlir::dyn_cast_or_null<fir::ShapeOp>(shapeOp)) {
fir::ShapeType shapeTy = shape.getType().cast<fir::ShapeType>(); fir::ShapeType shapeTy = mlir::cast<fir::ShapeType>(shape.getType());
llvm::APInt dim = getExtentOp.getDim(); llvm::APInt dim = getExtentOp.getDim();
uint64_t dimVal = dim.getLimitedValue(shapeTy.getRank()); uint64_t dimVal = dim.getLimitedValue(shapeTy.getRank());
mlir::Value extent = s.getExtents()[dimVal]; mlir::Value extent = s.getExtents()[dimVal];

View File

@ -185,7 +185,7 @@ protected:
// the width for use in runtime intrinsic calls. // the width for use in runtime intrinsic calls.
static unsigned getKindForType(mlir::Type ty) { static unsigned getKindForType(mlir::Type ty) {
mlir::Type eltty = hlfir::getFortranElementType(ty); mlir::Type eltty = hlfir::getFortranElementType(ty);
unsigned width = eltty.cast<mlir::IntegerType>().getWidth(); unsigned width = mlir::cast<mlir::IntegerType>(eltty).getWidth();
return width / 8; return width / 8;
} }

View File

@ -1090,7 +1090,7 @@ void OrderedAssignmentRewriter::generateSaveEntity(
mlir::Value loopExtent = mlir::Value loopExtent =
computeLoopNestIterationNumber(loc, builder, loopNest); computeLoopNestIterationNumber(loc, builder, loopNest);
auto sequenceType = auto sequenceType =
builder.getVarLenSeqTy(entityType).cast<fir::SequenceType>(); mlir::cast<fir::SequenceType>(builder.getVarLenSeqTy(entityType));
temp = insertSavedEntity(region, temp = insertSavedEntity(region,
fir::factory::HomogeneousScalarStack{ fir::factory::HomogeneousScalarStack{
loc, builder, sequenceType, loopExtent, loc, builder, sequenceType, loopExtent,

View File

@ -249,7 +249,7 @@ static bool areIdenticalOrDisjointSlices(mlir::Value ref1, mlir::Value ref2) {
auto isPositiveConstant = [](mlir::Value v) -> bool { auto isPositiveConstant = [](mlir::Value v) -> bool {
if (auto conOp = if (auto conOp =
mlir::dyn_cast<mlir::arith::ConstantOp>(v.getDefiningOp())) mlir::dyn_cast<mlir::arith::ConstantOp>(v.getDefiningOp()))
if (auto iattr = conOp.getValue().dyn_cast<mlir::IntegerAttr>()) if (auto iattr = mlir::dyn_cast<mlir::IntegerAttr>(conOp.getValue()))
return iattr.getInt() > 0; return iattr.getInt() > 0;
return false; return false;
}; };
@ -601,7 +601,7 @@ mlir::LogicalResult VariableAssignBufferization::matchAndRewrite(
// TODO: ExprType check is here to avoid conflicts with // TODO: ExprType check is here to avoid conflicts with
// ElementalAssignBufferization pattern. We need to combine // ElementalAssignBufferization pattern. We need to combine
// these matchers into a single one that applies to AssignOp. // these matchers into a single one that applies to AssignOp.
if (rhs.getType().isa<hlfir::ExprType>()) if (mlir::isa<hlfir::ExprType>(rhs.getType()))
return rewriter.notifyMatchFailure(assign, "RHS is not in memory"); return rewriter.notifyMatchFailure(assign, "RHS is not in memory");
if (!rhs.isArray()) if (!rhs.isArray())
@ -834,7 +834,7 @@ public:
unsigned rank = mlir::cast<hlfir::ExprType>(mloc.getType()).getShape()[0]; unsigned rank = mlir::cast<hlfir::ExprType>(mloc.getType()).getShape()[0];
mlir::Type arrayType = array.getType(); mlir::Type arrayType = array.getType();
if (!arrayType.isa<fir::BoxType>()) if (!mlir::isa<fir::BoxType>(arrayType))
return rewriter.notifyMatchFailure( return rewriter.notifyMatchFailure(
mloc, "Currently requires a boxed type input"); mloc, "Currently requires a boxed type input");
mlir::Type elementType = hlfir::getFortranElementType(arrayType); mlir::Type elementType = hlfir::getFortranElementType(arrayType);
@ -850,7 +850,7 @@ public:
auto init = [isMax](fir::FirOpBuilder builder, mlir::Location loc, auto init = [isMax](fir::FirOpBuilder builder, mlir::Location loc,
mlir::Type elementType) { mlir::Type elementType) {
if (auto ty = elementType.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(elementType)) {
const llvm::fltSemantics &sem = ty.getFloatSemantics(); const llvm::fltSemantics &sem = ty.getFloatSemantics();
llvm::APFloat limit = llvm::APFloat::getInf(sem, /*Negative=*/isMax); llvm::APFloat limit = llvm::APFloat::getInf(sem, /*Negative=*/isMax);
return builder.createRealConstant(loc, elementType, limit); return builder.createRealConstant(loc, elementType, limit);
@ -901,7 +901,7 @@ public:
// Compare with the max reduction value // Compare with the max reduction value
mlir::Value cmp; mlir::Value cmp;
if (elementType.isa<mlir::FloatType>()) { if (mlir::isa<mlir::FloatType>(elementType)) {
// For FP reductions we want the first smallest value to be used, that // For FP reductions we want the first smallest value to be used, that
// is not NaN. A OGL/OLT condition will usually work for this unless all // is not NaN. A OGL/OLT condition will usually work for this unless all
// the values are Nan or Inf. This follows the same logic as // the values are Nan or Inf. This follows the same logic as
@ -918,7 +918,7 @@ public:
loc, mlir::arith::CmpFPredicate::OEQ, elem, elem); loc, mlir::arith::CmpFPredicate::OEQ, elem, elem);
cmpNan = builder.create<mlir::arith::AndIOp>(loc, cmpNan, cmpNan2); cmpNan = builder.create<mlir::arith::AndIOp>(loc, cmpNan, cmpNan2);
cmp = builder.create<mlir::arith::OrIOp>(loc, cmp, cmpNan); cmp = builder.create<mlir::arith::OrIOp>(loc, cmp, cmpNan);
} else if (elementType.isa<mlir::IntegerType>()) { } else if (mlir::isa<mlir::IntegerType>(elementType)) {
cmp = builder.create<mlir::arith::CmpIOp>( cmp = builder.create<mlir::arith::CmpIOp>(
loc, loc,
isMax ? mlir::arith::CmpIPredicate::sgt isMax ? mlir::arith::CmpIPredicate::sgt

View File

@ -103,7 +103,8 @@ public:
// by hlfir.elemental) // by hlfir.elemental)
target.addDynamicallyLegalOp<hlfir::TransposeOp>( target.addDynamicallyLegalOp<hlfir::TransposeOp>(
[](hlfir::TransposeOp transpose) { [](hlfir::TransposeOp transpose) {
return transpose.getType().cast<hlfir::ExprType>().isPolymorphic(); return mlir::cast<hlfir::ExprType>(transpose.getType())
.isPolymorphic();
}); });
target.markUnknownOpDynamicallyLegal( target.markUnknownOpDynamicallyLegal(
[](mlir::Operation *) { return true; }); [](mlir::Operation *) { return true; });

View File

@ -65,14 +65,14 @@ static mlir::FunctionType getCPtrFunctionType(mlir::FunctionType funcTy) {
auto resultType = funcTy.getResult(0); auto resultType = funcTy.getResult(0);
assert(fir::isa_builtin_cptr_type(resultType)); assert(fir::isa_builtin_cptr_type(resultType));
llvm::SmallVector<mlir::Type> outputTypes; llvm::SmallVector<mlir::Type> outputTypes;
auto recTy = resultType.dyn_cast<fir::RecordType>(); auto recTy = mlir::dyn_cast<fir::RecordType>(resultType);
outputTypes.emplace_back(recTy.getTypeList()[0].second); outputTypes.emplace_back(recTy.getTypeList()[0].second);
return mlir::FunctionType::get(funcTy.getContext(), funcTy.getInputs(), return mlir::FunctionType::get(funcTy.getContext(), funcTy.getInputs(),
outputTypes); outputTypes);
} }
static bool mustEmboxResult(mlir::Type resultType, bool shouldBoxResult) { static bool mustEmboxResult(mlir::Type resultType, bool shouldBoxResult) {
return resultType.isa<fir::SequenceType, fir::RecordType>() && return mlir::isa<fir::SequenceType, fir::RecordType>(resultType) &&
shouldBoxResult; shouldBoxResult;
} }
@ -114,7 +114,7 @@ public:
bool isResultBuiltinCPtr = fir::isa_builtin_cptr_type(result.getType()); bool isResultBuiltinCPtr = fir::isa_builtin_cptr_type(result.getType());
Op newOp; Op newOp;
if (isResultBuiltinCPtr) { if (isResultBuiltinCPtr) {
auto recTy = result.getType().template dyn_cast<fir::RecordType>(); auto recTy = mlir::dyn_cast<fir::RecordType>(result.getType());
newResultTypes.emplace_back(recTy.getTypeList()[0].second); newResultTypes.emplace_back(recTy.getTypeList()[0].second);
} }
@ -261,7 +261,7 @@ public:
mlir::LogicalResult mlir::LogicalResult
matchAndRewrite(fir::AddrOfOp addrOf, matchAndRewrite(fir::AddrOfOp addrOf,
mlir::PatternRewriter &rewriter) const override { mlir::PatternRewriter &rewriter) const override {
auto oldFuncTy = addrOf.getType().cast<mlir::FunctionType>(); auto oldFuncTy = mlir::cast<mlir::FunctionType>(addrOf.getType());
mlir::FunctionType newFuncTy; mlir::FunctionType newFuncTy;
// TODO: This should be generalized for derived types, and it is // TODO: This should be generalized for derived types, and it is
// architecture and OS dependent. // architecture and OS dependent.
@ -296,7 +296,7 @@ public:
auto loc = func.getLoc(); auto loc = func.getLoc();
auto *context = &getContext(); auto *context = &getContext();
// Convert function type itself if it has an abstract result. // Convert function type itself if it has an abstract result.
auto funcTy = func.getFunctionType().cast<mlir::FunctionType>(); auto funcTy = mlir::cast<mlir::FunctionType>(func.getFunctionType());
if (hasAbstractResult(funcTy)) { if (hasAbstractResult(funcTy)) {
// TODO: This should be generalized for derived types, and it is // TODO: This should be generalized for derived types, and it is
// architecture and OS dependent. // architecture and OS dependent.
@ -343,11 +343,11 @@ public:
return mlir::TypeSwitch<mlir::Type, bool>(type) return mlir::TypeSwitch<mlir::Type, bool>(type)
.Case([](fir::BoxProcType boxProc) { .Case([](fir::BoxProcType boxProc) {
return fir::hasAbstractResult( return fir::hasAbstractResult(
boxProc.getEleTy().cast<mlir::FunctionType>()); mlir::cast<mlir::FunctionType>(boxProc.getEleTy()));
}) })
.Case([](fir::PointerType pointer) { .Case([](fir::PointerType pointer) {
return fir::hasAbstractResult( return fir::hasAbstractResult(
pointer.getEleTy().cast<mlir::FunctionType>()); mlir::cast<mlir::FunctionType>(pointer.getEleTy()));
}) })
.Default([](auto &&) { return false; }); .Default([](auto &&) { return false; });
} }
@ -411,7 +411,7 @@ public:
return !hasAbstractResult(call.getFunctionType()); return !hasAbstractResult(call.getFunctionType());
}); });
target.addDynamicallyLegalOp<fir::AddrOfOp>([](fir::AddrOfOp addrOf) { target.addDynamicallyLegalOp<fir::AddrOfOp>([](fir::AddrOfOp addrOf) {
if (auto funTy = addrOf.getType().dyn_cast<mlir::FunctionType>()) if (auto funTy = mlir::dyn_cast<mlir::FunctionType>(addrOf.getType()))
return !hasAbstractResult(funTy); return !hasAbstractResult(funTy);
return true; return true;
}); });

View File

@ -69,7 +69,7 @@ void AddDebugInfoPass::runOnOperation() {
// In that case, 'inputFilename' may be empty. Location embedded in the // In that case, 'inputFilename' may be empty. Location embedded in the
// module will be used to get file name and its directory. // module will be used to get file name and its directory.
if (inputFilename.empty()) { if (inputFilename.empty()) {
if (auto fileLoc = module.getLoc().dyn_cast<mlir::FileLineColLoc>()) { if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(module.getLoc())) {
fileName = llvm::sys::path::filename(fileLoc.getFilename().getValue()); fileName = llvm::sys::path::filename(fileLoc.getFilename().getValue());
filePath = llvm::sys::path::parent_path(fileLoc.getFilename().getValue()); filePath = llvm::sys::path::parent_path(fileLoc.getFilename().getValue());
} else } else
@ -94,14 +94,14 @@ void AddDebugInfoPass::runOnOperation() {
mlir::Location l = funcOp->getLoc(); mlir::Location l = funcOp->getLoc();
// If fused location has already been created then nothing to do // If fused location has already been created then nothing to do
// Otherwise, create a fused location. // Otherwise, create a fused location.
if (l.dyn_cast<mlir::FusedLoc>()) if (mlir::dyn_cast<mlir::FusedLoc>(l))
return; return;
unsigned int CC = (funcOp.getName() == fir::NameUniquer::doProgramEntry()) unsigned int CC = (funcOp.getName() == fir::NameUniquer::doProgramEntry())
? llvm::dwarf::getCallingConvention("DW_CC_program") ? llvm::dwarf::getCallingConvention("DW_CC_program")
: llvm::dwarf::getCallingConvention("DW_CC_normal"); : llvm::dwarf::getCallingConvention("DW_CC_normal");
if (auto funcLoc = l.dyn_cast<mlir::FileLineColLoc>()) { if (auto funcLoc = mlir::dyn_cast<mlir::FileLineColLoc>(l)) {
fileName = llvm::sys::path::filename(funcLoc.getFilename().getValue()); fileName = llvm::sys::path::filename(funcLoc.getFilename().getValue());
filePath = llvm::sys::path::parent_path(funcLoc.getFilename().getValue()); filePath = llvm::sys::path::parent_path(funcLoc.getFilename().getValue());
} }

View File

@ -98,14 +98,15 @@ public:
mlir::LogicalResult mlir::LogicalResult
matchAndRewrite(fir::ConvertOp op, matchAndRewrite(fir::ConvertOp op,
mlir::PatternRewriter &rewriter) const override { mlir::PatternRewriter &rewriter) const override {
if (op.getRes().getType().isa<mlir::MemRefType>()) { if (mlir::isa<mlir::MemRefType>(op.getRes().getType())) {
// due to index calculation moving to affine maps we still need to // due to index calculation moving to affine maps we still need to
// add converts for sequence types this has a side effect of losing // add converts for sequence types this has a side effect of losing
// some information about arrays with known dimensions by creating: // some information about arrays with known dimensions by creating:
// fir.convert %arg0 : (!fir.ref<!fir.array<5xi32>>) -> // fir.convert %arg0 : (!fir.ref<!fir.array<5xi32>>) ->
// !fir.ref<!fir.array<?xi32>> // !fir.ref<!fir.array<?xi32>>
if (auto refTy = op.getValue().getType().dyn_cast<fir::ReferenceType>()) if (auto refTy =
if (auto arrTy = refTy.getEleTy().dyn_cast<fir::SequenceType>()) { mlir::dyn_cast<fir::ReferenceType>(op.getValue().getType()))
if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(refTy.getEleTy())) {
fir::SequenceType::Shape flatShape = { fir::SequenceType::Shape flatShape = {
fir::SequenceType::getUnknownExtent()}; fir::SequenceType::getUnknownExtent()};
auto flatArrTy = fir::SequenceType::get(flatShape, arrTy.getEleTy()); auto flatArrTy = fir::SequenceType::get(flatShape, arrTy.getEleTy());
@ -158,7 +159,7 @@ public:
mlir::ConversionTarget target(*context); mlir::ConversionTarget target(*context);
target.addIllegalOp<memref::AllocOp>(); target.addIllegalOp<memref::AllocOp>();
target.addDynamicallyLegalOp<fir::ConvertOp>([](fir::ConvertOp op) { target.addDynamicallyLegalOp<fir::ConvertOp>([](fir::ConvertOp op) {
if (op.getRes().getType().isa<mlir::MemRefType>()) if (mlir::isa<mlir::MemRefType>(op.getRes().getType()))
return false; return false;
return true; return true;
}); });

View File

@ -111,7 +111,7 @@ private:
bool analyzeReference(mlir::Value memref, mlir::Operation *op) { bool analyzeReference(mlir::Value memref, mlir::Operation *op) {
if (auto acoOp = memref.getDefiningOp<ArrayCoorOp>()) { if (auto acoOp = memref.getDefiningOp<ArrayCoorOp>()) {
if (acoOp.getMemref().getType().isa<fir::BoxType>()) { if (mlir::isa<fir::BoxType>(acoOp.getMemref().getType())) {
// TODO: Look if and how fir.box can be promoted to affine. // TODO: Look if and how fir.box can be promoted to affine.
LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: cannot promote loop, " LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: cannot promote loop, "
"array memory operation uses fir.box\n"; "array memory operation uses fir.box\n";
@ -222,7 +222,7 @@ private:
return affineBinaryOp(mlir::AffineExprKind::Mod, op.getLhs(), return affineBinaryOp(mlir::AffineExprKind::Mod, op.getLhs(),
op.getRhs()); op.getRhs());
if (auto op = value.getDefiningOp<mlir::arith::ConstantOp>()) if (auto op = value.getDefiningOp<mlir::arith::ConstantOp>())
if (auto intConstant = op.getValue().dyn_cast<IntegerAttr>()) if (auto intConstant = mlir::dyn_cast<IntegerAttr>(op.getValue()))
return toAffineExpr(intConstant.getInt()); return toAffineExpr(intConstant.getInt());
if (auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(value)) { if (auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(value)) {
affineArgs.push_back(value); affineArgs.push_back(value);
@ -331,15 +331,16 @@ static mlir::AffineMap createArrayIndexAffineMap(unsigned dimensions,
static std::optional<int64_t> constantIntegerLike(const mlir::Value value) { static std::optional<int64_t> constantIntegerLike(const mlir::Value value) {
if (auto definition = value.getDefiningOp<mlir::arith::ConstantOp>()) if (auto definition = value.getDefiningOp<mlir::arith::ConstantOp>())
if (auto stepAttr = definition.getValue().dyn_cast<IntegerAttr>()) if (auto stepAttr = mlir::dyn_cast<IntegerAttr>(definition.getValue()))
return stepAttr.getInt(); return stepAttr.getInt();
return {}; return {};
} }
static mlir::Type coordinateArrayElement(fir::ArrayCoorOp op) { static mlir::Type coordinateArrayElement(fir::ArrayCoorOp op) {
if (auto refType = if (auto refType =
op.getMemref().getType().dyn_cast_or_null<ReferenceType>()) { mlir::dyn_cast_or_null<ReferenceType>(op.getMemref().getType())) {
if (auto seqType = refType.getEleTy().dyn_cast_or_null<SequenceType>()) { if (auto seqType =
mlir::dyn_cast_or_null<SequenceType>(refType.getEleTy())) {
return seqType.getEleTy(); return seqType.getEleTy();
} }
} }

View File

@ -461,9 +461,9 @@ void ArrayCopyAnalysisBase::arrayMentions(
} }
static bool hasPointerType(mlir::Type type) { static bool hasPointerType(mlir::Type type) {
if (auto boxTy = type.dyn_cast<BoxType>()) if (auto boxTy = mlir::dyn_cast<BoxType>(type))
type = boxTy.getEleTy(); type = boxTy.getEleTy();
return type.isa<fir::PointerType>(); return mlir::isa<fir::PointerType>(type);
} }
// This is a NF performance hack. It makes a simple test that the slices of the // This is a NF performance hack. It makes a simple test that the slices of the
@ -512,7 +512,7 @@ static bool mutuallyExclusiveSliceRange(ArrayLoadOp ld, ArrayMergeStoreOp st) {
auto isPositiveConstant = [](mlir::Value v) -> bool { auto isPositiveConstant = [](mlir::Value v) -> bool {
if (auto conOp = if (auto conOp =
mlir::dyn_cast<mlir::arith::ConstantOp>(v.getDefiningOp())) mlir::dyn_cast<mlir::arith::ConstantOp>(v.getDefiningOp()))
if (auto iattr = conOp.getValue().dyn_cast<mlir::IntegerAttr>()) if (auto iattr = mlir::dyn_cast<mlir::IntegerAttr>(conOp.getValue()))
return iattr.getInt() > 0; return iattr.getInt() > 0;
return false; return false;
}; };
@ -725,8 +725,8 @@ static bool
conservativeCallConflict(llvm::ArrayRef<mlir::Operation *> reaches) { conservativeCallConflict(llvm::ArrayRef<mlir::Operation *> reaches) {
return llvm::any_of(reaches, [](mlir::Operation *op) { return llvm::any_of(reaches, [](mlir::Operation *op) {
if (auto call = mlir::dyn_cast<fir::CallOp>(op)) if (auto call = mlir::dyn_cast<fir::CallOp>(op))
if (auto callee = if (auto callee = mlir::dyn_cast<mlir::SymbolRefAttr>(
call.getCallableForCallee().dyn_cast<mlir::SymbolRefAttr>()) { call.getCallableForCallee())) {
auto module = op->getParentOfType<mlir::ModuleOp>(); auto module = op->getParentOfType<mlir::ModuleOp>();
return isInternalProcedure( return isInternalProcedure(
module.lookupSymbol<mlir::func::FuncOp>(callee)); module.lookupSymbol<mlir::func::FuncOp>(callee));
@ -891,9 +891,9 @@ static mlir::Value getOrReadExtentsAndShapeOp(
if (arrLoad->hasAttr(fir::getOptionalAttrName())) if (arrLoad->hasAttr(fir::getOptionalAttrName()))
fir::emitFatalError( fir::emitFatalError(
loc, "shapes from array load of OPTIONAL arrays must not be used"); loc, "shapes from array load of OPTIONAL arrays must not be used");
if (auto boxTy = arrLoad.getMemref().getType().dyn_cast<BoxType>()) { if (auto boxTy = mlir::dyn_cast<BoxType>(arrLoad.getMemref().getType())) {
auto rank = auto rank =
dyn_cast_ptrOrBoxEleTy(boxTy).cast<SequenceType>().getDimension(); mlir::cast<SequenceType>(dyn_cast_ptrOrBoxEleTy(boxTy)).getDimension();
auto idxTy = rewriter.getIndexType(); auto idxTy = rewriter.getIndexType();
for (decltype(rank) dim = 0; dim < rank; ++dim) { for (decltype(rank) dim = 0; dim < rank; ++dim) {
auto dimVal = rewriter.create<mlir::arith::ConstantIndexOp>(loc, dim); auto dimVal = rewriter.create<mlir::arith::ConstantIndexOp>(loc, dim);
@ -929,7 +929,7 @@ static mlir::Type toRefType(mlir::Type ty) {
static llvm::SmallVector<mlir::Value> static llvm::SmallVector<mlir::Value>
getTypeParamsIfRawData(mlir::Location loc, FirOpBuilder &builder, getTypeParamsIfRawData(mlir::Location loc, FirOpBuilder &builder,
ArrayLoadOp arrLoad, mlir::Type ty) { ArrayLoadOp arrLoad, mlir::Type ty) {
if (ty.isa<BoxType>()) if (mlir::isa<BoxType>(ty))
return {}; return {};
return fir::factory::getTypeParams(loc, builder, arrLoad); return fir::factory::getTypeParams(loc, builder, arrLoad);
} }
@ -947,8 +947,8 @@ static mlir::Value genCoorOp(mlir::PatternRewriter &rewriter,
originated = factory::originateIndices(loc, rewriter, alloc.getType(), originated = factory::originateIndices(loc, rewriter, alloc.getType(),
shape, indices); shape, indices);
auto seqTy = dyn_cast_ptrOrBoxEleTy(alloc.getType()); auto seqTy = dyn_cast_ptrOrBoxEleTy(alloc.getType());
assert(seqTy && seqTy.isa<SequenceType>()); assert(seqTy && mlir::isa<SequenceType>(seqTy));
const auto dimension = seqTy.cast<SequenceType>().getDimension(); const auto dimension = mlir::cast<SequenceType>(seqTy).getDimension();
auto module = load->getParentOfType<mlir::ModuleOp>(); auto module = load->getParentOfType<mlir::ModuleOp>();
FirOpBuilder builder(rewriter, module); FirOpBuilder builder(rewriter, module);
auto typeparams = getTypeParamsIfRawData(loc, builder, load, alloc.getType()); auto typeparams = getTypeParamsIfRawData(loc, builder, load, alloc.getType());
@ -967,7 +967,7 @@ static mlir::Value getCharacterLen(mlir::Location loc, FirOpBuilder &builder,
ArrayLoadOp load, CharacterType charTy) { ArrayLoadOp load, CharacterType charTy) {
auto charLenTy = builder.getCharacterLengthType(); auto charLenTy = builder.getCharacterLengthType();
if (charTy.hasDynamicLen()) { if (charTy.hasDynamicLen()) {
if (load.getMemref().getType().isa<BoxType>()) { if (mlir::isa<BoxType>(load.getMemref().getType())) {
// The loaded array is an emboxed value. Get the CHARACTER length from // The loaded array is an emboxed value. Get the CHARACTER length from
// the box value. // the box value.
auto eleSzInBytes = auto eleSzInBytes =
@ -1027,7 +1027,7 @@ void genArrayCopy(mlir::Location loc, mlir::PatternRewriter &rewriter,
getTypeParamsIfRawData(loc, builder, arrLoad, dst.getType())); getTypeParamsIfRawData(loc, builder, arrLoad, dst.getType()));
auto eleTy = unwrapSequenceType(unwrapPassByRefType(dst.getType())); auto eleTy = unwrapSequenceType(unwrapPassByRefType(dst.getType()));
// Copy from (to) object to (from) temp copy of same object. // Copy from (to) object to (from) temp copy of same object.
if (auto charTy = eleTy.dyn_cast<CharacterType>()) { if (auto charTy = mlir::dyn_cast<CharacterType>(eleTy)) {
auto len = getCharacterLen(loc, builder, arrLoad, charTy); auto len = getCharacterLen(loc, builder, arrLoad, charTy);
CharBoxValue toChar(toAddr, len); CharBoxValue toChar(toAddr, len);
CharBoxValue fromChar(fromAddr, len); CharBoxValue fromChar(fromAddr, len);
@ -1049,8 +1049,8 @@ genArrayLoadTypeParameters(mlir::Location loc, mlir::PatternRewriter &rewriter,
auto eleTy = auto eleTy =
unwrapSequenceType(unwrapPassByRefType(load.getMemref().getType())); unwrapSequenceType(unwrapPassByRefType(load.getMemref().getType()));
if (hasDynamicSize(eleTy)) { if (hasDynamicSize(eleTy)) {
if (auto charTy = eleTy.dyn_cast<CharacterType>()) { if (auto charTy = mlir::dyn_cast<CharacterType>(eleTy)) {
assert(load.getMemref().getType().isa<BoxType>()); assert(mlir::isa<BoxType>(load.getMemref().getType()));
auto module = load->getParentOfType<mlir::ModuleOp>(); auto module = load->getParentOfType<mlir::ModuleOp>();
FirOpBuilder builder(rewriter, module); FirOpBuilder builder(rewriter, module);
return {getCharacterLen(loc, builder, load, charTy)}; return {getCharacterLen(loc, builder, load, charTy)};
@ -1067,7 +1067,7 @@ findNonconstantExtents(mlir::Type memrefTy,
llvm::ArrayRef<mlir::Value> extents) { llvm::ArrayRef<mlir::Value> extents) {
llvm::SmallVector<mlir::Value> nce; llvm::SmallVector<mlir::Value> nce;
auto arrTy = unwrapPassByRefType(memrefTy); auto arrTy = unwrapPassByRefType(memrefTy);
auto seqTy = arrTy.cast<SequenceType>(); auto seqTy = mlir::cast<SequenceType>(arrTy);
for (auto [s, x] : llvm::zip(seqTy.getShape(), extents)) for (auto [s, x] : llvm::zip(seqTy.getShape(), extents))
if (s == SequenceType::getUnknownExtent()) if (s == SequenceType::getUnknownExtent())
nce.emplace_back(x); nce.emplace_back(x);

View File

@ -60,8 +60,8 @@ public:
// For each code point in the `from` string, convert naively to the `to` // For each code point in the `from` string, convert naively to the `to`
// string code point. Conversion is done blindly on size only, not value. // string code point. Conversion is done blindly on size only, not value.
auto getCharBits = [&](mlir::Type t) { auto getCharBits = [&](mlir::Type t) {
auto chrTy = fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t)) auto chrTy = mlir::cast<fir::CharacterType>(
.cast<fir::CharacterType>(); fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t)));
return kindMap.getCharacterBitsize(chrTy.getFKind()); return kindMap.getCharacterBitsize(chrTy.getFKind());
}; };
auto fromBits = getCharBits(conv.getFrom().getType()); auto fromBits = getCharBits(conv.getFrom().getType());

View File

@ -147,7 +147,7 @@ struct ArgsUsageInLoop {
static fir::SequenceType getAsSequenceType(mlir::Value *v) { static fir::SequenceType getAsSequenceType(mlir::Value *v) {
mlir::Type argTy = fir::unwrapPassByRefType(fir::unwrapRefType(v->getType())); mlir::Type argTy = fir::unwrapPassByRefType(fir::unwrapRefType(v->getType()));
return argTy.dyn_cast<fir::SequenceType>(); return mlir::dyn_cast<fir::SequenceType>(argTy);
} }
/// if a value comes from a fir.declare, follow it to the original source, /// if a value comes from a fir.declare, follow it to the original source,

View File

@ -65,7 +65,7 @@ keepStackAllocation(fir::AllocaOp alloca, mlir::Block *entry,
// TODO: Generalize the algorithm and placement of the freemem nodes. // TODO: Generalize the algorithm and placement of the freemem nodes.
if (alloca->getBlock() != entry) if (alloca->getBlock() != entry)
return true; return true;
if (auto seqTy = alloca.getInType().dyn_cast<fir::SequenceType>()) { if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(alloca.getInType())) {
if (fir::hasDynamicSize(seqTy)) { if (fir::hasDynamicSize(seqTy)) {
// Move all arrays with runtime determined size to the heap. // Move all arrays with runtime determined size to the heap.
if (options.dynamicArrayOnHeap) if (options.dynamicArrayOnHeap)

View File

@ -97,8 +97,8 @@ struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {
// Get derived type information. // Get derived type information.
mlir::Type declaredType = mlir::Type declaredType =
fir::getDerivedType(dispatch.getObject().getType().getEleTy()); fir::getDerivedType(dispatch.getObject().getType().getEleTy());
assert(declaredType.isa<fir::RecordType>() && "expecting fir.type"); assert(mlir::isa<fir::RecordType>(declaredType) && "expecting fir.type");
auto recordType = declaredType.dyn_cast<fir::RecordType>(); auto recordType = mlir::dyn_cast<fir::RecordType>(declaredType);
// Lookup for the binding table. // Lookup for the binding table.
auto bindingsIter = bindingTables.find(recordType.getName()); auto bindingsIter = bindingTables.find(recordType.getName());
@ -157,7 +157,7 @@ struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {
// Load the bindings descriptor. // Load the bindings descriptor.
auto bindingsCompName = Fortran::semantics::bindingDescCompName; auto bindingsCompName = Fortran::semantics::bindingDescCompName;
fir::RecordType typeDescRecTy = typeDescTy.cast<fir::RecordType>(); fir::RecordType typeDescRecTy = mlir::cast<fir::RecordType>(typeDescTy);
mlir::Value field = rewriter.create<fir::FieldIndexOp>( mlir::Value field = rewriter.create<fir::FieldIndexOp>(
loc, fieldTy, bindingsCompName, typeDescRecTy, mlir::ValueRange{}); loc, fieldTy, bindingsCompName, typeDescRecTy, mlir::ValueRange{});
mlir::Type coorTy = mlir::Type coorTy =
@ -168,8 +168,8 @@ struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {
// Load the correct binding. // Load the correct binding.
mlir::Value bindings = rewriter.create<fir::BoxAddrOp>(loc, bindingBox); mlir::Value bindings = rewriter.create<fir::BoxAddrOp>(loc, bindingBox);
fir::RecordType bindingTy = fir::RecordType bindingTy = fir::unwrapIfDerived(
fir::unwrapIfDerived(bindingBox.getType().cast<fir::BaseBoxType>()); mlir::cast<fir::BaseBoxType>(bindingBox.getType()));
mlir::Type bindingAddrTy = fir::ReferenceType::get(bindingTy); mlir::Type bindingAddrTy = fir::ReferenceType::get(bindingTy);
mlir::Value bindingIdxVal = rewriter.create<mlir::arith::ConstantOp>( mlir::Value bindingIdxVal = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(), rewriter.getIndexAttr(bindingIdx)); loc, rewriter.getIndexType(), rewriter.getIndexAttr(bindingIdx));
@ -181,7 +181,7 @@ struct DispatchOpConv : public OpConversionPattern<fir::DispatchOp> {
mlir::Value procField = rewriter.create<fir::FieldIndexOp>( mlir::Value procField = rewriter.create<fir::FieldIndexOp>(
loc, fieldTy, procCompName, bindingTy, mlir::ValueRange{}); loc, fieldTy, procCompName, bindingTy, mlir::ValueRange{});
fir::RecordType procTy = fir::RecordType procTy =
bindingTy.getType(procCompName).cast<fir::RecordType>(); mlir::cast<fir::RecordType>(bindingTy.getType(procCompName));
mlir::Type procRefTy = fir::ReferenceType::get(procTy); mlir::Type procRefTy = fir::ReferenceType::get(procTy);
mlir::Value procRef = rewriter.create<fir::CoordinateOp>( mlir::Value procRef = rewriter.create<fir::CoordinateOp>(
loc, procRefTy, bindingAddr, procField); loc, procRefTy, bindingAddr, procField);
@ -298,13 +298,13 @@ mlir::LogicalResult SelectTypeConv::matchAndRewrite(
// before in the list to respect point 3. above. Otherwise it is just // before in the list to respect point 3. above. Otherwise it is just
// added in order at the end. // added in order at the end.
for (unsigned t = 0; t < typeGuardNum; ++t) { for (unsigned t = 0; t < typeGuardNum; ++t) {
if (auto a = typeGuards[t].dyn_cast<fir::ExactTypeAttr>()) { if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(typeGuards[t])) {
orderedTypeGuards.push_back(t); orderedTypeGuards.push_back(t);
continue; continue;
} }
if (auto a = typeGuards[t].dyn_cast<fir::SubclassAttr>()) { if (auto a = mlir::dyn_cast<fir::SubclassAttr>(typeGuards[t])) {
if (auto recTy = a.getType().dyn_cast<fir::RecordType>()) { if (auto recTy = mlir::dyn_cast<fir::RecordType>(a.getType())) {
auto dt = mod.lookupSymbol<fir::TypeInfoOp>(recTy.getName()); auto dt = mod.lookupSymbol<fir::TypeInfoOp>(recTy.getName());
assert(dt && "dispatch table not found"); assert(dt && "dispatch table not found");
llvm::SmallSet<llvm::StringRef, 4> ancestors = llvm::SmallSet<llvm::StringRef, 4> ancestors =
@ -313,8 +313,8 @@ mlir::LogicalResult SelectTypeConv::matchAndRewrite(
auto it = orderedClassIsGuards.begin(); auto it = orderedClassIsGuards.begin();
while (it != orderedClassIsGuards.end()) { while (it != orderedClassIsGuards.end()) {
fir::SubclassAttr sAttr = fir::SubclassAttr sAttr =
typeGuards[*it].dyn_cast<fir::SubclassAttr>(); mlir::dyn_cast<fir::SubclassAttr>(typeGuards[*it]);
if (auto ty = sAttr.getType().dyn_cast<fir::RecordType>()) { if (auto ty = mlir::dyn_cast<fir::RecordType>(sAttr.getType())) {
if (ancestors.contains(ty.getName())) if (ancestors.contains(ty.getName()))
break; break;
} }
@ -339,7 +339,7 @@ mlir::LogicalResult SelectTypeConv::matchAndRewrite(
auto *dest = selectType.getSuccessor(idx); auto *dest = selectType.getSuccessor(idx);
std::optional<mlir::ValueRange> destOps = std::optional<mlir::ValueRange> destOps =
selectType.getSuccessorOperands(operands, idx); selectType.getSuccessorOperands(operands, idx);
if (typeGuards[idx].dyn_cast<mlir::UnitAttr>()) if (mlir::dyn_cast<mlir::UnitAttr>(typeGuards[idx]))
rewriter.replaceOpWithNewOp<mlir::cf::BranchOp>( rewriter.replaceOpWithNewOp<mlir::cf::BranchOp>(
selectType, dest, destOps.value_or(mlir::ValueRange{})); selectType, dest, destOps.value_or(mlir::ValueRange{}));
else if (mlir::failed(genTypeLadderStep(loc, selector, typeGuards[idx], else if (mlir::failed(genTypeLadderStep(loc, selector, typeGuards[idx],
@ -357,9 +357,9 @@ mlir::LogicalResult SelectTypeConv::genTypeLadderStep(
fir::KindMapping &kindMap) const { fir::KindMapping &kindMap) const {
mlir::Value cmp; mlir::Value cmp;
// TYPE IS type guard comparison are all done inlined. // TYPE IS type guard comparison are all done inlined.
if (auto a = attr.dyn_cast<fir::ExactTypeAttr>()) { if (auto a = mlir::dyn_cast<fir::ExactTypeAttr>(attr)) {
if (fir::isa_trivial(a.getType()) || if (fir::isa_trivial(a.getType()) ||
a.getType().isa<fir::CharacterType>()) { mlir::isa<fir::CharacterType>(a.getType())) {
// For type guard statement with Intrinsic type spec the type code of // For type guard statement with Intrinsic type spec the type code of
// the descriptor is compared. // the descriptor is compared.
int code = fir::getTypeCode(a.getType(), kindMap); int code = fir::getTypeCode(a.getType(), kindMap);
@ -383,10 +383,10 @@ mlir::LogicalResult SelectTypeConv::genTypeLadderStep(
cmp = res; cmp = res;
} }
// CLASS IS type guard statement is done with a runtime call. // CLASS IS type guard statement is done with a runtime call.
} else if (auto a = attr.dyn_cast<fir::SubclassAttr>()) { } else if (auto a = mlir::dyn_cast<fir::SubclassAttr>(attr)) {
// Retrieve the type descriptor from the type guard statement record type. // Retrieve the type descriptor from the type guard statement record type.
assert(a.getType().isa<fir::RecordType>() && "expect fir.record type"); assert(mlir::isa<fir::RecordType>(a.getType()) && "expect fir.record type");
fir::RecordType recTy = a.getType().dyn_cast<fir::RecordType>(); fir::RecordType recTy = mlir::dyn_cast<fir::RecordType>(a.getType());
std::string typeDescName = std::string typeDescName =
fir::NameUniquer::getTypeDescriptorName(recTy.getName()); fir::NameUniquer::getTypeDescriptorName(recTy.getName());
auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName); auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);
@ -438,8 +438,8 @@ mlir::Value
SelectTypeConv::genTypeDescCompare(mlir::Location loc, mlir::Value selector, SelectTypeConv::genTypeDescCompare(mlir::Location loc, mlir::Value selector,
mlir::Type ty, mlir::ModuleOp mod, mlir::Type ty, mlir::ModuleOp mod,
mlir::PatternRewriter &rewriter) const { mlir::PatternRewriter &rewriter) const {
assert(ty.isa<fir::RecordType>() && "expect fir.record type"); assert(mlir::isa<fir::RecordType>(ty) && "expect fir.record type");
fir::RecordType recTy = ty.dyn_cast<fir::RecordType>(); fir::RecordType recTy = mlir::dyn_cast<fir::RecordType>(ty);
std::string typeDescName = std::string typeDescName =
fir::NameUniquer::getTypeDescriptorName(recTy.getName()); fir::NameUniquer::getTypeDescriptorName(recTy.getName());
auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName); auto typeDescGlobal = mod.lookupSymbol<fir::GlobalOp>(typeDescName);

View File

@ -215,8 +215,8 @@ static unsigned getDimCount(mlir::Value val) {
// the first ConvertOp that has non-opaque box type that we meet // the first ConvertOp that has non-opaque box type that we meet
// going through the ConvertOp chain. // going through the ConvertOp chain.
if (mlir::Value emboxVal = findBoxDef(val)) if (mlir::Value emboxVal = findBoxDef(val))
if (auto boxTy = emboxVal.getType().dyn_cast<fir::BoxType>()) if (auto boxTy = mlir::dyn_cast<fir::BoxType>(emboxVal.getType()))
if (auto seqTy = boxTy.getEleTy().dyn_cast<fir::SequenceType>()) if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(boxTy.getEleTy()))
return seqTy.getDimension(); return seqTy.getDimension();
return 0; return 0;
} }
@ -237,9 +237,9 @@ static std::optional<mlir::Type> getArgElementType(mlir::Value val) {
val = defOp->getOperand(0); val = defOp->getOperand(0);
// The convert operation is expected to convert from one // The convert operation is expected to convert from one
// box type to another box type. // box type to another box type.
auto boxType = val.getType().cast<fir::BoxType>(); auto boxType = mlir::cast<fir::BoxType>(val.getType());
auto elementType = fir::unwrapSeqOrBoxedSeqType(boxType); auto elementType = fir::unwrapSeqOrBoxedSeqType(boxType);
if (!elementType.isa<mlir::NoneType>()) if (!mlir::isa<mlir::NoneType>(elementType))
return elementType; return elementType;
} while (true); } while (true);
} }
@ -381,7 +381,7 @@ static void genRuntimeSumBody(fir::FirOpBuilder &builder,
// end function RTNAME(Sum)<T>x<rank>_simplified // end function RTNAME(Sum)<T>x<rank>_simplified
auto zero = [](fir::FirOpBuilder builder, mlir::Location loc, auto zero = [](fir::FirOpBuilder builder, mlir::Location loc,
mlir::Type elementType) { mlir::Type elementType) {
if (auto ty = elementType.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(elementType)) {
const llvm::fltSemantics &sem = ty.getFloatSemantics(); const llvm::fltSemantics &sem = ty.getFloatSemantics();
return builder.createRealConstant(loc, elementType, return builder.createRealConstant(loc, elementType,
llvm::APFloat::getZero(sem)); llvm::APFloat::getZero(sem));
@ -392,9 +392,9 @@ static void genRuntimeSumBody(fir::FirOpBuilder &builder,
auto genBodyOp = [](fir::FirOpBuilder builder, mlir::Location loc, auto genBodyOp = [](fir::FirOpBuilder builder, mlir::Location loc,
mlir::Type elementType, mlir::Value elem1, mlir::Type elementType, mlir::Value elem1,
mlir::Value elem2) -> mlir::Value { mlir::Value elem2) -> mlir::Value {
if (elementType.isa<mlir::FloatType>()) if (mlir::isa<mlir::FloatType>(elementType))
return builder.create<mlir::arith::AddFOp>(loc, elem1, elem2); return builder.create<mlir::arith::AddFOp>(loc, elem1, elem2);
if (elementType.isa<mlir::IntegerType>()) if (mlir::isa<mlir::IntegerType>(elementType))
return builder.create<mlir::arith::AddIOp>(loc, elem1, elem2); return builder.create<mlir::arith::AddIOp>(loc, elem1, elem2);
llvm_unreachable("unsupported type"); llvm_unreachable("unsupported type");
@ -414,7 +414,7 @@ static void genRuntimeMaxvalBody(fir::FirOpBuilder &builder,
mlir::Type elementType) { mlir::Type elementType) {
auto init = [](fir::FirOpBuilder builder, mlir::Location loc, auto init = [](fir::FirOpBuilder builder, mlir::Location loc,
mlir::Type elementType) { mlir::Type elementType) {
if (auto ty = elementType.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(elementType)) {
const llvm::fltSemantics &sem = ty.getFloatSemantics(); const llvm::fltSemantics &sem = ty.getFloatSemantics();
return builder.createRealConstant( return builder.createRealConstant(
loc, elementType, llvm::APFloat::getLargest(sem, /*Negative=*/true)); loc, elementType, llvm::APFloat::getLargest(sem, /*Negative=*/true));
@ -427,7 +427,7 @@ static void genRuntimeMaxvalBody(fir::FirOpBuilder &builder,
auto genBodyOp = [](fir::FirOpBuilder builder, mlir::Location loc, auto genBodyOp = [](fir::FirOpBuilder builder, mlir::Location loc,
mlir::Type elementType, mlir::Value elem1, mlir::Type elementType, mlir::Value elem1,
mlir::Value elem2) -> mlir::Value { mlir::Value elem2) -> mlir::Value {
if (elementType.isa<mlir::FloatType>()) { if (mlir::isa<mlir::FloatType>(elementType)) {
// arith.maxf later converted to llvm.intr.maxnum does not work // arith.maxf later converted to llvm.intr.maxnum does not work
// correctly for NaNs and -0.0 (see maxnum/minnum pattern matching // correctly for NaNs and -0.0 (see maxnum/minnum pattern matching
// in LLVM's InstCombine pass). Moreover, llvm.intr.maxnum // in LLVM's InstCombine pass). Moreover, llvm.intr.maxnum
@ -439,7 +439,7 @@ static void genRuntimeMaxvalBody(fir::FirOpBuilder &builder,
loc, mlir::arith::CmpFPredicate::OGT, elem1, elem2); loc, mlir::arith::CmpFPredicate::OGT, elem1, elem2);
return builder.create<mlir::arith::SelectOp>(loc, compare, elem1, elem2); return builder.create<mlir::arith::SelectOp>(loc, compare, elem1, elem2);
} }
if (elementType.isa<mlir::IntegerType>()) if (mlir::isa<mlir::IntegerType>(elementType))
return builder.create<mlir::arith::MaxSIOp>(loc, elem1, elem2); return builder.create<mlir::arith::MaxSIOp>(loc, elem1, elem2);
llvm_unreachable("unsupported type"); llvm_unreachable("unsupported type");
@ -662,7 +662,7 @@ static void genRuntimeMinMaxlocBody(fir::FirOpBuilder &builder,
mlir::Type resultElemTy, bool isDim) { mlir::Type resultElemTy, bool isDim) {
auto init = [isMax](fir::FirOpBuilder builder, mlir::Location loc, auto init = [isMax](fir::FirOpBuilder builder, mlir::Location loc,
mlir::Type elementType) { mlir::Type elementType) {
if (auto ty = elementType.dyn_cast<mlir::FloatType>()) { if (auto ty = mlir::dyn_cast<mlir::FloatType>(elementType)) {
const llvm::fltSemantics &sem = ty.getFloatSemantics(); const llvm::fltSemantics &sem = ty.getFloatSemantics();
llvm::APFloat limit = llvm::APFloat::getInf(sem, /*Negative=*/isMax); llvm::APFloat limit = llvm::APFloat::getInf(sem, /*Negative=*/isMax);
return builder.createRealConstant(loc, elementType, limit); return builder.createRealConstant(loc, elementType, limit);
@ -744,7 +744,7 @@ static void genRuntimeMinMaxlocBody(fir::FirOpBuilder &builder,
mlir::Value elem = builder.create<fir::LoadOp>(loc, addr); mlir::Value elem = builder.create<fir::LoadOp>(loc, addr);
mlir::Value cmp; mlir::Value cmp;
if (elementType.isa<mlir::FloatType>()) { if (mlir::isa<mlir::FloatType>(elementType)) {
// For FP reductions we want the first smallest value to be used, that // For FP reductions we want the first smallest value to be used, that
// is not NaN. A OGL/OLT condition will usually work for this unless all // is not NaN. A OGL/OLT condition will usually work for this unless all
// the values are Nan or Inf. This follows the same logic as // the values are Nan or Inf. This follows the same logic as
@ -761,7 +761,7 @@ static void genRuntimeMinMaxlocBody(fir::FirOpBuilder &builder,
loc, mlir::arith::CmpFPredicate::OEQ, elem, elem); loc, mlir::arith::CmpFPredicate::OEQ, elem, elem);
cmpNan = builder.create<mlir::arith::AndIOp>(loc, cmpNan, cmpNan2); cmpNan = builder.create<mlir::arith::AndIOp>(loc, cmpNan, cmpNan2);
cmp = builder.create<mlir::arith::OrIOp>(loc, cmp, cmpNan); cmp = builder.create<mlir::arith::OrIOp>(loc, cmp, cmpNan);
} else if (elementType.isa<mlir::IntegerType>()) { } else if (mlir::isa<mlir::IntegerType>(elementType)) {
cmp = builder.create<mlir::arith::CmpIOp>( cmp = builder.create<mlir::arith::CmpIOp>(
loc, loc,
isMax ? mlir::arith::CmpIPredicate::sgt isMax ? mlir::arith::CmpIPredicate::sgt
@ -839,7 +839,7 @@ static void genRuntimeMinMaxlocBody(fir::FirOpBuilder &builder,
builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
mlir::Value basicValue; mlir::Value basicValue;
if (elementType.isa<mlir::IntegerType>()) { if (mlir::isa<mlir::IntegerType>(elementType)) {
basicValue = builder.createIntegerConstant(loc, elementType, 0); basicValue = builder.createIntegerConstant(loc, elementType, 0);
} else { } else {
basicValue = builder.createRealConstant(loc, elementType, 0); basicValue = builder.createRealConstant(loc, elementType, 0);
@ -921,7 +921,7 @@ static void genRuntimeDotBody(fir::FirOpBuilder &builder,
mlir::IndexType idxTy = builder.getIndexType(); mlir::IndexType idxTy = builder.getIndexType();
mlir::Value zero = mlir::Value zero =
resultElementType.isa<mlir::FloatType>() mlir::isa<mlir::FloatType>(resultElementType)
? builder.createRealConstant(loc, resultElementType, 0.0) ? builder.createRealConstant(loc, resultElementType, 0.0)
: builder.createIntegerConstant(loc, resultElementType, 0); : builder.createIntegerConstant(loc, resultElementType, 0);
@ -978,10 +978,10 @@ static void genRuntimeDotBody(fir::FirOpBuilder &builder,
// Convert to the result type. // Convert to the result type.
elem2 = builder.create<fir::ConvertOp>(loc, resultElementType, elem2); elem2 = builder.create<fir::ConvertOp>(loc, resultElementType, elem2);
if (resultElementType.isa<mlir::FloatType>()) if (mlir::isa<mlir::FloatType>(resultElementType))
sumVal = builder.create<mlir::arith::AddFOp>( sumVal = builder.create<mlir::arith::AddFOp>(
loc, builder.create<mlir::arith::MulFOp>(loc, elem1, elem2), sumVal); loc, builder.create<mlir::arith::MulFOp>(loc, elem1, elem2), sumVal);
else if (resultElementType.isa<mlir::IntegerType>()) else if (mlir::isa<mlir::IntegerType>(resultElementType))
sumVal = builder.create<mlir::arith::AddIOp>( sumVal = builder.create<mlir::arith::AddIOp>(
loc, builder.create<mlir::arith::MulIOp>(loc, elem1, elem2), sumVal); loc, builder.create<mlir::arith::MulIOp>(loc, elem1, elem2), sumVal);
else else
@ -1056,8 +1056,8 @@ void SimplifyIntrinsicsPass::simplifyIntOrFloatReduction(
mlir::Type resultType = call.getResult(0).getType(); mlir::Type resultType = call.getResult(0).getType();
if (!resultType.isa<mlir::FloatType>() && if (!mlir::isa<mlir::FloatType>(resultType) &&
!resultType.isa<mlir::IntegerType>()) !mlir::isa<mlir::IntegerType>(resultType))
return; return;
auto argType = getArgElementType(args[0]); auto argType = getArgElementType(args[0]);
@ -1103,7 +1103,8 @@ void SimplifyIntrinsicsPass::simplifyLogicalDim0Reduction(
fir::FirOpBuilder builder{getSimplificationBuilder(call, kindMap)}; fir::FirOpBuilder builder{getSimplificationBuilder(call, kindMap)};
// Treating logicals as integers makes things a lot easier // Treating logicals as integers makes things a lot easier
fir::LogicalType logicalType = {elementType.dyn_cast<fir::LogicalType>()}; fir::LogicalType logicalType = {
mlir::dyn_cast<fir::LogicalType>(elementType)};
fir::KindTy kind = logicalType.getFKind(); fir::KindTy kind = logicalType.getFKind();
mlir::Type intElementType = builder.getIntegerType(kind * 8); mlir::Type intElementType = builder.getIntegerType(kind * 8);
@ -1138,7 +1139,8 @@ void SimplifyIntrinsicsPass::simplifyLogicalDim1Reduction(
fir::FirOpBuilder builder{getSimplificationBuilder(call, kindMap)}; fir::FirOpBuilder builder{getSimplificationBuilder(call, kindMap)};
// Treating logicals as integers makes things a lot easier // Treating logicals as integers makes things a lot easier
fir::LogicalType logicalType = {elementType.dyn_cast<fir::LogicalType>()}; fir::LogicalType logicalType = {
mlir::dyn_cast<fir::LogicalType>(elementType)};
fir::KindTy kind = logicalType.getFKind(); fir::KindTy kind = logicalType.getFKind();
mlir::Type intElementType = builder.getIntegerType(kind * 8); mlir::Type intElementType = builder.getIntegerType(kind * 8);
@ -1182,7 +1184,7 @@ void SimplifyIntrinsicsPass::simplifyMinMaxlocReduction(
auto inputBox = findBoxDef(args[1]); auto inputBox = findBoxDef(args[1]);
mlir::Type inputType = hlfir::getFortranElementType(inputBox.getType()); mlir::Type inputType = hlfir::getFortranElementType(inputBox.getType());
if (inputType.isa<fir::CharacterType>()) if (mlir::isa<fir::CharacterType>(inputType))
return; return;
int maskRank; int maskRank;
@ -1193,7 +1195,8 @@ void SimplifyIntrinsicsPass::simplifyMinMaxlocReduction(
} else { } else {
maskRank = getDimCount(mask); maskRank = getDimCount(mask);
mlir::Type maskElemTy = hlfir::getFortranElementType(maskDef.getType()); mlir::Type maskElemTy = hlfir::getFortranElementType(maskDef.getType());
fir::LogicalType logicalFirType = {maskElemTy.dyn_cast<fir::LogicalType>()}; fir::LogicalType logicalFirType = {
mlir::dyn_cast<fir::LogicalType>(maskElemTy)};
kind = logicalFirType.getFKind(); kind = logicalFirType.getFKind();
// Convert fir::LogicalType to mlir::Type // Convert fir::LogicalType to mlir::Type
logicalElemType = logicalFirType; logicalElemType = logicalFirType;
@ -1302,7 +1305,8 @@ void SimplifyIntrinsicsPass::runOnOperation() {
std::string fmfString{builder.getFastMathFlagsString()}; std::string fmfString{builder.getFastMathFlagsString()};
mlir::Type type = call.getResult(0).getType(); mlir::Type type = call.getResult(0).getType();
if (!type.isa<mlir::FloatType>() && !type.isa<mlir::IntegerType>()) if (!mlir::isa<mlir::FloatType>(type) &&
!mlir::isa<mlir::IntegerType>(type))
return; return;
// Try to find the element types of the boxed arguments. // Try to find the element types of the boxed arguments.

View File

@ -351,7 +351,7 @@ void AllocationAnalysis::visitOperation(mlir::Operation *op,
} }
auto retTy = allocmem.getAllocatedType(); auto retTy = allocmem.getAllocatedType();
if (!retTy.isa<fir::SequenceType>()) { if (!mlir::isa<fir::SequenceType>(retTy)) {
LLVM_DEBUG(llvm::dbgs() LLVM_DEBUG(llvm::dbgs()
<< "--Allocation is not for an array: skipping\n"); << "--Allocation is not for an array: skipping\n");
return; return;

View File

@ -96,6 +96,6 @@ TEST_F(ComplexTest, verifyConvertWithSemantics) {
// Convert complex to integer // Convert complex to integer
mlir::Value v2 = firBuilder->convertWithSemantics(loc, integerTy1, v1); mlir::Value v2 = firBuilder->convertWithSemantics(loc, integerTy1, v1);
EXPECT_TRUE(v2.getType().isa<mlir::IntegerType>()); EXPECT_TRUE(mlir::isa<mlir::IntegerType>(v2.getType()));
EXPECT_TRUE(mlir::dyn_cast<fir::ConvertOp>(v2.getDefiningOp())); EXPECT_TRUE(mlir::dyn_cast<fir::ConvertOp>(v2.getDefiningOp()));
} }

View File

@ -34,7 +34,7 @@ public:
void checkConstantValue(const mlir::Value &value, int64_t v) { void checkConstantValue(const mlir::Value &value, int64_t v) {
EXPECT_TRUE(mlir::isa<mlir::arith::ConstantOp>(value.getDefiningOp())); EXPECT_TRUE(mlir::isa<mlir::arith::ConstantOp>(value.getDefiningOp()));
auto cstOp = dyn_cast<mlir::arith::ConstantOp>(value.getDefiningOp()); auto cstOp = dyn_cast<mlir::arith::ConstantOp>(value.getDefiningOp());
auto valueAttr = cstOp.getValue().dyn_cast_or_null<IntegerAttr>(); auto valueAttr = dyn_cast_or_null<IntegerAttr>(cstOp.getValue());
EXPECT_EQ(v, valueAttr.getInt()); EXPECT_EQ(v, valueAttr.getInt());
} }

View File

@ -54,7 +54,7 @@ static void checkIntegerConstant(mlir::Value value, mlir::Type ty, int64_t v) {
EXPECT_TRUE(mlir::isa<mlir::arith::ConstantOp>(value.getDefiningOp())); EXPECT_TRUE(mlir::isa<mlir::arith::ConstantOp>(value.getDefiningOp()));
auto cstOp = dyn_cast<mlir::arith::ConstantOp>(value.getDefiningOp()); auto cstOp = dyn_cast<mlir::arith::ConstantOp>(value.getDefiningOp());
EXPECT_EQ(ty, cstOp.getType()); EXPECT_EQ(ty, cstOp.getType());
auto valueAttr = cstOp.getValue().dyn_cast_or_null<IntegerAttr>(); auto valueAttr = mlir::dyn_cast_or_null<IntegerAttr>(cstOp.getValue());
EXPECT_EQ(v, valueAttr.getInt()); EXPECT_EQ(v, valueAttr.getInt());
} }
@ -151,7 +151,7 @@ TEST_F(FIRBuilderTest, createRealZeroConstant) {
auto cstOp = dyn_cast<arith::ConstantOp>(cst.getDefiningOp()); auto cstOp = dyn_cast<arith::ConstantOp>(cst.getDefiningOp());
EXPECT_EQ(realTy, cstOp.getType()); EXPECT_EQ(realTy, cstOp.getType());
EXPECT_EQ( EXPECT_EQ(
0u, cstOp.getValue().cast<FloatAttr>().getValue().convertToDouble()); 0u, mlir::cast<FloatAttr>(cstOp.getValue()).getValue().convertToDouble());
} }
TEST_F(FIRBuilderTest, createBool) { TEST_F(FIRBuilderTest, createBool) {
@ -164,8 +164,8 @@ TEST_F(FIRBuilderTest, createBool) {
TEST_F(FIRBuilderTest, getVarLenSeqTy) { TEST_F(FIRBuilderTest, getVarLenSeqTy) {
auto builder = getBuilder(); auto builder = getBuilder();
auto ty = builder.getVarLenSeqTy(builder.getI64Type()); auto ty = builder.getVarLenSeqTy(builder.getI64Type());
EXPECT_TRUE(ty.isa<fir::SequenceType>()); EXPECT_TRUE(mlir::isa<fir::SequenceType>(ty));
fir::SequenceType seqTy = ty.dyn_cast<fir::SequenceType>(); fir::SequenceType seqTy = mlir::dyn_cast<fir::SequenceType>(ty);
EXPECT_EQ(1u, seqTy.getDimension()); EXPECT_EQ(1u, seqTy.getDimension());
EXPECT_TRUE(fir::unwrapSequenceType(ty).isInteger(64)); EXPECT_TRUE(fir::unwrapSequenceType(ty).isInteger(64));
} }
@ -216,9 +216,9 @@ TEST_F(FIRBuilderTest, createGlobal2) {
EXPECT_FALSE(global.getConstant().has_value()); EXPECT_FALSE(global.getConstant().has_value());
EXPECT_EQ(i32Type, global.getType()); EXPECT_EQ(i32Type, global.getType());
EXPECT_TRUE(global.getInitVal().has_value()); EXPECT_TRUE(global.getInitVal().has_value());
EXPECT_TRUE(global.getInitVal().value().isa<mlir::IntegerAttr>()); EXPECT_TRUE(mlir::isa<mlir::IntegerAttr>(global.getInitVal().value()));
EXPECT_EQ( EXPECT_EQ(16,
16, global.getInitVal().value().cast<mlir::IntegerAttr>().getValue()); mlir::cast<mlir::IntegerAttr>(global.getInitVal().value()).getValue());
EXPECT_TRUE(global.getLinkName().has_value()); EXPECT_TRUE(global.getLinkName().has_value());
EXPECT_EQ( EXPECT_EQ(
builder.createLinkOnceLinkage().getValue(), global.getLinkName().value()); builder.createLinkOnceLinkage().getValue(), global.getLinkName().value());
@ -271,12 +271,12 @@ TEST_F(FIRBuilderTest, locationToFilename) {
auto stringLitOps = global.getRegion().front().getOps<fir::StringLitOp>(); auto stringLitOps = global.getRegion().front().getOps<fir::StringLitOp>();
EXPECT_TRUE(llvm::hasSingleElement(stringLitOps)); EXPECT_TRUE(llvm::hasSingleElement(stringLitOps));
for (auto stringLit : stringLitOps) { for (auto stringLit : stringLitOps) {
EXPECT_EQ(10, stringLit.getSize().cast<mlir::IntegerAttr>().getValue()); EXPECT_EQ(
EXPECT_TRUE(stringLit.getValue().isa<StringAttr>()); 10, mlir::cast<mlir::IntegerAttr>(stringLit.getSize()).getValue());
EXPECT_TRUE(mlir::isa<StringAttr>(stringLit.getValue()));
EXPECT_EQ(0, EXPECT_EQ(0,
strcmp("file1.f90\0", strcmp("file1.f90\0",
stringLit.getValue() mlir::dyn_cast<StringAttr>(stringLit.getValue())
.dyn_cast<StringAttr>()
.getValue() .getValue()
.str() .str()
.c_str())); .c_str()));
@ -288,9 +288,9 @@ TEST_F(FIRBuilderTest, createStringLitOp) {
llvm::StringRef data("mystringlitdata"); llvm::StringRef data("mystringlitdata");
auto loc = builder.getUnknownLoc(); auto loc = builder.getUnknownLoc();
auto op = builder.createStringLitOp(loc, data); auto op = builder.createStringLitOp(loc, data);
EXPECT_EQ(15, op.getSize().cast<mlir::IntegerAttr>().getValue()); EXPECT_EQ(15, mlir::cast<mlir::IntegerAttr>(op.getSize()).getValue());
EXPECT_TRUE(op.getValue().isa<StringAttr>()); EXPECT_TRUE(mlir::isa<StringAttr>(op.getValue()));
EXPECT_EQ(data, op.getValue().dyn_cast<StringAttr>().getValue()); EXPECT_EQ(data, mlir::dyn_cast<StringAttr>(op.getValue()).getValue());
} }
TEST_F(FIRBuilderTest, createStringLiteral) { TEST_F(FIRBuilderTest, createStringLiteral) {
@ -318,9 +318,11 @@ TEST_F(FIRBuilderTest, createStringLiteral) {
auto stringLitOps = global.getRegion().front().getOps<fir::StringLitOp>(); auto stringLitOps = global.getRegion().front().getOps<fir::StringLitOp>();
EXPECT_TRUE(llvm::hasSingleElement(stringLitOps)); EXPECT_TRUE(llvm::hasSingleElement(stringLitOps));
for (auto stringLit : stringLitOps) { for (auto stringLit : stringLitOps) {
EXPECT_EQ(16, stringLit.getSize().cast<mlir::IntegerAttr>().getValue()); EXPECT_EQ(
EXPECT_TRUE(stringLit.getValue().isa<StringAttr>()); 16, mlir::cast<mlir::IntegerAttr>(stringLit.getSize()).getValue());
EXPECT_EQ(strValue, stringLit.getValue().dyn_cast<StringAttr>().getValue()); EXPECT_TRUE(mlir::isa<StringAttr>(stringLit.getValue()));
EXPECT_EQ(
strValue, mlir::dyn_cast<StringAttr>(stringLit.getValue()).getValue());
} }
} }
@ -344,7 +346,7 @@ TEST_F(FIRBuilderTest, allocateLocal) {
static void checkShapeOp(mlir::Value shape, mlir::Value c10, mlir::Value c100) { static void checkShapeOp(mlir::Value shape, mlir::Value c10, mlir::Value c100) {
EXPECT_TRUE(mlir::isa<fir::ShapeOp>(shape.getDefiningOp())); EXPECT_TRUE(mlir::isa<fir::ShapeOp>(shape.getDefiningOp()));
fir::ShapeOp op = dyn_cast<fir::ShapeOp>(shape.getDefiningOp()); fir::ShapeOp op = dyn_cast<fir::ShapeOp>(shape.getDefiningOp());
auto shapeTy = op.getType().dyn_cast<fir::ShapeType>(); auto shapeTy = mlir::dyn_cast<fir::ShapeType>(op.getType());
EXPECT_EQ(2u, shapeTy.getRank()); EXPECT_EQ(2u, shapeTy.getRank());
EXPECT_EQ(2u, op.getExtents().size()); EXPECT_EQ(2u, op.getExtents().size());
EXPECT_EQ(c10, op.getExtents()[0]); EXPECT_EQ(c10, op.getExtents()[0]);
@ -372,7 +374,7 @@ TEST_F(FIRBuilderTest, genShapeWithExtentsAndShapeShift) {
auto shape = builder.genShape(loc, shifts, extents); auto shape = builder.genShape(loc, shifts, extents);
EXPECT_TRUE(mlir::isa<fir::ShapeShiftOp>(shape.getDefiningOp())); EXPECT_TRUE(mlir::isa<fir::ShapeShiftOp>(shape.getDefiningOp()));
fir::ShapeShiftOp op = dyn_cast<fir::ShapeShiftOp>(shape.getDefiningOp()); fir::ShapeShiftOp op = dyn_cast<fir::ShapeShiftOp>(shape.getDefiningOp());
auto shapeTy = op.getType().dyn_cast<fir::ShapeShiftType>(); auto shapeTy = mlir::dyn_cast<fir::ShapeShiftType>(op.getType());
EXPECT_EQ(2u, shapeTy.getRank()); EXPECT_EQ(2u, shapeTy.getRank());
EXPECT_EQ(2u, op.getExtents().size()); EXPECT_EQ(2u, op.getExtents().size());
EXPECT_EQ(2u, op.getOrigins().size()); EXPECT_EQ(2u, op.getOrigins().size());
@ -428,7 +430,7 @@ TEST_F(FIRBuilderTest, createZeroValue) {
auto cst = auto cst =
mlir::dyn_cast_or_null<mlir::arith::ConstantOp>(zeroInt.getDefiningOp()); mlir::dyn_cast_or_null<mlir::arith::ConstantOp>(zeroInt.getDefiningOp());
EXPECT_TRUE(cst); EXPECT_TRUE(cst);
auto intAttr = cst.getValue().dyn_cast<mlir::IntegerAttr>(); auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(cst.getValue());
EXPECT_TRUE(intAttr && intAttr.getInt() == 0); EXPECT_TRUE(intAttr && intAttr.getInt() == 0);
mlir::Type f32Ty = mlir::FloatType::getF32(builder.getContext()); mlir::Type f32Ty = mlir::FloatType::getF32(builder.getContext());
@ -437,7 +439,7 @@ TEST_F(FIRBuilderTest, createZeroValue) {
auto cst2 = mlir::dyn_cast_or_null<mlir::arith::ConstantOp>( auto cst2 = mlir::dyn_cast_or_null<mlir::arith::ConstantOp>(
zeroFloat.getDefiningOp()); zeroFloat.getDefiningOp());
EXPECT_TRUE(cst2); EXPECT_TRUE(cst2);
auto floatAttr = cst2.getValue().dyn_cast<mlir::FloatAttr>(); auto floatAttr = mlir::dyn_cast<mlir::FloatAttr>(cst2.getValue());
EXPECT_TRUE(floatAttr && floatAttr.getValueAsDouble() == 0.); EXPECT_TRUE(floatAttr && floatAttr.getValueAsDouble() == 0.);
mlir::Type boolTy = mlir::IntegerType::get(builder.getContext(), 1); mlir::Type boolTy = mlir::IntegerType::get(builder.getContext(), 1);
@ -446,7 +448,7 @@ TEST_F(FIRBuilderTest, createZeroValue) {
auto cst3 = mlir::dyn_cast_or_null<mlir::arith::ConstantOp>( auto cst3 = mlir::dyn_cast_or_null<mlir::arith::ConstantOp>(
flaseBool.getDefiningOp()); flaseBool.getDefiningOp());
EXPECT_TRUE(cst3); EXPECT_TRUE(cst3);
auto intAttr2 = cst.getValue().dyn_cast<mlir::IntegerAttr>(); auto intAttr2 = mlir::dyn_cast<mlir::IntegerAttr>(cst.getValue());
EXPECT_TRUE(intAttr2 && intAttr2.getInt() == 0); EXPECT_TRUE(intAttr2 && intAttr2.getInt() == 0);
} }
@ -482,7 +484,7 @@ TEST_F(FIRBuilderTest, getBaseTypeOf) {
llvm::SmallVector<fir::ExtendedValue, 4> arrays; llvm::SmallVector<fir::ExtendedValue, 4> arrays;
auto extent = builder.create<fir::UndefOp>(loc, builder.getIndexType()); auto extent = builder.create<fir::UndefOp>(loc, builder.getIndexType());
llvm::SmallVector<mlir::Value> extents( llvm::SmallVector<mlir::Value> extents(
arrayType.dyn_cast<fir::SequenceType>().getDimension(), mlir::dyn_cast<fir::SequenceType>(arrayType).getDimension(),
extent.getResult()); extent.getResult());
arrays.emplace_back(fir::ArrayBoxValue(ptrValArray, extents)); arrays.emplace_back(fir::ArrayBoxValue(ptrValArray, extents));
arrays.emplace_back(fir::BoxValue(boxValArray)); arrays.emplace_back(fir::BoxValue(boxValArray));

View File

@ -27,7 +27,7 @@ TEST(RTBuilderTest, ComplexRuntimeInterface) {
mlir::Type c99_cacosf_signature{ mlir::Type c99_cacosf_signature{
fir::runtime::RuntimeTableKey<decltype(c99_cacosf)>::getTypeModel()( fir::runtime::RuntimeTableKey<decltype(c99_cacosf)>::getTypeModel()(
&ctx)}; &ctx)};
auto c99_cacosf_funcTy = c99_cacosf_signature.cast<mlir::FunctionType>(); auto c99_cacosf_funcTy = mlir::cast<mlir::FunctionType>(c99_cacosf_signature);
EXPECT_EQ(c99_cacosf_funcTy.getNumInputs(), 1u); EXPECT_EQ(c99_cacosf_funcTy.getNumInputs(), 1u);
EXPECT_EQ(c99_cacosf_funcTy.getNumResults(), 1u); EXPECT_EQ(c99_cacosf_funcTy.getNumResults(), 1u);
auto cplx_ty = fir::ComplexType::get(&ctx, 4); auto cplx_ty = fir::ComplexType::get(&ctx, 4);

View File

@ -138,10 +138,10 @@ def Linalg_SoftmaxOp : Linalg_Op<"softmax",
let extraClassDeclaration = [{ let extraClassDeclaration = [{
ShapedType getInputOperandType() { ShapedType getInputOperandType() {
return getInput().getType().cast<ShapedType>(); return cast<ShapedType>(getInput().getType());
} }
ShapedType getOutputOperandType() { ShapedType getOutputOperandType() {
return getOutput().getType().cast<ShapedType>(); return cast<ShapedType>(getOutput().getType());
} }
int64_t getInputOperandRank() { int64_t getInputOperandRank() {
return getInputOperandType().getRank(); return getInputOperandType().getRank();

View File

@ -234,8 +234,8 @@ def OffloadModuleInterface : OpInterface<"OffloadModuleInterface"> {
/*methodName=*/"getIsTargetDevice", /*methodName=*/"getIsTargetDevice",
(ins), [{}], [{ (ins), [{}], [{
if (Attribute isTargetDevice = $_op->getAttr("omp.is_target_device")) if (Attribute isTargetDevice = $_op->getAttr("omp.is_target_device"))
if (isTargetDevice.isa<mlir::BoolAttr>()) if (::llvm::isa<mlir::BoolAttr>(isTargetDevice))
return isTargetDevice.dyn_cast<BoolAttr>().getValue(); return ::llvm::dyn_cast<BoolAttr>(isTargetDevice).getValue();
return false; return false;
}]>, }]>,
InterfaceMethod< InterfaceMethod<
@ -259,7 +259,7 @@ def OffloadModuleInterface : OpInterface<"OffloadModuleInterface"> {
/*methodName=*/"getIsGPU", /*methodName=*/"getIsGPU",
(ins), [{}], [{ (ins), [{}], [{
if (Attribute isTargetCGAttr = $_op->getAttr("omp.is_gpu")) if (Attribute isTargetCGAttr = $_op->getAttr("omp.is_gpu"))
if (auto isTargetCGVal = isTargetCGAttr.dyn_cast<BoolAttr>()) if (auto isTargetCGVal = ::llvm::dyn_cast<BoolAttr>(isTargetCGAttr))
return isTargetCGVal.getValue(); return isTargetCGVal.getValue();
return false; return false;
}]>, }]>,
@ -332,7 +332,7 @@ def OffloadModuleInterface : OpInterface<"OffloadModuleInterface"> {
/*methodName=*/"getRequires", /*methodName=*/"getRequires",
(ins), [{}], [{ (ins), [{}], [{
if (Attribute requiresAttr = $_op->getAttr("omp.requires")) if (Attribute requiresAttr = $_op->getAttr("omp.requires"))
if (auto requiresVal = requiresAttr.dyn_cast<mlir::omp::ClauseRequiresAttr>()) if (auto requiresVal = ::llvm::dyn_cast<mlir::omp::ClauseRequiresAttr>(requiresAttr))
return requiresVal.getValue(); return requiresVal.getValue();
return mlir::omp::ClauseRequires::none; return mlir::omp::ClauseRequires::none;
}]>, }]>,

View File

@ -164,10 +164,10 @@ def XeGPU_CreateNdDescOp: XeGPU_Op<"create_nd_tdesc", [Pure, ViewLikeOpInterface
/// source operand. They overide static shape from source memref type. /// source operand. They overide static shape from source memref type.
ArrayRef<int64_t> getStaticSizes() { ArrayRef<int64_t> getStaticSizes() {
auto attr = getConstShapeAttr(); auto attr = getConstShapeAttr();
if (getSourceType().isa<IntegerType>() || attr) if (llvm::isa<IntegerType>(getSourceType()) || attr)
return attr; return attr;
auto memrefType = getSourceType().dyn_cast<MemRefType>(); auto memrefType = llvm::dyn_cast<MemRefType>(getSourceType());
assert(memrefType && "Incorrect use of getStaticSizes"); assert(memrefType && "Incorrect use of getStaticSizes");
return memrefType.getShape(); return memrefType.getShape();
} }
@ -179,10 +179,10 @@ def XeGPU_CreateNdDescOp: XeGPU_Op<"create_nd_tdesc", [Pure, ViewLikeOpInterface
/// source operand. They overide static strides from source memref type. /// source operand. They overide static strides from source memref type.
ArrayRef<int64_t> getStaticStrides() { ArrayRef<int64_t> getStaticStrides() {
auto attr = getConstStridesAttr(); auto attr = getConstStridesAttr();
if (getSourceType().isa<IntegerType>() || attr) if (llvm::isa<IntegerType>(getSourceType()) || attr)
return attr; return attr;
auto memrefType = getSourceType().dyn_cast<MemRefType>(); auto memrefType = llvm::dyn_cast<MemRefType>(getSourceType());
assert(memrefType && "Incorrect use of getStaticStrides"); assert(memrefType && "Incorrect use of getStaticStrides");
auto [strides, offset] = getStridesAndOffset(memrefType); auto [strides, offset] = getStridesAndOffset(memrefType);
// reuse the storage of ConstStridesAttr since strides from // reuse the storage of ConstStridesAttr since strides from
@ -196,7 +196,7 @@ def XeGPU_CreateNdDescOp: XeGPU_Op<"create_nd_tdesc", [Pure, ViewLikeOpInterface
/// `static_shape` and `static_strides` attributes. /// `static_shape` and `static_strides` attributes.
std::array<unsigned, 3> getArrayAttrMaxRanks() { std::array<unsigned, 3> getArrayAttrMaxRanks() {
unsigned rank; unsigned rank;
if (auto ty = getSourceType().dyn_cast<MemRefType>()) { if (auto ty = llvm::dyn_cast<MemRefType>(getSourceType())) {
rank = ty.getRank(); rank = ty.getRank();
} else { } else {
rank = (unsigned)getMixedOffsets().size(); rank = (unsigned)getMixedOffsets().size();

View File

@ -228,7 +228,8 @@ def OpaqueLoc : Builtin_LocationAttr<"OpaqueLoc"> {
template <typename T> static T getUnderlyingLocation(Location location) { template <typename T> static T getUnderlyingLocation(Location location) {
assert(isa<T>(location)); assert(isa<T>(location));
return reinterpret_cast<T>( return reinterpret_cast<T>(
location.cast<mlir::OpaqueLoc>().getUnderlyingLocation()); mlir::cast<mlir::OpaqueLoc>(static_cast<LocationAttr>(location))
.getUnderlyingLocation());
} }
/// Returns a pointer to some data structure that opaque location stores. /// Returns a pointer to some data structure that opaque location stores.
@ -237,15 +238,17 @@ def OpaqueLoc : Builtin_LocationAttr<"OpaqueLoc"> {
template <typename T> template <typename T>
static T getUnderlyingLocationOrNull(Location location) { static T getUnderlyingLocationOrNull(Location location) {
return isa<T>(location) return isa<T>(location)
? reinterpret_cast<T>( ? reinterpret_cast<T>(mlir::cast<mlir::OpaqueLoc>(
location.cast<mlir::OpaqueLoc>().getUnderlyingLocation()) static_cast<LocationAttr>(location))
: T(nullptr); .getUnderlyingLocation())
: T(nullptr);
} }
/// Checks whether provided location is opaque location and contains a /// Checks whether provided location is opaque location and contains a
/// pointer to an object of particular type. /// pointer to an object of particular type.
template <typename T> static bool isa(Location location) { template <typename T> static bool isa(Location location) {
auto opaque_loc = location.dyn_cast<OpaqueLoc>(); auto opaque_loc =
mlir::dyn_cast<OpaqueLoc>(static_cast<LocationAttr>(location));
return opaque_loc && opaque_loc.getUnderlyingTypeID() == TypeID::get<T>(); return opaque_loc && opaque_loc.getUnderlyingTypeID() == TypeID::get<T>();
} }
}]; }];

View File

@ -98,25 +98,25 @@ public:
constexpr Value(detail::ValueImpl *impl = nullptr) : impl(impl) {} constexpr Value(detail::ValueImpl *impl = nullptr) : impl(impl) {}
template <typename U> template <typename U>
[[deprecated("Use isa<U>() instead")]] [[deprecated("Use mlir::isa<U>() instead")]]
bool isa() const { bool isa() const {
return llvm::isa<U>(*this); return llvm::isa<U>(*this);
} }
template <typename U> template <typename U>
[[deprecated("Use dyn_cast<U>() instead")]] [[deprecated("Use mlir::dyn_cast<U>() instead")]]
U dyn_cast() const { U dyn_cast() const {
return llvm::dyn_cast<U>(*this); return llvm::dyn_cast<U>(*this);
} }
template <typename U> template <typename U>
[[deprecated("Use dyn_cast_or_null<U>() instead")]] [[deprecated("Use mlir::dyn_cast_or_null<U>() instead")]]
U dyn_cast_or_null() const { U dyn_cast_or_null() const {
return llvm::dyn_cast_or_null<U>(*this); return llvm::dyn_cast_or_null<U>(*this);
} }
template <typename U> template <typename U>
[[deprecated("Use cast<U>() instead")]] [[deprecated("Use mlir::cast<U>() instead")]]
U cast() const { U cast() const {
return llvm::cast<U>(*this); return llvm::cast<U>(*this);
} }

View File

@ -857,7 +857,7 @@ struct SqrtOpConversion : public OpConversionPattern<complex::SqrtOp> {
ImplicitLocOpBuilder b(op.getLoc(), rewriter); ImplicitLocOpBuilder b(op.getLoc(), rewriter);
auto type = cast<ComplexType>(op.getType()); auto type = cast<ComplexType>(op.getType());
auto elementType = type.getElementType().cast<FloatType>(); auto elementType = cast<FloatType>(type.getElementType());
arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue(); arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
auto cst = [&](APFloat v) { auto cst = [&](APFloat v) {

View File

@ -172,7 +172,7 @@ Attribute RingAttr::parse(AsmParser &parser, Type type) {
if (failed(parser.parseEqual())) if (failed(parser.parseEqual()))
return {}; return {};
IntegerType iType = ty.dyn_cast<IntegerType>(); IntegerType iType = mlir::dyn_cast<IntegerType>(ty);
if (!iType) { if (!iType) {
parser.emitError(parser.getCurrentLocation(), parser.emitError(parser.getCurrentLocation(),
"coefficientType must specify an integer type"); "coefficientType must specify an integer type");

View File

@ -140,7 +140,7 @@ struct LinearizeVectorExtractStridedSlice final
ConversionPatternRewriter &rewriter) const override { ConversionPatternRewriter &rewriter) const override {
Type dstType = getTypeConverter()->convertType(extractOp.getType()); Type dstType = getTypeConverter()->convertType(extractOp.getType());
assert(!(extractOp.getVector().getType().isScalable() || assert(!(extractOp.getVector().getType().isScalable() ||
dstType.cast<VectorType>().isScalable()) && cast<VectorType>(dstType).isScalable()) &&
"scalable vectors are not supported."); "scalable vectors are not supported.");
if (!isLessThanTargetBitWidth(extractOp, targetVectorBitWidth)) if (!isLessThanTargetBitWidth(extractOp, targetVectorBitWidth))
return rewriter.notifyMatchFailure( return rewriter.notifyMatchFailure(
@ -172,7 +172,7 @@ struct LinearizeVectorExtractStridedSlice final
// Get total number of extracted slices. // Get total number of extracted slices.
int64_t nExtractedSlices = 1; int64_t nExtractedSlices = 1;
for (Attribute size : sizes) { for (Attribute size : sizes) {
nExtractedSlices *= size.cast<IntegerAttr>().getInt(); nExtractedSlices *= cast<IntegerAttr>(size).getInt();
} }
// Compute the strides of the source vector considering first k dimensions. // Compute the strides of the source vector considering first k dimensions.
llvm::SmallVector<int64_t, 4> sourceStrides(kD, extractGranularitySize); llvm::SmallVector<int64_t, 4> sourceStrides(kD, extractGranularitySize);
@ -189,7 +189,7 @@ struct LinearizeVectorExtractStridedSlice final
// Compute extractedStrides. // Compute extractedStrides.
for (int i = kD - 2; i >= 0; --i) { for (int i = kD - 2; i >= 0; --i) {
extractedStrides[i] = extractedStrides[i] =
extractedStrides[i + 1] * sizes[i + 1].cast<IntegerAttr>().getInt(); extractedStrides[i + 1] * cast<IntegerAttr>(sizes[i + 1]).getInt();
} }
// Iterate over all extracted slices from 0 to nExtractedSlices - 1 // Iterate over all extracted slices from 0 to nExtractedSlices - 1
// and compute the multi-dimensional index and the corresponding linearized // and compute the multi-dimensional index and the corresponding linearized
@ -207,7 +207,7 @@ struct LinearizeVectorExtractStridedSlice final
int64_t linearizedIndex = 0; int64_t linearizedIndex = 0;
for (int64_t j = 0; j < kD; ++j) { for (int64_t j = 0; j < kD; ++j) {
linearizedIndex += linearizedIndex +=
(offsets[j].cast<IntegerAttr>().getInt() + multiDimIndex[j]) * (cast<IntegerAttr>(offsets[j]).getInt() + multiDimIndex[j]) *
sourceStrides[j]; sourceStrides[j];
} }
// Fill the indices array form linearizedIndex to linearizedIndex + // Fill the indices array form linearizedIndex to linearizedIndex +
@ -254,7 +254,7 @@ struct LinearizeVectorShuffle final
Type dstType = getTypeConverter()->convertType(shuffleOp.getType()); Type dstType = getTypeConverter()->convertType(shuffleOp.getType());
assert(!(shuffleOp.getV1VectorType().isScalable() || assert(!(shuffleOp.getV1VectorType().isScalable() ||
shuffleOp.getV2VectorType().isScalable() || shuffleOp.getV2VectorType().isScalable() ||
dstType.cast<VectorType>().isScalable()) && cast<VectorType>(dstType).isScalable()) &&
"scalable vectors are not supported."); "scalable vectors are not supported.");
if (!isLessThanTargetBitWidth(shuffleOp, targetVectorBitWidth)) if (!isLessThanTargetBitWidth(shuffleOp, targetVectorBitWidth))
return rewriter.notifyMatchFailure( return rewriter.notifyMatchFailure(
@ -324,7 +324,7 @@ struct LinearizeVectorExtract final
ConversionPatternRewriter &rewriter) const override { ConversionPatternRewriter &rewriter) const override {
Type dstTy = getTypeConverter()->convertType(extractOp.getType()); Type dstTy = getTypeConverter()->convertType(extractOp.getType());
assert(!(extractOp.getVector().getType().isScalable() || assert(!(extractOp.getVector().getType().isScalable() ||
dstTy.cast<VectorType>().isScalable()) && cast<VectorType>(dstTy).isScalable()) &&
"scalable vectors are not supported."); "scalable vectors are not supported.");
if (!isLessThanTargetBitWidth(extractOp, targetVectorBitWidth)) if (!isLessThanTargetBitWidth(extractOp, targetVectorBitWidth))
return rewriter.notifyMatchFailure( return rewriter.notifyMatchFailure(
@ -405,9 +405,7 @@ void mlir::vector::populateVectorLinearizeShuffleLikeOpsPatterns(
[=](vector::ShuffleOp shuffleOp) -> bool { [=](vector::ShuffleOp shuffleOp) -> bool {
return isLessThanTargetBitWidth(shuffleOp, targetBitWidth) return isLessThanTargetBitWidth(shuffleOp, targetBitWidth)
? (typeConverter.isLegal(shuffleOp) && ? (typeConverter.isLegal(shuffleOp) &&
shuffleOp.getResult() cast<mlir::VectorType>(shuffleOp.getResult().getType())
.getType()
.cast<mlir::VectorType>()
.getRank() == 1) .getRank() == 1)
: true; : true;
}); });