Chapter 3 Machine-Level Programming II Control Flow

Similar documents
Condition Codes The course that gives CMU its Zip! Machine-Level Programming II Control Flow Sept. 13, 2001 Topics

Condition Codes. Lecture 4B Machine-Level Programming II: Control Flow. Setting Condition Codes (cont.) Setting Condition Codes (cont.

CF Carry Flag SF Sign Flag ZF Zero Flag OF Overflow Flag. ! CF set if carry out from most significant bit. "Used to detect unsigned overflow

Giving credit where credit is due

Page # CISC 360. Machine-Level Programming II: Control Flow Sep 23, Condition Codes. Setting Condition Codes (cont.)

CISC 360. Machine-Level Programming II: Control Flow Sep 23, 2008

CISC 360. Machine-Level Programming II: Control Flow Sep 17, class06

Page 1. Condition Codes CISC 360. Machine-Level Programming II: Control Flow Sep 17, Setting Condition Codes (cont.)

ASSEMBLY II: CONTROL FLOW. Jo, Heeseung

Assembly II: Control Flow. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Machine- level Programming II: Control Flow

Machine-Level Programming II: Control Flow

The Hardware/Software Interface CSE351 Spring 2013

Machine Level Programming II: Arithmetic &Control

Sungkyunkwan University

CS241 Computer Organization Spring Addresses & Pointers

Machine-Level Programming II: Arithmetic & Control. Complete Memory Addressing Modes

Machine-Level Programming II: Control and Arithmetic

Control flow. Condition codes Conditional and unconditional jumps Loops Switch statements

Machine-Level Programming II: Arithmetic & Control /18-243: Introduction to Computer Systems 6th Lecture, 5 June 2012

Homework 0: Given: k-bit exponent, n-bit fraction Find: Exponent E, Significand M, Fraction f, Value V, Bit representation

Credits to Randy Bryant & Dave O Hallaron

Machine-Level Programming I: Introduction

Assembly II: Control Flow. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Machine Programming 2: Control flow

Questions about last homework? (Would more feedback be useful?) New reading assignment up: due next Monday

Assembly II: Control Flow

Machine- Level Programming II: Arithme6c & Control

System Programming and Computer Architecture (Fall 2009)

CS 33. Machine Programming (2) CS33 Intro to Computer Systems XII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Machine- Level Programming II: Arithme c & Control

Machine-Level Programming II: Control

Machine- Level Programming II: Arithme6c & Control

Machine-Level Programming II: Control

CS 33. Machine Programming (2) CS33 Intro to Computer Systems XI 1 Copyright 2018 Thomas W. Doeppner. All rights reserved.

Process Layout and Function Calls

Machine Representa/on of Programs: Control Flow cont d. Previous lecture. Do- While loop. While- Do loop CS Instructors: Sanjeev Se(a

The Hardware/Software Interface CSE351 Spring 2015

CS 31: Intro to Systems ISAs and Assembly. Kevin Webb Swarthmore College February 9, 2016

CS 31: Intro to Systems ISAs and Assembly. Kevin Webb Swarthmore College September 25, 2018

CS367. Program Control

Machine Level Programming: Control

Process Layout, Function Calls, and the Heap

Turning C into Object Code Code in files p1.c p2.c Compile with command: gcc -O p1.c p2.c -o p Use optimizations (-O) Put resulting binary in file p

CS429: Computer Organization and Architecture

X86 Addressing Modes Chapter 3" Review: Instructions to Recognize"

2/12/2016. Today. Machine-Level Programming II: Control. Condition Codes (Implicit Setting) Processor State (x86-64, Partial)

Second Part of the Course

CS241 Computer Organization Spring Loops & Arrays

Machine-Level Programming (2)

CSE2421 FINAL EXAM SPRING Name KEY. Instructions: Signature

CS61 Section Solutions 3

Controlling Program Flow

This is a medical robot, guided by a skilled surgeon and designed to get to places doctors are unable to reach without opening a pacent up.

CSC 8400: Computer Systems. Machine-Level Representation of Programs

Assembly Language: IA-32 Instructions

Control. Young W. Lim Mon. Young W. Lim Control Mon 1 / 16

Assembly I: Basic Operations. Jo, Heeseung

x86-64 Programming II

ASSEMBLY I: BASIC OPERATIONS. Jo, Heeseung

Instruction Set Architecture

Y86 Processor State. Instruction Example. Encoding Registers. Lecture 7A. Computer Architecture I Instruction Set Architecture Assembly Language View

Instruction Set Architecture

CSC 2400: Computer Systems. Towards the Hardware: Machine-Level Representation of Programs

Assembly I: Basic Operations. Computer Systems Laboratory Sungkyunkwan University

Carnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition

Outline. Review: Assembly/Machine Code View. Processor State (x86-64, Par2al) Condi2on Codes (Explicit Se^ng: Compare) Condi2on Codes (Implicit Se^ng)

Three Kinds of Instruc;ons

Handout #2: Machine-Level Programs

Assembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction

Instruction Set Architecture

CISC 360 Instruction Set Architecture

Machine-Level Programming I: Introduction Jan. 30, 2001

Machine Programming 1: Introduction

Machine-Level Programming II: Control

CMSC 313 Fall2009 Midterm Exam 2 Section 01 Nov 11, 2009

Assembly Programming III

Sungkyunkwan University

CS , Fall 2001 Exam 1

Credits and Disclaimers

administrivia today start assembly probably won t finish all these slides Assignment 4 due tomorrow any questions?

CS241 Computer Organization Spring 2015 IA

x86 Programming II CSE 351 Winter

Credits and Disclaimers

L09: Assembly Programming III. Assembly Programming III. CSE 351 Spring Guest Lecturer: Justin Hsia. Instructor: Ruth Anderson

Chapter 4! Processor Architecture!

Instruction Set Architecture

EECS 213 Fall 2007 Midterm Exam

Chapter 4 Processor Architecture: Y86 (Sections 4.1 & 4.3) with material from Dr. Bin Ren, College of William & Mary

CISC 360. Machine-Level Programming I: Introduction Sept. 18, 2008

1 /* file cpuid2.s */ 4.asciz "The processor Vendor ID is %s \n" 5.section.bss. 6.lcomm buffer, section.text. 8.globl _start.

Machine-Level Programming Introduction

Assembly level Programming. 198:211 Computer Architecture. (recall) Von Neumann Architecture. Simplified hardware view. Lecture 10 Fall 2012

Computer System. Cheng JIN.

Machine- Level Programming II: Control Structures and Procedures

Machine- Level Programming II: Control Structures and Procedures

Control flow (1) Condition codes Conditional and unconditional jumps Loops Conditional moves Switch statements

CS 31: Intro to Systems ISAs and Assembly. Martin Gagné Swarthmore College February 7, 2017

Machine-level Representation of Programs. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

Transcription:

Chapter 3 Machine-Level Programming II Control Flow Topics Condition Codes Setting Testing Control Flow If-then-else Varieties of Loops Switch Statements Condition Codes Single Bit Registers CF Carry Flag ZF Zero Flag SF Sign Flag OF Overflow Flag Implicit Setting By Arithmetic Operations e.g. addl Src,Dest C analog: t = a + b CF set if carry out from most significant bit Used to detect unsigned overflow ZF set if t == 0 SF set if t < 0 OF set if two s complement overflow (a>0 && b>0 && t<0) (a<0 && b<0 && t>0) Not Set by leal instruction 2 Setting Condition Codes (cont.) Explicit Setting by Compare Instruction cmpl Src2,Src1 cmpl b,a like computing a-b without setting destination CF set if carry out from most significant bit ZF set if a == b SF set if (a-b) < 0 OF set if two s complement overflow (a>0 && b<0 && (a-b)<0) (a<0 && b>0 && (a-b)>0) 3

Setting Condition Codes (cont.) Explicit Setting by Test instruction testl Src2,Src1 Sets condition codes based on value of Src1 & Src2 Useful to have one of the operands be a mask testl b,a like computing a&b without setting destination ZF set when a&b == 0 SF set when a&b < 0 4 Reading Condition Codes SetX Instructions Set single byte to 1 or 0 based on combinations of CC SetX Condition Description sete ZF Equal / Zero setne ~ZF Not Equal / Not Zero sets SF Negative setns ~SF Nonnegative setg ~(SF^OF)&~ZF Greater (Signed) setge ~(SF^OF) Greater or Equal (Signed) setl (SF^OF) Less (Signed) setle (SF^OF) ZF Less or Equal (Signed) seta ~CF&~ZF Above (unsigned) setb CF Below (unsigned) 5 Reading Condition Codes (Cont.) SetX Instructions One of 8 addressable byte registers Embedded within first 4 integer registers Does not alter remaining 3 bytes Typically use andl 0xFF,%eax to finish job int gt (int x, int y) return x > y; movl 12(%ebp),%eax # eax = y cmpl %eax,8(%ebp) # Compare x : eax setg %al # al = x > y andl $255,%eax # Zero rest of %eax %eax %edx %ecx %ebx %esi %edi %esp %ebp %ah %dh %ch %bh Note inverted ordering! %al %dl %cl %bl 6

Examples Assume a in %eax and b in %ebx C Expression a > b (short) a == b (char) a < b a == 0 If ( a ) Assembly Code cmpl %ebx,%eax cmpw %bx,%ax cmpb %bl,%al testl %eax,%eax testl %eax,%eax 7 Examples Assume a in %eax and b in %ebx, and t is a char C Expression Assembly Code t = a > b t =(short) a == b t =(char) a < b t = a == 0 8 cmpl %ebx,%eax setg %al cmpw %bx,%ax sete %al cmpb %bl,%al setl %al testl %eax,%eax sete %al Jumping jx Instructions Jump to different part of code depending on CC jx Condition Description jmp 1 Unconditional je ZF Equal / Zero jne ~ZF Not Equal / Not Zero js SF Negative jns ~SF Nonnegative jg ~(SF^OF)&~ZF Greater (Signed) jge ~(SF^OF) Greater or Equal (Signed) jl (SF^OF) Less (Signed) jle (SF^OF) ZF Less or Equal (Signed) ja ~CF&~ZF Above (unsigned) jb CF Below (unsigned) 9

Examples Assume a in %eax and b in %ebx C Expression Assembly Code If ((short) a == b) If ( a > b) If ( a == 0) If ( a ) cmpl %ebx,%eax jle L1 cmpw %bx,%ax jne L1 testl %eax,%eax jne L1 testl %eax,%eax je L1 10 Conditional Branch Example int max(int x, int y) if (x > y) return x; else return y; _max:.... movl 8(%ebp),%edx movl 12(%ebp),%eax cmpl %eax,%edx jle L9 movl %edx,%eax.... L9: Return X Return Y 11 Conditional Branch Example (if-then-else) int max(int x, int y) if (x > y) x++; else y++;... _max:.... movl 8(%ebp),%edx movl 12(%ebp),%eax cmpl %eax,%edx jle L9 incr %edx jmp L10 L9: incr %eax L10:... 12

Conditional Branch Example (if-then) int max(int x, int y) if (x > y) x++;... _max:.... movl 8(%ebp),%edx movl 12(%ebp),%eax cmpl %eax,%edx jle L10 incr %edx L10:... 13 Conditional Branch Example (if-goto) int max(int x, int y) if (x > y) goto L1;... _max:.... movl 8(%ebp),%edx movl 12(%ebp),%eax cmpl %eax,%edx jg L1........ L1:... 14 Conditional Branch Example (nested if) int max(int x, int y) if (x > y) if (x > 2) x++; else y++; _max:.... movl 8(%ebp),%edx movl 12(%ebp),%eax cmpl %eax,%edx jle L9 cmpl $2,%edx jle L10 incr %edx L10: jmp L11 L9: incr %eax L11:... 15

Where Have We Been? IA32 Architecture Compiling and Debugging Machine Language MOVL Instruction and Variants Addressing Modes Control Constructs from C to Assembly Where Are We Going? More Control Examples 16 Conditional Branch Example (&& and ) int max(int x, int y) if (x && y > 0) x++; else y++; _max:.... movl 8(%ebp),%edx movl 12(%ebp),%eax testl %edx,%edx je L9 testl %eax,%eax jle L9 incr %edx jmp L10; L9: incr %eax L10:... 17 Summary of CC Setting Reading Implicit Arithmetic operations Explicit Cmp (-) Test (&) Set Jump 18

%eax 2 %ebx 3 Exercise What will be stored in %edx at the end of the following assembly code sequence? cmpl %ebx, %eax jl.l0 does this branch take? addl $0xA, %eax sall $2, %eax movl %eax, %edx.l0 leal (%eax,%eax,8), %edx addl %eax,%edx 19 Direct and Indirect Jump Direct Jump Target is encoded as part of the jump instruction e.g. je L1, jmp L2 Indirect Jump Target is read from a register or a memory location e.g. jmp *%eax jmp *(%eax) jmp *(%eax, %ecx, 4) Conditional jumps can only be direct!! 23 General Do-While Translation C Code do while (Test); can be any C statement Typically compound statement: Statement 1 ; Statement 2 ; Statement n ; Goto Version Test is expression returning integer = 0 interpreted as false 0 interpreted as true loop: if (Test) goto loop 24

While Loop Example #1 C Code int fact_while (int x) int result = 1; while (x > 1) result *= x; x = x-1; ; return result; First Goto Version int fact_while(int x) int result = 1; loop: if (!(x > 1)) goto done; result *= x; x = x-1; goto loop; done: return result; 25 Actual While Loop Translation C Code int fact_while(int x) int result = 1; while (x > 1) result *= x; x = x-1; ; return result; Uses same inner loop as do-while version Guards loop entry with extra test Second Goto Version int fact_while (int x) int result = 1; if (!(x > 1)) goto done; loop: result *= x; x = x-1; if (x > 1) goto loop; done: return result; 26 General While Translation C Code while (Test) Do-While Version if (!Test) goto done; do while(test); done: Goto Version if (!Test) goto done; loop: if (Test) goto loop; done: 27

int result; for ( result = 1; p!= 0; p = p>>1) if (p & 0x1) result *= x; x = x*x; For Loop Example for General Form (Init; Test; Update ) 28 For Version for(init;test;update ) Do-While Version Init; if (!Test) goto done; do Update ; while (Test) done: For While 29 While Version Init; while (Test ) Update ; Goto Version Init; if (!Test) goto done; loop: Update ; if (Test) goto loop; done: Goto Version Init; if (!Test) goto done; loop: Update ; if (Test) goto loop; done: Init result = 1 Update p = p >> 1 For Loop Compilation Test p!= 0 30 result = 1; if (p == 0) goto done; loop: if (p & 0x1) result *= x; x = x*x; p = p >> 1; if (p!= 0) goto loop; done: if (p & 0x1) result *= x; x = x*x;

C Code Example of While Loop int fact_while(int x) int result = 1; while (x > 1) result *= x; x = x-1; ; return result; Assembly Code movl 8(%ebp),%eax movl $1,%edx cmpl $1,%eax jle.l0.l1: imull %eax,%edx decl %eax cmpl $1,%eax jg.l1.l0: movl %edx,%eax 31 C Code Another Example of While Loop loop(int a, int b) int i=0; int result = a; while (i < 256) result += a; a -= b; i += b; ; return result; This code is compiled with Assembly Code movl 8(%ebp),%eax movl 12(%ebp),%ebx xorl %ecx,%ecx movl %eax,%edx.l1: addl %eax,%edx subl %ebx,%eax addl %ebx,%ecx cmpl $256,%ecx jl.l1 movl %edx,%eax 32 C Code int loop (int x, int y, int n) int result = 0; int i; for (i=n-1; i>=0; i=i-x) result += y*x; return result; Example of For Loop Assembly Code (with -O) movl 8(%ebp),%ebx movl 16(%ebp),%edx xorl %eax,%eax decl %edx js.l4 movl %ebx,%ecx imull 12(%ebp),%ecx.L6: addl %ecx,%eax subl %ebx,%edx jns.l6.l4: 34

typedef enum ADD,MULT,MINUS,DIV,MOD,BAD op_type; char symbol(op_type op) switch (op) case ADD : return '+'; case MULT: return '*'; case MINUS: return '-'; case DIV: return '/'; case MOD: return '%'; case BAD: return '?'; 36 Switch Statements Implementation Options Series of conditionals Good if few cases Slow if many Jump Table Lookup branch target Avoids conditionals Possible when cases are small integer constants GCC Picks one based on case structure Bug in example code No default given Switch Form switch(op) case 0: Block 0 case 1: Block 1 case n-1: Block n 1 Approx. Translation target = JTab[op]; goto *target; Jump Table Structure jtab: Jump Table Targ0 Targ1 Targ2 Targn-1 Targ0: Targ1: Targ2: Targn-1: Jump Targets Code Block 0 Code Block 1 Code Block 2 Code Block n 1 37 Branching Possibilities typedef enum ADD, MULT, MINUS, DIV, MOD, BAD op_type; char symbol(op_type op) switch (op) Setup: pushl %ebp # Setup movl %esp,%ebp # Setup movl 8(%ebp),%eax # eax = op cmpl $5,%eax # Compare op : 5 ja.l49 # If > goto done jmp *.L57(,%eax,4) # goto Table[op] 38 Enumerated Values ADD 0 MULT 1 MINUS 2 DIV 3 MOD 4 BAD 5

Switch Statement Example movl 8(%ebp),%eax # eax = op cmpl $5,%eax # Compare op : 5 ja.l49 # If > goto done jmp *.L57(,%eax,4) # goto Table[op] 1. Why the op is compared with 5? 2. What if the case values are from 10 to 200? 3. Why is ja used? Why not jg? 39 Remember Our Jumping Options jx Instructions Jump to different part of code depending on CC jx Condition Description jmp 1 Unconditional je ZF Equal / Zero jne ~ZF Not Equal / Not Zero js SF Negative jns ~SF Nonnegative jg ~(SF^OF)&~ZF Greater (Signed) jge ~(SF^OF) Greater or Equal (Signed) jl (SF^OF) Less (Signed) jle (SF^OF) ZF Less or Equal (Signed) ja ~CF&~ZF Above (unsigned) jb CF Below (unsigned) 40 Assembly Setup Explanation Symbolic Labels Labels of form.lxx translated into addresses by assembler Table Structure Each target requires 4 bytes Base address at.l57 Jumping jmp.l49 Jump target is denoted by label.l49 jmp *.L57(,%eax,4) Start of jump table denoted by label.l57 Register %eax holds op Must scale by factor of 4 to get offset into table Fetch target from effective Address.L57 + op*4 41

Table Contents.section.rodata.align 4.L57:.long.L51 #Op = 0.long.L52 #Op = 1.long.L53 #Op = 2.long.L54 #Op = 3.long.L55 #Op = 4.long.L56 #Op = 5 Enumerated Values ADD 0 MULT 1 MINUS 2 DIV 3 MOD 4 BAD 5 Jump Table Targets & Completion.L51: movl $43,%eax # + jmp.l49.l52: movl $42,%eax # * jmp.l49.l53: movl $45,%eax # - jmp.l49.l54: movl $47,%eax # / jmp.l49.l55: movl $37,%eax # % jmp.l49.l56: movl $63,%eax #? # Fall Through to.l49 42 Switch Statement Completion Puzzle What value returned when op is invalid? Answer:.L49: movl %ebp,%esp popl %ebp ret # Done: # Finish # Finish # Finish 43 Switch Statement Completion.L49: movl %ebp,%esp popl %ebp ret # Done: # Finish # Finish # Finish Puzzle What value returned when op is invalid? Answer Register %eax set to op at beginning of procedure This becomes the returned value Advantage of Jump Table Can do k-way branch in O(1) operations 44

Object Code Setup Label.L49 becomes address 0x804875c Label.L57 becomes address 0x8048bc0 08048718 <symbol>: 8048718: 55 pushl %ebp 8048719: 89 e5 movl %esp,%ebp 804871b: 8b 45 08 movl 0x8(%ebp),%eax 804871e: 83 f8 05 cmpl $0x5,%eax 8048721: 77 39 ja 804875c <symbol+0x44> 8048723: ff 24 85 c0 8b jmp *0x8048bc0(,%eax,4) 45 Object Code (cont.) Jump Table Doesn t show up in disassembled code Can inspect using GDB gdb code-examples (gdb) x/6xw 0x8048bc0 Examine 6 hexadecimal format words (4-bytes each) Use command help x to get format documentation 0x8048bc0 <_fini+32>: 0x08048730 0x08048737 0x08048740 0x08048747 0x08048750 0x08048757 46 Extracting Jump Table from Binary Jump Table Stored in Read Only Data Segment (.rodata) Various fixed values needed by your code Can examine with objdump objdump code-examples s -section=.rodata Show everything in indicated segment. Hard to read Jump table entries shown with reversed byte ordering Contents of section.rodata: 8048bc0 30870408 37870408 40870408 47870408 0...7...@...G... 8048bd0 50870408 57870408 46616374 28256429 P...W...Fact(%d) 8048be0 203d2025 6c640a00 43686172 203d2025 = %ld..char = % E.g., 30870408 really means 0x08048730 47

Disassembled Targets No-operations (movl %esi,%esi) inserted to align target addresses 8048730:b8 2b 00 00 00 movl $0x2b,%eax 8048735:eb 25 jmp 804875c <symbol+0x44> 8048737:b8 2a 00 00 00 movl $0x2a,%eax 804873c:eb 1e jmp 804875c <symbol+0x44> 804873e:89 f6 movl %esi,%esi 8048740:b8 2d 00 00 00 movl $0x2d,%eax 8048745:eb 15 jmp 804875c <symbol+0x44> 8048747:b8 2f 00 00 00 movl $0x2f,%eax 804874c:eb 0e jmp 804875c <symbol+0x44> 804874e:89 f6 movl %esi,%esi 8048750:b8 25 00 00 00 movl $0x25,%eax 8048755:eb 05 jmp 804875c <symbol+0x44> 8048757:b8 3f 00 00 00 movl $0x3f,%eax 48 Matching Disassembled Targets Entry 0x08048730 0x08048737 0x08048740 0x08048747 0x08048750 0x08048757 8048730: b8 2b 00 00 00 movl 8048735: eb 25 jmp 8048737: b8 2a 00 00 00 movl 804873c: eb 1e jmp 804873e: 89 f6 movl 8048740: b8 2d 00 00 00 movl 8048745: eb 15 jmp 8048747: b8 2f 00 00 00 movl 804874c: eb 0e jmp 804874e: 89 f6 movl 8048750: b8 25 00 00 00 movl 8048755: eb 05 jmp 8048757: b8 3f 00 00 00 movl 49 Summarizing C Control Conditions Codes if-then-else do-while while switch Assembler Control Jump / Indirect jump Conditional jump Compiler Must generate assembly code to implement more complex control CISC machines generally have condition code registers RISC machines use general registers to store condition information or use special comparison instructions Jump Table Implementation RISC architectures do not support indirect jump with memory operands. How is jump table implemented on such machines? 50

Casting and Promotions If (either operand == long double) both = long double Else if (either operand == double) both = double Else if (either operand == float) both = float Else if (either == unsigned long) both = unsigned long Else if ((one == long) && (other == unsigned)) if (bits(long) > bits(unsigned)) both = long else both = unsigned Else if (either == long) both = long Else if (either == unsigned) both = unsigned Else int 51 Precedence Operator ( ) ++(postfix) --(postfix) +(unary) -(unary) ++(prefix) (prefix) * / % + - < <= > >= ==!= && = += -= *= /= Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Right to left 52