learning assembly language in simple part2

Document Sample
learning assembly language in simple part2 Powered By Docstoc
					tamu CPSC321 Lec 03 mips2 .1   © UCB
                                   Texas A&M University
                                Computer Science Department
                               CPSC 321 Computer Architecture
                                             Part II
                                    Control Flow Statements

                               Instructor Michael E. Thomadakis
                www.cs.tamu.edu/course-info/cpsc321/miket
                     Adopted from notes by David A. Patterson and John
                                       Kubiatowicz
                                        Copyright © 2001
                               University of California at Berkeley


tamu CPSC321 Lec 03 mips2 .1                                             © UCB
         Recap (2/2)
         ° How to access memory?
                 • Load word:      lw
                    lw $t0, 32($s3)

             destination
                                offset      Base address

                 • address of memory word  base address + (byte) offset
                   (called Effective Memory Address or EA)
                 • offset must be a constant (not register)
                     - if zero, then base address register contains the
                       ``absolute'' address
         ° Store word (sw): like load word, except store 1st argument in
           memory




tamu CPSC321 Lec 03 mips2 .1                                               © UCB
          Do it yourself:


              ° Compile this C code into MIPS:
                               B[i] = h + A[i];
              ° Let h: $s2, i: $s4, $s3: base address of A,
              $s5: base address of B
               add $t1, $s4, $s4 # $t1 = 2*i
               add $t1, $t1, $t1 # $t1 = 4*i
               add $t2, $t1, $s3 # $t2 = addr A[i]
               lw $t0, 0($t2)           # $t0 = A[i]
               add $t0, $s2, $t0 # $t0 = h+A[i]
               add $t3, $t1, $s5 # $t3 = addr B[i]
               sw $t0, 0($t3)           # B[i]= h+A[i]




tamu CPSC321 Lec 03 mips2 .1                                  © UCB
        MIPS Instructions (Quick Summary)
                 Name               Example                                           Comments
                           $s0-$s7, $t0-$t9, $zero, Fast locations f or data. In MIPS, data must be in registers to perf orm
             32 regi sters $a0-$a3, $v0-$v1, $gp, arithmetic. MIPS register $zero alway s equals 0. Register $at is
                           $fp, $sp, $ra, $at       reserv ed f or the assembler to handle large constants.
                           Memory[0],               Accessed only by data transf er instructions. MIPS uses by te addresses, so
             230 memory Memory[4], ...,                        sequential words dif f er by 4. Memory holds data structures, such as array s,
             words          Memory[42 94967292]                and spilled registers, such as those sav ed on procedure calls.
                                                               MIPS assembly language
               Category               Instruction           Example                Meaning                                  Comments
                               add                   add $s1, $s2, $s3    $s1 = $s2 + $s3                       Three operands; data in registers


            Arithmetic         subtract              sub $s1, $s2, $s3          $s1 = $s2 - $s3                 Three operands; data in registers


                               add immediate        addi $s1, $s2, 100          $s1 = $s2 + 100                 Used to add constants
                               load word            lw $s1, 100($s2)            $s1 = Memory[$s2 + 100]         Word from memory to register
                               store word           sw $s1, 100($s2)            Memory[$s2 + 100] = $s1         Word from register to memory
            Data transfer      load byte            lb $s1, 100($s2)            $s1 = Memory[$s2 + 100]         Byte from memory to register
                               store byte           sb $s1, 100($s2)            Memory[$s2 + 100] = $s1         Byte from register to memory
                               load upper im ediate lui $s1, 100
                                            m                                   $s1 = 100 * 2
                                                                                               16               Loads constant in upper 16 bits


                               branch on equal       beq    $s1, $s2, 25        if ($s1 == $s2 ) go to          Equal test; PC-relative branch
                                                                                PC + 4 + 100

                               branch on not equal   bne    $s1, $s2, 25        if ( $s1 != $s2 ) go to         Not equal test; PC-relative
                                                                                PC + 4 + 100
            Conditional
            branch             set on less than      slt    $s1, $s2, $s3       if ( $s2 < $s3 ) $s1 = 1;       Compare less than; for beq, bne
                                                                                else $s1 = 0

                               set less than         slti   $s1, $s2, 100       if ( $s2 < 100 ) $s1 = 1;       Compare less than constant
                               immediate                                        else $s1 = 0

                               jump                  j      2500                go to 10000               Jump to target address
            Uncondi-           jump register         jr     $ra                 go to $ra                 For switch, procedure return
            tional jump        jump and link         jal    2500                $ra = PC + 4; go to 10000 For procedure call
