> For the complete documentation index, see [llms.txt](https://valineliu.gitbook.io/deuterium-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/csapp-3e-homework-solution/3.-machine-level-representation-of-programs/3.60-for-loop.md).

# 3.60 For Loop

★★

Consider the following assembly code:

```
loop:
    ; x in %rdi, n in %esi
    movl     %esi, %ecx
    movl     $1, %edx
    movl     $0, %eax
    jmp      .L2
.L3:
    movq     %rdi, %r8
    andq     %rdx, %r8
    orq      %r8, %rax
    salq     %cl, %rdx
.L2:
    testq    %rdx, %rdx
    jne      .L3
    rep; ret
```

The preceding code was generated by compiling C code that had the following overall form:

```c
long loop(long x, long n) {
    long result = ____;
    long mask;
    for (mask = ____; mask ____; mask = ____) {
        result |= ____;
    }
    return result;
}
```

Your task is to fill in the missing parts of the code to get a program equivalent to the generated assembly code. Recall that the result of the function is returened in register %rax. You will find it helpful to examine the assembly code before, during , and after the loop to form a consistent mapping between the registers and the program variables.

A. Which registers hold program values `x`, `n`, `result`, and `mask`?

x in %rdi, n in %eax, result in %rax, mask in %rdx

B. What are the initial values of `result` and `mask`?

```c
long result = 0;
long mask = 1;
```

C. What is the test condition for `mask`?

```c
mask != 0
```

D. How does `mask` get updated?

```c
mask <<= n;
```

E. How does `result` get updated?

```c
result |= x & mask;
```

F. Fill in all the missing parts of the C code.

```c
long loop(long x, int n) {
    long result = 0;
    long mask;
    for (mask = 1; mask != 0; mask <<= n) {
        result |= (x & mask);
    }
    return result;
}
```
