mpq_cmp_z

Marc Glisse marc.glisse at inria.fr
Thu Aug 20 07:56:55 UTC 2015


On Thu, 20 Aug 2015, Marco Bodrato wrote:

> Is casting an mpz to an mpq, then accessing only the NUM() part of it,
> portable?

>From what I understand of the aliasing model currently used by gcc, to be 
safe, in the function using it, we should have:
mpz_srcptr op2n = NUM(op2);
and then use SIZ(op2n) instead of directly SIZ(NUM(op2)). The reason is 
that as long as you are only doing pointer arithmetic (NUM counts as 
pointer arithmetic), the exact type is kind of irrelevant (size matters as 
a multiplicative factor, and alignment because it can make the result 
invalid, but that's it), but as soon as you actually use it (load or 
store), you are making a promise that the type is right. So 
"x=op2->_mp_den._mp_size" promises that op2 points to a __mpq_struct while 
"x=op2n->_mp_size" only promises a __mpz_struct (and gcc folds *& to 
nothing very early, so it sees SIZ(NUM(op2)) as the first expression). 
Note that my understanding could be wrong, and other compilers could have 
a different model.

In practice, I doubt your code would fail, but with the generalization of 
link-time optimizations, the library and user code are not hidden from 
each other anymore, and surprising things could happen.

The cast itself seems fine: "A pointer to a structure object, suitably 
converted, points to its initial member (or if that member is a bit-field, 
then to the unit in which it resides), and vice versa. There may be 
unnamed padding within a structure object, but not at its beginning."

On Thu, 20 Aug 2015, Torbjörn Granlund wrote:

> (We might consider adding mpf_cmp_z too, at least in a simple-minded
> manner, to keep the GMP interface as orthogonal as possible.)

Adding new mpf_t functions might confuse the message that people should 
use mpfr...

-- 
Marc Glisse


More information about the gmp-devel mailing list