tamu CPSC321 Lec 03 mips2 .1                                                                                                                        © UCB
          Instructions as Numbers

         ° Hardware stores digital information in binary digits (bits)
            • stored as series of high and low electrical signals
              (voltages, currents).
         ° Binary numbers are a convenient representation for
           digital information.
         ° Information can be interpreted as machine instructions
           or data.
         ° Must convert Assembly Language Instructions into
           binary numbers (Machine Language)
                • Done by the Assembler

         ° Means must turn instruction operation names, offsets,
           register names into binary numbers




tamu CPSC321 Lec 03 mips2 .1                                             © UCB
          Register Names as Numbers (page A-23)

     ° Set of 32 MIPS registers sometimes called the processor’s register
       file
     ° Processor accesses register file by supplying register number (like
       array index).
     ° Register Naming
     Register Type          Register Names Register No.
     Temporary registers $t0-$t7        8 - 15
     Saved registers        $s0-$s7         16 - 23
     Temporary registers    $t8-$t9         24 - 25

     ° What about all the rest? ($v0, $v1, $a0, $a1, ...)
       Will be defined shortly




tamu CPSC321 Lec 03 mips2 .1                                             © UCB
          Instruction as Number Example (decimal)

             ° C code: i = j + k; /* i-k:$s0-$s2 */
             ° Assembly: add $s0,$s1,$s2 #s0=s1+s2
             ° Decimal representation of ``R type'' machine instruction:


         0                     17   18    16        0        32
                    • Segments are called fields
                                                                  Order
                    • 1st and last tell MIPS computer to add     differs:
                    • 2nd is 1st source operand (17 = $s1)         desti-
                    • 3rd is 2nd source operand (18 = $s2)        nation
                    • 4th is destination operand (16 = $s0) 1st vs. last!
                    • 5th unused, so set to 0                 (common
                                                                   error)


tamu CPSC321 Lec 03 mips2 .1                                                © UCB
          Numbers: Review
         ° Number Base B  B symbols per position (digit):
            • Base 10 (Decimal, B = 10): { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
              }
                • Base 2 (Binary, B = 2):      { 0, 1 }
         ° Number representation in base B=10: d4d3d2d1d0
                • d4 ×B4 + d3 × B3 + d2 × B2 + d1 × B1 + d0 × B0
                • 1001010 = 1×104 + 0×103 + 0×102+ 1×101+ 0×100
                   = 1×10000 + 0×1000 + 0×100 + 1×10 + 0×1
                   = 10000 + 0 + 0 + 10 + 0
                   = 1001010
                • 100102 = 1×24 + 0×23 + 0×22 + 1×21 + 0×20
                   = 1×16 + 0×8 + 0×4 + 1×2 + 0×1
                   = 1610 + 010 + 010 + 210 + 010
                   = 1810




tamu CPSC321 Lec 03 mips2 .1                                              © UCB
          Instruction as Number Example (binary)
      ° C code: i = j + k; /* i-k: $s0-$s2 */

      ° Assembly: add $s0, $s1, $s2 # s0=s1+s2
      ° Decimal representation (R-type instruction):

                   0           17   18        16        0         32
      ° Binary representation:



          000000 10001 10010 10000 00000 100000
           • Called 5 bits 5 bits 5 bits
          6 bits Machine Language Instruction5 bits 6 bits
             • Layout called Instruction Format
             • All MIPS instructions 32 bits (1 word) for simplicity




