[fpc-devel] [Suggestion] Enumeration range-check intrinsic

Jonas Maebe jonas at freepascal.org
Tue Jul 2 23:34:12 CEST 2019


On 02/07/2019 22:31, Ondrej Pokorny wrote:
> var
>   Value: TEnumType;
> begin
>   Value := TEnumType(-1);
>   IsValid := Value is TEnumType; // IsValid gains false
> 
> The compiler may not do any optimizations here (like return always true
> if the left side value is the enum type at the right side). This should
> be clearly stated and documented if the feature is added to FPC.

Whenever you need an exception like this, it means that the behaviour
does not fit in the language. As a result, it would make the language
(more) inconsistent and harder to reason about, even independently of
optimizations. E.g. if Value is inside a bitpacked array or record,
IsValid will may well be true instead of false, because a bunch of bits
were thrown away during the assignment. This shows that the only place
where the checking can reliably happen, is during the initial conversion
(which should have been done with "as" in this scenario).

And yes, it also complicates compilers/optimizers, because you have to
make sure you handle this special case everywhere, now and forever. E.g.
it would make it impossible to add range annotations for enum types in
LLVM bitcode without adding volatile load hacks all over the place.

> This is similar to the object-is operator that gets evaluated as well
> even if the type of the left-side value is the type at right side:
> 
> var
>   Value: TPersistent;
> begin
>   Value := TPersistent(TObject.Create);
>   IsValid := Value is TPersistent; // IsValid gains false

This is an invalid program. If you compile with -CR, the program will
abort with an error when the typecast is performed, because it will get
replaced by an "as" operation. In that sense, "integer as enum" would
indeed be somewhat similar, and -CR might even be extended to perform
the same replacement of explicit typecasts with "as" operators for these
types.

As an example of an operation on the resulting "Value" that is already
undefined: if you would call a TPersistent virtual method on it, and
whole-program optimization devirtualised that call, it may call the
"correct" method of TPersistent instead of using the VMT of whatever
other class instance type Value points to.

Invalid data means undefined behaviour, always. "is" is not a special
case that is immune to this. And e.g. in the context of generics,
simplifying/removing such checks where possible would probably be quite
desirable.

As to your patch itself: why do you not directly compare the
tconstexprint values directly, and use the svalue/uvalue fields instead?


Jonas


More information about the fpc-devel mailing list