Lecture 16

Arithmetic and Logic Operations

  • addX SRC DST: Adds two values, resulting in DST = DST + SRC
  • Operations Categories:
    • Immediate: Direct values
    • Register: Values from registers
    • Memory: Values stored in memory
  • Binary Operations:
    • subX SRC DST: Subtract, DST = DST - SRC
    • imulX SRC DST: Integer multiply, DST = DST * SRC
    • xorX SRC DST: Bitwise XOR, DST = DST ^ SRC
    • orX SRC DST: Bitwise OR, DST = DST | SRC
    • andX SRC DST: Bitwise AND, DST = DST & SRC

Unary Operations

  • Operations with one argument:
    • negX DST: Negates the value, DST = -DST
    • notX DST: Bitwise negate, DST = ~DST
    • incX DST: Increment, DST = DST + 1
    • decX DST: Decrement, DST = DST - 1

Shift Operations

  • Shift Operations:
    • salX k, DST: Left shift by k, DST = DST << k
    • sarX k, DST: Arithmetic right shift by k, DST = DST >>A k
    • shrX k, DST: Logical right shift by k, DST = DST >>L k

Load Effective Address (LEA)

  • lea SRC, DST: Loads the effective address of the memory operand SRC into DST without dereferencing. Example: leaq (%rsi, %rcx, 4), %rax computes R[%rsi] + R[%rcx] * 4.

Assembly vs C Comparison

  • Example Function: long scale(long x, long y, long z) { return x + 4*y + 12*z; }
  • Example Assembly Code:
    • leal (%rdi, %rsi, 4), %rax - calculates x + 4*y
    • leal (%rdx, %rdx, 2), %rdx - doubles z
    • leal (%rax, %rdx, 4), %rax - combines to calculate final result.

Control Flow

  • Instructions: cmpX, testX (conditions) and jXX (jumps for conditional execution)
  • Special register: %rip stores the address of the next executable instruction.

Comparisons in Control Flow

  • cmpX B, A: Computes A - B and sets flags
  • Flags set:
    • CF: Carry Flag (unsigned overflow)
    • ZF: Zero Flag (result is 0)
    • SF: Sign Flag (result is negative)
    • OF: Overflow Flag (signed overflow)

Example Tests

  • Example: If %rbx = 0x3, cmpq $5, %rbx: sets flags accordingly based on operation result.
  • Test Example: If %rcx = 0x8, testq %rcx, %rbx: performs bitwise AND and sets flags based on operation result.