tamu CPSC321 Lec 03 mips2 .1                                           © UCB
          Big Idea: Stored-Program Concept

          ° Computers built on 2 key principles:
          1) Instructions are represented as numbers (binary
            quantities)
          2) Programs can be stored in memory to be read or
           written just like numbers
          ° Machine for accounting can help write a book; just
            load memory with program & data, & start executing
            at given address
          ° Simplifies SW/HW of computer systems:
                 • Memory technology for data is also used for
                   programs
                 • Compilers translate HLL code (data) into machine
                   code (instructions)




tamu CPSC321 Lec 03 mips2 .1                                          © UCB
          Big Consequence #1: Everything addressed

          ° Since all instructions and data are stored in memory
            as numbers, everything has a memory address:
            instructions, data words
          ° C pointers are just memory addresses: they can
            point to anything in memory
                 • Unconstrained use of addresses can lead to
                   nasty bugs; up to you in C; limits in Java
          ° Special register keeps address of instruction being
            executed: "Program Counter" (PC)
                 • Better name is Instruction Address Register, but
                   PC is traditional name




tamu CPSC321 Lec 03 mips2 .1                                          © UCB
          Big Consequence #2: Binary Compatibility

          ° Programs often distributed in binary form
              • Binary programs are bound to the instruction set
                architecture
                 • Different versions for Macintosh and IBM PC
          ° New machines want to run old programs ("binaries")
            as well as programs compiled to new instructions
          ° Leads to instruction set evolving over time
          ° Selection of Intel 8088 in 1981 for 1st IBM PC is
            major reason latest (Pentium IV) PCs still use 80x86
            instruction set; could still run program from 1981 PC
            today




tamu CPSC321 Lec 03 mips2 .1                                        © UCB
          MIPS Instruction Format and Field Names
              • Instruction fields have names (R-type Instruction):


              op                 rs     rt         rd shamt funct
            6 bits             5 bits 5 bits     5 bits 5 bits 6 bits
              • op: basic operation of instruction, "opcode"
              • rs:        1st register source operand
              • rt:        2nd register source operand
              • rd:        register destination operand, gets the result
              • shamt: shift amount (use later, so 0 for now)
              • funct: function; selects the specific variant of the operation
                in the op field; sometimes called the function code




tamu CPSC321 Lec 03 mips2 .1                                                     © UCB
          Instruction Formats
          ° What if we want longer fields? e.g., offset in lw
            • 5 bits  address of 25 or 32  too small
            • But want all instructions same length!
          ° Principle: Good design demands good compromises
             • Add 2nd format with larger address (offset)

     R:              op           rs     rt       rd shamt funct
                   6 bits       5 bits 5 bits   5 bits 5 bits 6 bits
              • 1st R (register) format; 2nd I (immediate) format



    I:            op              rs       rt          address
                6 bits         5 bits 5 bits         16 bits



tamu CPSC321 Lec 03 mips2 .1                                           © UCB
         Notes about Register and Immediate Formats

          ° To make it easier for hardware (HW), first three fields
            same in R-format and I-format
          ° Alas, rt field meaning changed
             • R-format: rt is 2nd source operand
             • I-format: rt can be destination operand
          ° How does HW know which format is which?
             • Distinct values in 1st field (op) tell whether last 16
               bits are 3 fields (R-format) or 1 field (I-format)


    R:                  op      rs      rt     rd     shamt funct

    I:               op          rs     rt              address
                   6 bits      5 bits 5 bits          16 bits



tamu CPSC321 Lec 03 mips2 .1                                            © UCB
          Instructions, Formats, “opcodes”

                 Instruction Format        Op   Funct
                 add           Register    0    32
                 sub           Register    0    34    Register
                 lw            Immediate   35          Format
                 sw            Immediate   43        if op field
                                                         =0
                 ° Back inside cover of textbook gives machine code
                   for all MIPS instructions we will study




tamu CPSC321 Lec 03 mips2 .1                                          © UCB
          Administrivia

          ° Readings for next Monday: finish 3.6, start 3.7
             • 3.6 is hard topic (procedures)




