forked from OSchip/llvm-project
add a method to get FloatAttr value as double
Sometimes we have to get the raw value of the FloatAttr to invoke APIs from non-MLIR libraries (i.e. in the tpu_ops.inc and convert_tensor.cc files). Using `FloatAttr::getValue().convertToFloat()` and `FloatAttr::getValue().convertToDouble()` is not safe because interally they checke the semantics of the APFloat in the attribute, and the semantics is not always specified (the default value is f64 then convertToFloat will fail) or inferred incorrectly (for example, using 1.0 instead of 1.f for IEEEFloat). Calling these convert methods without knowing the semantics can usually crash the compiler. This new method converts the value of a FloatAttr to double even if it loses precision. Currently this method can be used to read in f32 data from arrays. PiperOrigin-RevId: 227076616
This commit is contained in:
parent
bd24a131d3
commit
9b20a4ccdf
|
@ -184,7 +184,9 @@ public:
|
|||
|
||||
APFloat getValue() const;
|
||||
|
||||
double getDouble() const;
|
||||
/// This function is used to convert the value to a double, even if it loses
|
||||
/// precision.
|
||||
double getValueAsDouble() const;
|
||||
|
||||
Type getType() const;
|
||||
|
||||
|
|
|
@ -88,7 +88,16 @@ APFloat FloatAttr::getValue() const {
|
|||
|
||||
Type FloatAttr::getType() const { return static_cast<ImplType *>(attr)->type; }
|
||||
|
||||
double FloatAttr::getDouble() const { return getValue().convertToDouble(); }
|
||||
double FloatAttr::getValueAsDouble() const {
|
||||
const auto &semantics = getType().cast<FloatType>().getFloatSemantics();
|
||||
auto value = getValue();
|
||||
bool losesInfo = false; // ignored
|
||||
if (&semantics != &APFloat::IEEEdouble()) {
|
||||
value.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
|
||||
&losesInfo);
|
||||
}
|
||||
return value.convertToDouble();
|
||||
}
|
||||
|
||||
StringAttr::StringAttr(Attribute::ImplType *ptr) : Attribute(ptr) {}
|
||||
|
||||
|
|
|
@ -899,8 +899,8 @@ Attribute Parser::parseAttribute(Type type) {
|
|||
if (!(type = parseType()))
|
||||
return nullptr;
|
||||
} else {
|
||||
// Default to F32 when no type is specified.
|
||||
type = builder.getF32Type();
|
||||
// Default to F64 when no type is specified.
|
||||
type = builder.getF64Type();
|
||||
}
|
||||
}
|
||||
if (!type.isa<FloatType>())
|
||||
|
|
Loading…
Reference in New Issue