[LLVMdev] APInt::sdivrem error?

Preston Briggs preston.briggs at gmail.com
Mon May 21 10:17:22 PDT 2012


"Caldarale, Charles R" <Chuck.Caldarale at unisys.com> wrote:

> > APInt q(bits, 1), r(bits, 1);
>
> The APInt constructor has three arguments, the last one being whether or not the value is to be treated as signed.
> It defaults to false, as you appear to have just verified.

The initial values of q and r shouldn't make a difference (note that
several of the correct examples give correct positive and negative
results). And trying it with a 3rd true argument made no difference.

Other ideas anyone?

My only other clue is that bits = 64.

Thanks,
Preston


> I wrote the following bit of code
>
>  static APInt FloorOfQuotient(APInt a, APInt b) {
>  unsigned bits = a.getBitWidth();
>  APInt q(bits, 1), r(bits, 1);
>  APInt::sdivrem(a, b, q, r);
>  errs() << "sdivrem(" << a << ", " << b << ") = (" << q << ", " << r << ")\n";
>  if (r == 0)
>    return q;
>  else {
>    if ((a.sgt(0) && b.sgt(0)) ||
>        (a.slt(0) && b.slt(0)))
>      return q;
>    else
>      return q - 1;
>   }
> }
>
> but sometimes see surprising results.  Here are examples:
>
> sdivrem(9, -2) = (-4, 1)
> sdivrem(9, -3) = (-3, 0)
> sdivrem(10, -3) = (-3, 1)
> sdivrem(38, 2) = (19, 0)
> sdivrem(29, 1) = (29, 0)
> sdivrem(-8, -1) = (-8, 0)
> sdivrem(-9, -1) = (-9, 0)
>
> What's up with the last two?
>
> Am I doing something wrong (again)?



More information about the llvm-dev mailing list