Problem with __gmp_expr

Marc Glisse marc.glisse at
Sat Jan 18 13:14:41 UTC 2014

On Fri, 17 Jan 2014, Marc Glisse wrote:

> On Fri, 17 Jan 2014, Marc Glisse wrote:
>> In this particular case (I haven't checked closely yet), it may be that 
>> things "work" with other expression template libraries whose expressions 
>> use copies instead of references. In gmp, -m*a is a neg expr that stores a 
>> ref to a mult expr that stores references to m and a. Since you managed to 
>> postpone the evaluation of the expression, the mult expr went out of scope 
>> (older versions of gcc don't crash because they are not good at reusing 
>> space from dead objects). Other libraries would have a big neg expr that 
>> embeds a copy of the mult expr, and only mp?_class is spared the copying. 
>> It has advantages. It also seems (didn't try it myself) to make it harder 
>> for the compiler to eliminate all this meta-stuff. It may be worth 
>> re-evaluating (I don't have time to do it myself soon).
> The following patch (only tested on this example) handles your example with 
> and without LAMBDA.

Surprisingly, that patch, which passes the testsuite, actually seems to 
help the compiler quite a bit. On this testcase (random operations to 
build a large enough expression):

mpq_class f(mpz_class z,mpq_class q1,mpq_class q2,mpq_class q3){
   return (q1*q1+2)/-z+(q3-q2-1)*2*(q2-z);

With the patch I get a .s file of size 3855 (-O2 or -O3, doesn't matter), 
while with the old gmpxx.h I get 4315 at -O3 and 4513 at -O2. The 
difference is mostly a bunch of useless mov+lea that disappear. The patch 
also lets the compiler notice one more __builtin_constant_p for the 
multiplication by 2, and it notices that 2 (in +2) is positive at -O2 
instead of -O3.

I still believe it is too late for 5.2, but it is definitely worth 
considering for 5.3, if it makes more code valid (although it is a kind of 
code I'd prefer people not to write) and lets the compiler generate better 
asm. It should also make it easier to implement other optimizations like 
replacing -(-x) with x.

For 5.2, I am going to try to add a few words to the doc.

Marc Glisse

More information about the gmp-bugs mailing list