tamu CPSC321 Lec 03 mips2 .1                                  © UCB
          "Computers in the news"


                                             Computer scientists have created a robot that
        Houston Chronicle, August 31         designs and builds other robots almost entirely
                                             without human help or expertise….the automatons
                                             have the ability to crawl slowly….The computer in
                                             the Brandeis system was … merely given a list of
                                             possible parts it could work with, the physical laws
                                             of gravity and friction, the goal of moving on a
                                             horizontal surface and a group of 200 randomly
                                             constructed nonworking designs. Mimicking
                                             biological evolution, the computer added,
                                             subtracted, and changed pieces in the designs.
                                             After each step, the computer ran simulations to
                                             test the designs, keeping the ones that moved well
                                             and discarding the others.




   According to scientists, the robots
   now have the brain power of
   bacteria. "We hope to get up to the
   insect level within a couple of years."


tamu CPSC321 Lec 03 mips2 .1                                                                        © UCB
          Assembly Constants
        ° C expressions can have constants:
                               i = i + 10;
        ° How to get them using instructions so far?
           • Keep constants in memory with program
        lw    $t0, 0($s0)        # load 10 from memory
        add $s3, $s3, $t0 # i = i + 10
        ° Because so common, have instructions to add constants
          (called "immediate instructions")
        addi $s3, $s3, 10       # i = i + 10




tamu CPSC321 Lec 03 mips2 .1                                      © UCB
        Assembly Constants

          ° Why include immediate instructions?
             • Design principle: Make the common case fast
                 • Why faster?
                        - Don’t need to access memory
                        - 2 instructions vs. 1 instruction

          ° Also, perhaps most popular constant is zero
              • MIPS designers reserved 1 of 32 registers to always
                have the value 0; it’s called "$zero" ($0)
                 • Useful in making additional operations from existing
                   instructions; e.g., $s0  $s1
          add $s0, $s1, $zero                # $s0 = $s1 + 0




tamu CPSC321 Lec 03 mips2 .1                                              © UCB
          Immediate Instruction in Machine Code

          ° C:                 i = j + 4; /* i,j:$s0,$s1 */
          ° MIPS:              addi $s0, $s1, 4 # $s0 = $s1 + 4
          ° Instruction Format:

     I:           op                rs       rt        address
                6 bits           5 bits 5 bits       16 bits
          ° Machine Code (decimal representation):

     I:         8                 17       16                 4
                6 bits           5 bits 5 bits      16 bits
          ° Machine Code (binary representation):

              001000 10001 10000 0000 0000 0000 0100
              6 bits  5 bits 5 bits      16 bits

tamu CPSC321 Lec 03 mips2 .1                                      © UCB
        So Far...


        ° All instructions have allowed us to manipulate data.
        ° So we’ve built a calculator.
        ° To build a computer, we need ability to make decisions…
        ° Heads up: pull out some papers and pens, you’ll do some
          in-class exercises today!




tamu CPSC321 Lec 03 mips2 .1                                        © UCB
      C Decisions (Control Flow) Statements
 ° All “block-structured” languages (C, Pascal, ADA, etc.) support flow of
   control statements, including the following:
 ° Conditional statements in C (if)
 if (condition) statement
 if (condition) statement1 else statement2
 if (condition) statement1
 else if (condition) statement2
 else if (condition) statement3 . . .
 else statementk
 ° Iteration Statements in C (Loops):
 while (condition) statement-block
 for (init; loop condition; update)
  statement-block
 do statement-block while (condition)
 ° Multi-way Branching (“switch” statements)
 ° Unconditional branching (“goto” statements); Harmful; Not
   recommended for general use; “spaghetti code”

tamu CPSC321 Lec 03 mips2 .1                                            © UCB
         C Decisions: if statements
          ° 2 kinds of if statements in C :
                 • if (condition) statement
                 • if (condition) statement1 else statement2
          ° Following code is same as 2nd if:
             if        (condition) go to L1;
                       statement2;
                       go to L2;
             L1: statement1;
             L2:
                 • Not as elegant as if-else, but same meaning




