Professional Documents
Culture Documents
Programming: Control
Computer Systems Organization (Spring 2016)
CSCI-UA 201, Section 2
Condition Codes
CF
ZF
cmpq b,a
CF set if carry out from most significant bit (used for unsigned
comparisons)
ZF set if a == b
SF set if (a-b) < 0 (as signed)
OF set if twos-complement (signed) overflow
(a>0 && b<0 && (a-b)<0) || (a<0 && b>0 && (a-b)>0)
SetX Instructions:
cmpq
%rsi, %rdi
setg
%al
movzbl %al, %eax
ret
# Compare x:y
# Set when >
# Zero rest of %rax
9
Conditional Branches
10
11
long absdiff
(long x, long y)
{
long result;
if (x > y)
result = x-y;
else
result = y-x;
return result;
}
long absdiff_j
(long x, long y)
{
long result;
int ntest = x <= y;
if (ntest) goto Else;
result = x-y;
goto Done;
Else:
result = y-x;
Done:
return result;
}
Why do that?
Because the "goto" code is closer to the assembly instructions.
12
ntest = !Test;
if (ntest) goto Else;
val = Then_Expr;
goto Done;
Else:
val = Else_Expr;
Done:
. . .
13
Instruction supports:
if (Test) Dest
Src
Why?
C Code:
val = Test
? Then_Expr
: Else_Expr;
goto version:
result = Then_Expr;
eval = Else_Expr;
nt = !Test;
if (nt) result = eval;
return result;
14
absdiff:
movq
subq
movq
subq
cmpq
cmovle
ret
%rdi,
%rsi,
%rsi,
%rdi,
%rsi,
%rdx,
%rax
%rax
%rdx
%rdx
%rdi
%rax
# x
# result = x-y
# eval = y-x
# x:y
# if <=, result = eval
15
expensive computations:
risky computations
16
Loops
17
18
movl
$0, %eax
.L2:
movq
%rdi, %rdx
andl
$1, %edx
addq
%rdx, %rax
shrq
%rdi
jne
.L2
rep; ret
# result = 0
# loop:
#
#
#
#
t = x & 0x1
result += t
x >>= 1
if (x) goto loop
19
do
Body
while (Test);
loop:
Body
if (Test)
goto loop
20
while (Test)
Body
goto test;
loop:
Body
test:
if (Test)
goto loop;
done:
Jump-to-middle translation
Used with -Og option to gcc
21
22
while (Test)
Body
Do-while conversion
Used with -O1
convert to do..
while.. first
if (!Test)
goto done;
do
Body
while(Test);
done:
if (!Test)
goto done;
loop:
Body
if (Test)
goto loop;
done:
23
24
Init;
while (Test ) {
Body
Update
}
26
27