Re: programmer optimizations?

Dave Gillespie <synaptx!carambole!daveg@uunet.uu.net>
Wed, 11 Jan 1995 11:36:54 GMT

          From comp.compilers

Related articles
[4 earlier articles]
Re: programmer optimizations? jbuck@Synopsys.COM (1995-01-02)
Re: programmer optimizations? eru@tele.nokia.fi (Erkki Ruohtula) (1995-01-11)
Re: programmer optimizations? conway@munta.cs.mu.OZ.AU (1995-01-05)
Re: programmer optimizations? bill@amber.ssd.csd.harris.com (1995-01-05)
Re: programmer optimizations? kerch@albion.camb.inmet.com (1995-01-12)
Re: programmer optimizations? monnier@di.epfl.ch (Stefan Monnier) (1995-01-21)
Re: programmer optimizations? synaptx!carambole!daveg@uunet.uu.net (Dave Gillespie) (1995-01-11)
Re: programmer optimizations? det@sw.stratus.com (David Toland) (1995-01-11)
Re: programmer optimizations? cdg@nullstone.com (1995-01-23)
Re: programmer optimizations? hbaker@netcom.com (1995-01-27)
Re: programmer optimizations? cdg@nullstone.com (1995-01-31)
Re: programmer optimizations? c1veeru@WATSON.IBM.COM (Virendra K. Mehta) (1995-02-02)
Re: programmer optimizations? hbaker@netcom.com (1995-02-01)
[3 later articles]
| List of all articles for this month |
Newsgroups: comp.compilers
From: Dave Gillespie <synaptx!carambole!daveg@uunet.uu.net>
Keywords: optimize, 386
Organization: Compilers Central
References: 95-01-003 94-12-145 95-01-010
Date: Wed, 11 Jan 1995 11:36:54 GMT

Erkki Ruohtula <uunet!tele.nokia.fi!eru> writes:


> xor edx,edx
> mov dx, [esp] ; now register edx is the value being divided by 4
> mov eax,edx
> sar edx,1fH
> shl edx,02H
> sbb eax,edx
> sar eax,02H
> ; now eax is the result


What's going on here is that the compiler knows how to divide
both signed and unsigned ints by shifting. It has broken
"(unsigned short)n >> 2" down into two steps: Zero-extend "n" to
a signed integer, then shift the resulting signed integer.


Again, in super-slow-motion:


                xor edx,edx ; edx = 0.
                mov dx, [esp] ; edx = n, zero-extended.
                mov eax,edx ; eax = n, zero-extended.
                sar edx,1fH ; eax = -1 if n < 0, 0 if n >= 0.
                shl edx,02H ; eax = -4 with carry set if n < 0.
                sbb eax,edx ; eax += 3 if n < 0.
                sar eax,02H ; eax = n / 4 (signed).


The idea is that positive numbers can be shifted right the same as
unsigned numbers, but for negative numbers you need to add one unless
the number was a multiple of the denominator. (This duplicates the
round-toward-zero that regular integer division does.) If "n" is
a multiple of 4, adding 3 has no effect since the bits will just get
rounded away. If "n" is not a multiple of 4, adding 3 will bump it
upward by one in the high 30 bits.


Cute! (Except, of course, that it's a complete waste of time when
the operand is known to be non-negative...)


-- Dave
--


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.