tamu CPSC321 Lec 03 mips2 .1                                     © UCB
          MIPS Decision Instructions (Control Flow)
  ° Decision instruction in MIPS:
     • beq register1, register2, L1
         • beq is "Branch if (registers are) equal"; with alternate
      notation:
  if (register1 == register2) go to L1 (using C)
  if (R[1] == R[2]) go to L1               (Register Transfer)
  ° Complementary MIPS decision instruction
     • bne register1, register2, L1
         • bne is "Branch if (registers are) not equal"
  if (register1 != register2) go to L1 (using C)
  if (R[1] != R[2]) go to L1               (Register Transfer)
  ° Called conditional branches




tamu CPSC321 Lec 03 mips2 .1                                          © UCB
         MIPS Goto Instruction

     ° In addition to conditional branches, MIPS has an
       unconditional branch:

                   j label
     ° Called a Jump Instruction: jump (or branch) directly to the
       given label without requiring to satisfy any logical condition
     ° Same meaning as (using C):

                   goto label
     ° Technically, it’s the same as:

                   beq         $0, $0, label
     since it always satisfies the condition.




tamu CPSC321 Lec 03 mips2 .1                                            © UCB
          Compiling C if into MIPS Assembly
 ° Compile by hand:
 Mapping f: $s0, g: $s1,                 (true)               (false)
                                                      i == j?
  h: $s2, i: $s3, j: $s4                  i == j                i != j

 if (i == j) f = g + h;                       f=g+h        f=g-h
 else f = g - h;
                                                       Exit
 ° Start with branch:
 beq $s3, $s4, True # branch to True
                  # if (i == j)
 ° Follow with false part
 sub $s0, $s1, $s2               # f=g-h (skip if i==j)



tamu CPSC321 Lec 03 mips2 .1                                             © UCB
          Compiling C if into MIPS Assembly
          ° Next must skip over true part
             • Need instruction that always branches (unconditional
               branch)
               • MIPS has jump:
          j Exit                   # go to Exit
          ° Next is true part
          True:
          add $s0, $s1, $s2 # f = g + h
          ° Followed by exit branch label
          Exit:




tamu CPSC321 Lec 03 mips2 .1                                          © UCB
          Compiling C if into MIPS: Summary
            °Compile by hand
                                                (true)            (false)
            if (i == j)                                   i == j?
                                                 i == j             i != j
                f = g+h;

       C else            f = g-h;
                                                  f=g+h        f=g-h
            Mapping f: $s0, g: $s1,
            h: $s2, i: $s3, j: $s4

                                                           Exit

      M     beq                $s3, s4, true # branch i==j
      I     sub                $s0, $s1, $s2 # f=g-h (false)
            j                  Exit          # go to Exit
      P true:
      S     add                $s0, $s1, $s2 # f=g+h (true)
            Exit:

            ° Note: Compiler supplies labels, branches not found in HLL
            code; often it flips the condition to branch to false part

tamu CPSC321 Lec 03 mips2 .1                                                 © UCB
          Loops in C/Assembly

    ° Simple loop in C:
    do
    {
      g = g + A[i]; i = i + j;
    } while (i != h);
    ° Rewrite this as:
    Loop: g = g + A[i];
                         i = i + j;
                         if (i != h) goto Loop;
    ° Let g, h, i, j: $s1, $s2, $s3, $s4;

    ° Base of A[]: $s5

tamu CPSC321 Lec 03 mips2 .1                      © UCB
          Loops in C /Assembly
          ° Fetch A[i]

          Loop: add $t1, $s3, $s3            # $t1 = 2*i
             add $t1, $t1, $t1               # $t1 = 4*i
             add $t1, $t1, $s5               # $t1 = addr A
             lw         $t1, 0($t1)          # $t1 = A[i]
          ° Add A[i] to g and then j to i
          ° g, h, i, j: $s1, $s2, $s3, $s4
          add           $s1, $s1, $t1   # g = g + A[i]
          add           $s3, $s3, $s4   # i = i + j
          ° The final instruction branches back to Loop if i != h :
          bne $s3, $s2, Loop            # goto Loop if i!=h


