unsigned operations with negative numbers

Hello,

I want to know, if I can always assume that when I do unsigned operations like

udiv, urem

I will get the both operands converted to unsigned values? with under optimized version of code I sometimes receive these lines:
unsigned a = 123;
int b = -2;
int c = a / b;
→ %1 = udiv i32 123, -2

and get the result 0. Will it always be zero? or is it undefined? Somewhere I have read that it may produce garbage.

will it be zero in this case : %1 = udiv i32 -123, 2?

However, when I set only the result as unsigned, then :
int a = 123;
int b = -2;
unsigned int c = a / b;
→ %1 = sdiv i32 123, -2

the result seems to be correct. So one operand (not the result variable) needs to be unsigned in order the result was unsigned too?

What should I expect from sign of the operand if I get the line:
%1 = udiv i32 %a.o, 2. Can it in this case be negative. Or this situation is only the result of under optimization and zero value is ok?

These questions may be related mostly to c, but still, perhaps llvm has some additional rules that I didn’t find. The general thing I wanted to know what to expect from sign of value when I get urem/udiv ops in final code?

Thank you in advance for the answer.

I’m surprised llvm (or clang) is emitting that -2 without a cast. But I’m sure it is treating it as MAXUINT-1 i.e. 0xfffffffe = 4294967294 on a 32 bit machine.

I get this result by applying only these transformations -mem2reg -lcssa -simplifycfg, maybe they are sufficient, -reassociate helps and returns 0.

So, if it MAXUINT-1, it is clear why it is zero or a big number when the first operand is negative.

What should I expect from sign of the operand if I get the line:
%1 = udiv i32 %a.o, 2. Can it in this case be negative.

LLVM integers don't really have a sign and are just bags of bits. It's
the operations that interpret those as signed or unsigned integers and
udiv's arguments are unsigned.

They're printed as signed numbers purely for convenience (-2 is a lot
more recognisable than 4294967294)

Or this situation is
only the result of under optimization and zero value is ok?

I'm not sure what you mean by zero here. The result of your first
division example will be 0.

Cheers.

Tim.

Hello,