encode_value: Improved support for variant dispatchers.
The variant dispatcher often replaces the reference id to the terminating
function, which instead gets the reference id that the variant dispatcher
would have gotten otherwise.
This fixes broken encoding where the terminating function's reference id
was taken by the next function that was encoded, which in turn caused
decode_value() to fail with "Bad function identifier offset".