tamu CPSC321 Lec 03 mips2 .1                                          © UCB
         Loops in C/Assembly: Summary

              Loop:
      C
              g = g + A[i];
              i = i + j;
              if (i != h) goto Loop;
              Let (g, h, i, j: $s1, $s2, $s3, $s4; base of A[]: $s5):
              Loop:
     M        add $t1,         $s3, $s3         #   $t1 =   2*i
     I        add $t1,         $t1, $t1         #   $t1 =   4*i
              add $t1,         $t1, $s5         #   $t1 =   addr A
     P        lw $t1,          0($t1)           #   $t1 =   A[i]
     S        add $s1,         $s1, $t1         #   g = g   + A[i]
              add $s3,         $s3, $s4         #   i = i   + j
              bne $s3,         $s2, Loop   # goto   Loop
                                           # if i   != h




tamu CPSC321 Lec 03 mips2 .1                                            © UCB
         while in C/Assembly:
         ° Although legal C, we almost never write loops with if,
           goto: use while, for loops
             • why?
         ° Syntax: while(condition) statement
         while (save[i]==k)
             i = i + j;
         ° 1st load save[i] into a temporary register
         (i, j, k: $s3, $s4, $s5; base of save[]: $s6):
         Loop:
         add $t1,$s3,$s3            # $t1 = 2*i
         add $t1,$t1,$t1            # $t1 = 4*i
         add $t1,$t1,$s6            # $t1 = Addr
         lw $t1,0($t1)              # $t1 = save[i]




tamu CPSC321 Lec 03 mips2 .1                                        © UCB
          while in C/Assembly:
          ° Loop test, exiting if (save[i] != k ) ;
          ° Let i, j, k: $s3, $s4, $s5; base of save[]: $s6 ;
          bne $t1, $s5, Exit            # goto Exit
                                    # if save[i]!= k
          ° The next instruction adds j to i:
          add           $s3, $s3, $s4   # i = i + j
          ° End of loop branches back to the while test at top of
            loop. Add the Exit label after:
          j Loop               # goto Loop

          Exit:




tamu CPSC321 Lec 03 mips2 .1                                        © UCB
          while in C/Assembly: Summary

                while (save[i]==k)
      C                   i = i + j;
             ( i, j, k: $s3, $s4, $s5; base of save[]: $s6 )
             Loop: add            $t1,$s3,$s3    # $t1 = 2*i
                   add            $t1,$t1,$t1         # $t1 = 4*i
                   add            $t1,$t1,$s6         # $t1 = Addr
      M            lw             $t1,0($t1)     # $t1 = save[i]
                   bne            $t1,$s5,Exit        # goto Exit
      I
                                                 # if save[i]!=k
      P
      S         add $s3,$s3,$s4                  # i = i + j
                  j            Loop              # goto Loop
             Exit:




tamu CPSC321 Lec 03 mips2 .1                                         © UCB
         Loops in C/Assembly

       ° Three types of loops in C:
              • while
              • do… while
              • for
       ° Each can be rewritten as either of the other two, so the
         method used in the previous example can be applied to
         while and for loops as well.
       ° Key Concept: Though there are multiple ways of writing a
         loop in MIPS, conditional branch is key to decision making




tamu CPSC321 Lec 03 mips2 .1                                          © UCB
Other Iteration Statements
 ° for — next loops: compute the loop body while iteration-condition
   is true.
° for ( init ; iter-condition ; step )
  {
     loop_body;
  }
° Equivalent to:
   init ;
   while ( iter-condition )
   {
      loop_body;
      step ;
   }
° Use the while-loop method.
tamu CPSC321 Lec 03 mips2 .1                                     © UCB

				
DOCUMENT INFO
Shared By:
Stats:
views:145
posted:3/20/2012
language:
pages:38
Description: learn in simple how to deal with assembly language and control of all programs and can crack it and be cracker