GATE / CS ARCHIVE

GATE CSE 1999 / QUESTION 17(a)

Trace the population-count loop

Computer Organization & Architecture · Instructions & Addressing Modes · Full GATE CSE 1999 paper

GATE 1999, Q17(a) 2 marks · Descriptive
Report issue

Instructions & Addressing Modes

Question 17(a), GATE 1999: For the assembly below with initial (R1,R2,R3)=(5,0,0), find R1 and R3 on reaching Z:
X: CMP R1,0
   JZ Z
   MOV R2,R1
   SHR R1
   SHL R1
   CMP R2,R1
   JZ Y
   INC R3
Y: SHR R1
   JMP X
Z: ...
CMP sets comparison flags; JZ jumps on equality; MOV copies its second operand into its first; SHR/SHL shift by one bit.
Question 17(a), GATE 1999: For the assembly below with initial (R1,R2,R3)=(5,0,0), find R1 and R3 on reaching Z:
X: CMP R1,0
   JZ Z
   MOV R2,R1
   SHR R1
   SHL R1
   CMP R2,R1
   JZ Y
   INC R3
Y: SHR R1
   JMP X
Z: ...
CMP sets comparison flags; JZ jumps on equality; MOV copies its second operand into its first; SHR/SHL shift by one bit.
Question 17(a), GATE 1999: For the assembly below with initial (R1,R2,R3)=(5,0,0), find R1 and R3 on reaching Z:
X: CMP R1,0
   JZ Z
   MOV R2,R1
   SHR R1
   SHL R1
   CMP R2,R1
   JZ Y
   INC R3
Y: SHR R1
   JMP X
Z: ...
CMP sets comparison flags; JZ jumps on equality; MOV copies its second operand into its first; SHR/SHL shift by one bit.
Tap to enlarge
Answer & solution

Answer: R1=0, R3=2 (no official key was published)

The SHR followed by SHL clears the least significant bit. Comparing the result against saved R2 detects whether that bit was 1. If so, increment R3. The SHR at Y then advances to the next bit. With nonnegative logical shifts the trace is:

Entry R1 | R2 after MOV | after SHR,SHL | R3 after test | R1 after Y
5 (101)  | 5            | 4 (100)       | 1             | 2
2 (010)  | 2            | 2 (010)       | 1             | 1
1 (001)  | 1            | 0 (000)       | 2             | 0

At the next X, R1=0 makes JZ Z branch before another iteration. Hence final R1=0 and R3=2. R2 happens to remain 1, though it is not requested. The two right shifts in the body do not skip two input bits because the intervening left shift restores the higher-bit positions.

Original paper, page 8