CMPT 295

Last Lecture

Today’s Menu

Completing our Demo

  1. (checked) gcc uses leaq for addition -> sum_store.c our own assembly code (arith.s) using arithmetic
  2. (checked) Writing instructions of x86-64 assembly language
  3. makefile
    • when we compile our own *.s files with *.c files
    • when we compile only *.c files
  4. How would gcc compile our arith.c into arith.s?

Program Control Overview

Function calls -> call and ret

Conditional statement: if/else

in C:

void func(long x,long y){
  if ( x < y ) {
    // stmts true
  } else {
    // stmts false
  }
  return;
}

A label is a memory address.

in assembly:

# func is a label
func:
  cmpq %rsi,%rdi # x – y
  jge else       #
  ...            # stmts true
  jmp endif      #
  # else is a label
  else: ...      # stmts false
  # endif is a label
  endif: ret     #

We branch (jump) when the condition is false -> This technique is called “coding the false condition first”

comparison instructions

Remember in Lecture 9, we saw… (See header “Programming in x86-64 assembly” from lecture 9)

Syntax Meaning/Effect Example Notes
cmp* Src2, Src1 Src1 – Src2 ->
> 0? -> Src1 > Src2
= 0? -> Src1 == Src2
< 0? -> Src1 < Src2
cmpq %rsi,%rdi without saving the result in the destination operand (no Dest). Sets condition codes based on value of Src1Src2\text{Src1} - \text{Src2}
test* Src2, Src1 Src1 & Src2 -> testq %rax,%rax without saving the result in the destination operand (no Dest); sets condition code based on value of Src1Src2\text{Src1} \land \text{Src2}; useful when one of the operands is a bit mask

jX jump family instructions (branching)

jX Description
jmp unconditional
je Equal / Zero
jne Not Equal / Not Zero
js Negative
jns Nonnegative
jg Greater (Signed)
jge Greater or Equal (Signed)
jl Less (Signed)
jle Less or Equal (Signed
ja Above (unsigned)
jb Below (unsigned)

Example – int abs(int x)

in C:

int abs(int x){
  if(x<0)
    x=-x;
  return x;
}

in assembly:

# x in edi, result in eax

abs:
  movl %edi,%eax # eax <- x
  ____ #
  ____ # ret if x >= 0
  ____ # x = -x

endif:
  ret

int max(int x, int y )- Homework

In C:

int max(int x, int y){
  int result=x;
  if(y>x)
    result=y;
  return result;
}

In assembly:

# x in edi, y in esi, result in eax
max:
  movl %edi,%eax # result = x
  ____
  ____
  ____
  ____
  ____
endif:
  ret 

Summary

Next Lecture